# maximal slice
def slow_max_slice(A):
    n = len(A)
    result = 0
    for i in range(n):
        for j in range(i, n):
            sum = 0
            for t in range(i, j+1):
                sum += A[t]
            result = max(sum, result)
    return result
print(slow_max_slice([5,-7,3,5,-2,4,-1]))

def prefix_sums(A):
    n = len(A)
    P = [0] * (n+1)
    for i in range(1, n+1):
        P[i] = P[i-1] + A[i-1]
    return P

def quad_max_slice(A):
    n = len(A)
    pref = prefix_sums(A)
    result = 0
    for i in range(n):
        for j in range(i, n):
            sum = pref[j+1] - pref[i]
            result= max(sum, result)
    return result

print(quad_max_slice([5,-7,3,5,-2,4,-1]))

def golden_max_slice(A):
    max_ending = max_slice = 0
    for a in A:
        max_ending = max(0, max_ending + a)
        max_slice = max(max_ending, max_slice)
    return max_slice
print(golden_max_slice([5,-7,3,5,-2,4,-1]))

# 1. MaxProfit
# Given a log of stock prices compute the maximum possible earning.
def MaxProfit0(A):
    # write your code in Python 3.6
    n = len(A)
    if n <= 1 and n > 400000:
        return 0
    max_profit_from = A[n-1]
    max_profit = 0
    for i in range(n-2, -1, -1):
        max_profit = max(max_profit, max_profit_from - A[i])
        max_profit_from = max(A[i], max_profit_from)
    return max_profit
# print(MaxProfit0([]))

def MaxProfit(A):
    max_ending = max_slice = 0
    for i in range(1, len(A)):
        max_ending = max(0, max_ending + A[i] - A[i - 1])
        max_slice = max(max_slice, max_ending)
    return max_slice
print(MaxProfit([]))

# 2. MaxSliceSum
# Find a maximum sum of a compact subsequence of array elements.
def MaxSliceSum(A):
    # write your code in Python 3.6
    max_ending = 0
    max_slice = -1000000
    for a in A:
        max_ending = max([-1000000, max_ending + a, a])
        max_slice = max(max_ending, max_slice)
    return max_slice
print(MaxSliceSum([-2,1]))

# 3. MaxDoubleSliceSum
# Find the maximal sum of any double slice.
def MaxDoubleSliceSum(A):
    N = len(A)
    A1 = [0]*N
    A2 = [0]*N
    maxCurrent = 0
    maxTotal = 0
    for i in range(1,N-1):
        A1[i] = maxCurrent = max( 0, maxCurrent + A[i] )
    maxCurrent = 0
    for i in range(N-2,0,-1):
        A2[i] = maxCurrent = max( 0, maxCurrent + A[i] )
    for i in range(1,N-1):
        maxTotal = max( maxTotal, A1[i-1] + A2[i+1] )
    return maxTotal
print(MaxDoubleSliceSum([0, -10, -5, -5, 3, 0]))
# Basic idea is that any max double slice is build around some local minimum, this code is trying to consider
# new element  A[i] as a new local minimum. maxdCand2 is new max double candidate without A[i] but with
# last known local minimum (minElem). Also we keep track of total sum without local minimum, if it is
# greater, assign it as a new maxDouble and consider A[i] as new local minimum (or 0 if maxDouble is
# negative)
def MaxDoubleSliceSum0(A):
    maxCurrent = 0
    maxDouble = 0
    maxTotal = 0
    minElem = A[1]
    # reserve the very first and last elements, as they can't be count in this task
    for i in range(2,len(A)-1):
        # compare sum without current min elemnt and
        # without current element. If the later more, current
        # element becomes current min element
        maxdCand2 = maxDouble + minElem
        maxDouble = maxDouble + A[i]
        if maxdCand2 >= maxDouble:
            # got new min element
            minElem = A[i]
            maxDouble = maxdCand2
        # Also keep track of max current without min element
        # If maxDouble less, assing the bigger
        if maxDouble <= maxCurrent:
            maxDouble = maxCurrent
            minElem = A[i] if maxDouble > 0 else 0
        maxCurrent = max( 0, maxCurrent + A[i] )
        maxTotal = max( maxTotal, maxDouble )
    return maxTotal
print(MaxDoubleSliceSum0([0, -10, -5, -5, 3, 0]))


import sys
import json
import requests

class Connection:
    def __init__(self, verbose, room, name):
        self.verbose = verbose
        self.room = room
        self.name = name
        self.nameRequired = False
        self.activityID = None
        self.activityInstanceID = None
        self.authToken = None
        self.questions = None

        self.print('Connecting to {}... '.format(self.room), newline=False)
        self.getActivityIds()
        self.print('Done!')

        self.print('Authenticating... ', newline=False)
        self.getAuthToken()
        self.print('Done!')

        self.print('Retrieving questions... ', newline=False)
        self.getQuestions()
        self.print('Done!')

    def print(self, s, newline=True):
        if self.verbose:
            if newline:
                print(s)
            else:
                print(s, end='')

    def isNameSet(self):
        return self.name is not '' and self.name is not None

    def getActivityIds(self):
        r = requests.get('https://api.socrative.com/rooms/api/current-activity/{}'.format(self.room))
        response = r.json()

        if r.status_code != 200:
            sys.exit('Invalid room name')

        self.activityID = response['activity_id']
        self.activityInstanceID = response['id']

        for setting in response['settings']:
            if setting['key'] == 'require_names':
                self.nameRequired = setting['value'] == 'True'
                break

    def getAuthToken(self):
        data = {'role': 'student', 'name': self.room, 'tz_offset': -60}
        r = requests.post('https://api.socrative.com/rooms/api/join/', data)

        self.authToken = r.headers['Set-Cookie'].split(';')[0][3:]

    def getQuestions(self):
        params = {'room_name': self.room}
        cookies = {'sa': self.authToken}
        r = requests.get('https://api.socrative.com/quizzes/api/quiz/{}'.format(self.activityID), params, cookies=cookies)

        self.questions = json.loads(r.content)['questions']

    def setName(self):
        self.print('Setting name... ', newline=False)

        data = {'activity_instance_id': self.activityInstanceID, 'student_name': self.name}
        cookies = {'sa': self.authToken}

        requests.post('https://api.socrative.com/students/api/set-name/', data=json.dumps(data), cookies=cookies)

        self.print('Done!')

    def sendAnswer(self, answers, _type):
        answerList = list(answers.keys())
        if len(answers) == 0:
            sys.exit('')

        cookies = {'sa': self.authToken}
        questionID = answerList[0]
        data = {'question_id': questionID, 'activity_instance_id': self.activityInstanceID}

        if _type == 'MC':
            selectionAnswers = [{'answer_id': answer_id} for answer_id in answers[questionID]]
            answer_ids = ','.join(str(e) for e in answers[questionID])

            data['selection_answers'] = selectionAnswers
            data['answer_ids'] = answer_ids

        elif _type == 'SC':
            data['selection_answers'] = answers[questionID]
            data['answer_ids'] = str(answers[questionID])

        else:
            data['text_answers'] = [{'answer_text': answers[questionID]}]
            data['answer_text'] = answers[questionID]

        requests.post('https://api.socrative.com/students/api/responses/', data=json.dumps(data), cookies=cookies)


def solution(s):
    s = ' '+s
    answer = ''
    print(s)
    for w in range(1, len(s)):
        a = s[w]
        if s[w-1] == ' ':
            a = s[w].upper()
        else:
            a = s[w].lower()
        answer += a
    return answer

프로그래머스/lv2/12951. JadenCase 문자열 만들기/JadenCase 문자열 만들기.py


#! /usr/bin/env mpcpython
"""
    Autor : Barish Chandran B
    Description : PyQt4 custom combobox for selecting multiple options.
    Created : Aug 10, 2012
    Email : barishcb@hotmail.com
"""
from PyQt4 import QtGui, QtCore

class MultiCheckComboBox(QtGui.QComboBox):
    """ Class definition for the custom QComboBox that can select multiple
        options using check-box.
    """
    def __init__(self, parent=None):
        """ Initialization for MultiCheckComboBox class.

            Args:
                parent (QWidget): parent widget to which the table is attached.
        """
        super(MultiCheckComboBox, self).__init__(parent)

        self._model = MultiCheckComboModel(self)
        self._lineEdit = QtGui.QLineEdit()
        self._listView = self.view()
        self._separator = ', '
        self._defaultText = 'Filter Revisions'
        self._selectAllText = 'Filtering All'
        self._maxTextLength = 42
        self._checkedItems = []

        self.setModel(self._model)
        self.setLineEdit(self._lineEdit)
        self.setInsertPolicy(QtGui.QComboBox.NoInsert)
        self._lineEdit.setReadOnly(True)

        self._lineEdit.installEventFilter(self)
        self._listView.installEventFilter(self)
        self._listView.window().installEventFilter(self)
        self._listView.viewport().installEventFilter(self)
        self.installEventFilter(self)

        self.connect(self,
                    QtCore.SIGNAL('activated(int)'),
                    self.toggleCheckState)
        self.connect(self._model,
                    QtCore.SIGNAL('checkStateChanged()'),
                    self.updateCheckedItems)
        self.connect(self._model,
                    QtCore.SIGNAL('rowsInserted(const QModelIndex&,int,int)'),
                    self.updateCheckedItems)
        self.connect(self._model,
                    QtCore.SIGNAL('rowsRemoved(const QModelIndex&,int,int)'),
                    self.updateCheckedItems)
        self.connect(self,
                    QtCore.SIGNAL('clearAll()'),
                    self.clearAllEvent)
        self.connect(self,
                    QtCore.SIGNAL('checkAll()'),
                    self.checkAllEvent)

    def defaultText(self):
        """ Function to get the default text of ComboBox.

            Returns:
                (str) return the default text.
        """
        return self._defaultText

    def setDefaultText(self, text):
        """ Function to set the default text of ComboBox.

            Args:
                text (str):  string for default text
        """
        self._defaultText = text
        self.updateCheckedItems()

    def selectAllText(self):
        """ Function to get value of when all the items selected.

            Returns:
                (str) return the select all text.
        """
        return self._selectAllText

    def setSelectAllText(self, text):
        """ Function to set the value to display when all the items selected.

            Args:
                text (str):  string for select all text.
        """
        self._selectAllText = text
        self.updateCheckedItems()

    def itemCheckState(self, index):
        """ Function to get the check state of the given item.

            Args:
                index (QModelIndex): Model index of the item.
        """
        if self._model.itemData(index, QtCore.Qt.CheckStateRole).toInt():
            return QtCore.Qt.Checked
        else:
            return QtCore.Qt.UnChecked

    def setItemCheckState(self, index, state):
        """ Function to set the check state of the given item.

            Args:
                index (QModelIndex): Model index of the item.
                state (QCheckState): Check state of the item.
        """
        checkState = QtCore.Qt.Checked if state else QtCore.Qt.Unchecked
        self._model.setItemData(index,
                                checkState,
                                QtCore.Qt.CheckStateRole)

    def separator(self):
        """ Function to get the separator text for the ComboBox.

            Returns:
                (str) return combobox's separator
        """
        return self._separator

    def setSeparator(self, separator):
        """ Function to get the separator text for the ComboBox.

            Args:
                separator (str): Separator as string.
        """
        self._separator = separator
        self.updateCheckedItems()

    def maxTextLength(self):
        """ Function to get the maximum length that display on the ComboBox.

            Returns:
                (int) Return combobox's maximum display length
        """
        return self._maxTextLength

    def setMaxTextLength(self, length):
        """ Function to set the maximum length that display on the ComboBox.

            Args:
                length (int): Combobox's maximum display length.
        """
        self._maxTextLength = length
        self.updateCheckedItems()

    def checkedItems(self):
        """ Function to get the checked items label as list.

            Returns:
                (QStringList) list of item labels.
        """
        itemList = QtCore.QStringList()
        if self._model:
            modelIndex = self._model.index(0,
                                            self.modelColumn(),
                                            self.rootModelIndex())
            modelIndexList = self._model.match(modelIndex,
                                                QtCore.Qt.CheckStateRole,
                                                QtCore.Qt.Checked,
                                                -1,
                                                QtCore.Qt.MatchExactly)
            for mIndex in modelIndexList:
                itemList << mIndex.data().toString()
        return itemList

    def uncheckedItems(self):
        """ Function to get the checked items label as list.

            Returns:
                (QStringList) list of item labels.
        """
        itemList = QtCore.QStringList()
        if self._model:
            modelIndex = self._model.index(0,
                                            self.modelColumn(),
                                            self.rootModelIndex())
            modelIndexList = self._model.match(modelIndex,
                                                QtCore.Qt.CheckStateRole,
                                                QtCore.Qt.Unchecked,
                                                -1,
                                                QtCore.Qt.MatchExactly)
            for mIndex in modelIndexList:
                itemList << mIndex.data().toString()
        return itemList

    def setCheckedItems(self, items):
        """ Function to set the checked state for the given items.

            Args:
                items (QStringList): list of item labels.
        """
        for item in items:
            index = self.findText(item)
            state = QtCore.Qt.Unchecked if index == -1 else QtCore.Qt.Checked
            self.setItemData(index, state, QtCore.Qt.CheckStateRole)

    def checkAll(self, check=False):
        """ Function to set all the items as checked or unchecked based on
            the argument.

            Args:
                check(bool): Check State.

            Returns:
                (list) : list of items Checked or UnChecked based
                        on the status.
        """
        itemList = QtCore.QStringList()
        searchState = QtCore.Qt.Checked
        assignState = QtCore.Qt.Unchecked
        if check:
            searchState = QtCore.Qt.Unchecked
            assignState = QtCore.Qt.Checked
        if self._model:
            modelIndex = self._model.index(0,
                                            self.modelColumn(),
                                            self.rootModelIndex())
            modelIndexList = self._model.match(modelIndex,
                                            QtCore.Qt.CheckStateRole,
                                            searchState,
                                            -1,
                                            QtCore.Qt.MatchExactly)
            for mIndex in modelIndexList:
                self.setItemData(mIndex.row(),
                                assignState,
                                QtCore.Qt.CheckStateRole)
        return itemList

    def trimDisplayText(self, text):
        """ Function to trim the display text base on the max length property.

            Args:
                text (str):  Text to be trimmed.

            Returns:
                (str) : Trimmed text.
        """
        textLength = self._maxTextLength - 3
        if (self._maxTextLength and
            self._maxTextLength > 3 and
            len(text) > textLength):
            text = '%s...' % text[:textLength]
        return text

    def setEditText(self, text):
        """ Override the setEditText function.

            Args:
                text (str): default text for the ComboBox.
        """
        super(MultiCheckComboBox, self).setEditText(self.trimDisplayText(text))

    def reloadPopup(self):
        """ Function to reload the popup of the Combobox.
        """
        currentIndex = self._listView.currentIndex()
        scrollValue = self._listView.verticalScrollBar().value()
        self.showPopup()
        self._listView.setCurrentIndex(currentIndex)
        self._listView.verticalScrollBar().setValue(scrollValue)

    def keyPressEvent(self, event):
        """ Function to override key press event.

            Args:
                event (QEvent):  Any KeyPress Event.
        """
        if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
            pass

    def eventFilter(self, obj, event):
        """ Function to filter out the unwanted events and add new
            functionalities for it.

            Args:
                obj (QWidget):  List of strings that shows in QCompleter
                event (QEvent):  Event to be filtered.

            Returns:
                (bool) return the status in boolean.
        """
        eventType = event.type()
        if eventType == QtCore.QEvent.KeyPress:
            return False
        if eventType == QtCore.QEvent.KeyRelease:
            eventKey = event.key()
            if (obj in (self, self._listView, self._lineEdit)
                and eventKey in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down)):
                self.reloadPopup()
                return False
            elif obj == self._listView and eventKey == QtCore.Qt.Key_Space:
                self.reloadPopup()
                return True
            elif obj == self._listView and eventKey in (QtCore.Qt.Key_Enter,
                                                        QtCore.Qt.Key_Return,
                                                        QtCore.Qt.Key_Escape,
                                                        QtCore.Qt.Key_Tab):
                self.hidePopup()
                return True
        if eventType == QtCore.QEvent.MouseButtonPress:
            return False
        if eventType == QtCore.QEvent.MouseButtonRelease:
            eventButton = event.button()
            if eventButton == QtCore.Qt.RightButton:
                return False
            if obj == self._listView.viewport():
                self.emit(QtCore.SIGNAL('activated(int)'),
                            self._listView.currentIndex().row())
                self.reloadPopup()
                return True
            if obj == self._lineEdit:
                self.showPopup()
            elif obj not in (self._listView, self._listView.window()):
                self.hidePopup()
        return False

    def updateCheckedItems(self, index=None, start=None, end=None):
        """ Slot to update the checkedItems when the dataChanged or
            checkStateChanged Signal emits.

            Args:
                index (int): Row index of the item.
                start (int): Start index of the change
                end (int): End index of the change
        """
        itemList = self.checkedItems() + self.uncheckedItems()
        if not len(itemList):
            self.setEditText(self._defaultText)
        elif len(itemList) == self._model.rowCount():
            self.setEditText(self._selectAllText)
            pass
        else:
            self.setEditText(itemList.join(self._separator))
        self.emit(QtCore.SIGNAL('checkedItemsChanged(PyQt_PyObject)'), itemList)

    def toggleCheckState(self, index):
        """ Slot to update the check state of the item in the given index,
            Calls when the activated signal emits.

            Args:
                index (QModelIndex): Index of the item that has to change.
        """
        value = self.itemData(index, QtCore.Qt.CheckStateRole)
        if value.toInt()[0]:
            state = QtCore.Qt.Unchecked
        else:
            state = QtCore.Qt.Checked
        self.setItemData(index, state, QtCore.Qt.CheckStateRole)

    def clearAllEvent(self):
        """ Event for clear all check from the list view.
        """
        self.checkAll(False)

    def checkAllEvent(self):
        """ Event for check all from the list view.
        """
        self.checkAll(True)

    def contextMenuEvent(self, event):
        """ Event for create context menu.

            Args:
                event (QEvent):  Mouse right click event.
        """
        signalMap = {}
        contextMenu = QtGui.QMenu(self)

        clearAllAction = contextMenu.addAction("Clear All")
        signalMap[clearAllAction] = "clearAll()"
        checkAllAction = contextMenu.addAction("Check All")
        signalMap[checkAllAction] = "checkAll()"

        contextMenuAction = contextMenu.exec_(QtGui.QCursor.pos())
        if contextMenuAction and contextMenuAction in signalMap:
            self.emit(QtCore.SIGNAL(signalMap[contextMenuAction]))

class MultiCheckComboModel(QtGui.QStandardItemModel):
    """ Class definition for the custom QComboBox that can select multiple
        options using check-box.
    """
    def __init__(self, parent=None):
        """ Initialization for MultiCheckComboModel class.

            Args:
                parent(QWidget): parent widget to which the table is attached.
        """
        super(MultiCheckComboModel, self).__init__(parent)

    def flags(self, index):
        """ Overwritten function to return the wanted roles for the
            given index.

            Args:
                index (QModelIndex):  index of the item.
        """
        return QtCore.Qt.ItemIsUserCheckable | \
                QtCore.Qt.ItemIsSelectable | \
                QtCore.Qt.ItemIsEnabled | \
                QtCore.Qt.ItemIsEditable

    def data(self, index, role):
        """ Overwritten function to return value based on the role and index.

            Args:
                index (QModelIndex):  index of the item that has to change.
                role (UserRole):   Qt.UserRole

            Return:
                (QVariant)  return the value for specific role.
        """
        value = super(MultiCheckComboModel, self).data(index, role)
        if index.isValid() and role == QtCore.Qt.CheckStateRole:
            if not value.isValid():
                return QtCore.Qt.Unchecked
            else:
                return value
        return value

    def setData(self, index, value, role):
        """ Overwritten function to return set value based on the
            role and index.

            Args:
                index (QModelIndex): Index of the item that has to change.
                value (QVariant): Value for the specific role.
                role (UserRole): Qt.UserRole

            Return:
                (bool) return the status in boolean.
        """
        result = super(MultiCheckComboModel, self).setData(index, value, role)

        if result and role == QtCore.Qt.CheckStateRole:
            self.emit(QtCore.SIGNAL('dataChanged(PyQt_PyObject, PyQt_PyObject)'),
                                    index,
                                    index)
            self.emit(QtCore.SIGNAL('checkStateChanged()'))
        return True


class Car:
    speed = 0

    def upSpeed(self, value):
        self.speed += value

        print("current speed(super class) :", self.speed)

class Sedan(Car):
    def upSpeed(self, value):
        self.speed += value

        if self.speed > 150:
            self.speed = 150

        print("current speed(sub class) :", self.speed)

class Truck(Car):
    pass

sedan1, truck1 = None, None
truck1 = Truck()
sedan1 = Sedan()
print("truck --> ", end="")
truck1.upSpeed(200)
print("sedan --> ", end="")
sedan1.upSpeed(200)


import time
import os
import pip

if os.name == 'nt':
    clear = lambda: os.system('cls')
else:
    clear = lambda: os.system('clear')

def import_or_install():
    try:
        from pydrive.auth import GoogleAuth
        from pydrive.drive import GoogleDrive
        import pyperclip
    except ImportError:
        pip.main(['install', 'pydrive'])
        pip.main(['install', 'pyperclip'])

        clear()
        print('pydrive has been installed!')
import_or_install()

from requests import get
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from requests.sessions import extract_cookies_to_jar

os.chdir('../credentials')
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
os.chdir('../data')
externalIPAddress = ''

class UpdateIP:

    def DriveRootFolderQuery():
        global externalIPAddress
        #print('externalip in DriveRootFolderQuery is')
        #print(externalIPAddress)
        externalIPAddress = get('https://api.ipify.org').text
        file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
        for file1 in file_list:
            if  'IPUpdate.txt' in file1['title']:
                #print('title: %s, id: %s' % (file1['title'], file1['id']))
                UpdateIP.UpdateFileContent(file1)
        return

    def UpdateFileContent(file1):
        global externalIPAddress
        if externalIPAddress != file1.GetContentString():
            print('The ip does not match. Trying to set the content to the global ip in string.')

            file1.SetContentString(externalIPAddress) # Set content of the file from given string.
            file1.Upload()
        else:

            print('The ip matches. Sleeping for 300 seconds')
            time.sleep(300)

while True:
    UpdateIP.DriveRootFolderQuery()


from django.contrib import admin

# Register your models here.
from post.models import Post, User

class UserAdmin(admin.ModelAdmin):
    class Meta:
        model = User

    readonly_fields = 'created_at updated_at'.split()

admin.site.register(User, UserAdmin)

class PostAdmin(admin.ModelAdmin):
    class Meta:
        model = Post

    readonly_fields = 'created_at updated_at'.split()

admin.site.register(Post, PostAdmin)


from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.controller import ofp_event
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.ofproto import ofproto_v1_3
from ryu.base import app_manager
from ryu.lib import hub

import copy

class switching_hub(app_manager.RyuApp):

	OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

	# Initialization
	def __init__(self, *args, **kwargs):

		# Call superclass __init__ and start monitor thread
		super(switching_hub, self).__init__(*args, **kwargs)
		self.monitor_thread = hub.spawn(self.monitor)

		# Initialize tables
		self.mac_to_port = {}
		self.packet_counter = {}
		self.switches = {}
		self.suspects = {}
		self.blocked = []

		# Constants
		self.omega = 8
		self.rho = 5

	# Display packet counts
	def monitor(self):

		# Loop every 10 seconds
		while True:

			# Loop over switches
			for dpid in self.packet_counter:

				# Print data
				counter = copy.deepcopy(self.packet_counter[dpid])
				self.logger.info("Datapath Id %s", dpid)
				S = 0

				# Loop over ports
				for in_port in self.packet_counter[dpid]:
					self.logger.info("Port %s --> %s", in_port, self.packet_counter[dpid][in_port])
					S += self.packet_counter[dpid][in_port]
					self.packet_counter[dpid][in_port] = 0

				# Check if blocked
				if dpid in self.blocked:
					if S < self.omega:
						self.blocked.remove(dpid)
					else:
						continue

				# Compare with threshold for DoS detection
				if (S > self.omega) and (dpid not in self.suspects):
					self.suspects[dpid] = counter
					self.dos_detect(dpid)
					continue

				# Process between host or switch attack for existing suspect
				if dpid in self.suspects:
					if S > self.omega:
						self.switch_defender(dpid)
					else:
						self.host_defender(dpid)
					del self.suspects[dpid]

			# Wait 10 seconds
			hub.sleep(10)

	# DoS detector
	def dos_detect(self, dpid):

		# Get switch info
		datapath = self.switches[dpid]
		ofproto = datapath.ofproto
		parser = datapath.ofproto_parser

		# Remove table miss entry
		match = parser.OFPMatch()
		inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, [])]
		mod = parser.OFPFlowMod(datapath=datapath, priority=3, cookie=3, match=match, instructions=inst, hard_timeout=10)
		# mod = parser.OFPFlowMod(datapath=datapath, priority=0, cookie=1, command=ofproto.OFPFC_MODIFY_STRICT)
		datapath.send_msg(mod)

		# Record suspect
		self.logger.info("DoS detected at switch id %s", dpid)

	# Host defender
	def host_defender(self, dpid):

		# Log message
		self.logger.info("Host defender activated for switch id %s", dpid)

		# Get switch info
		datapath = self.switches[dpid]
		ofproto = datapath.ofproto
		parser = datapath.ofproto_parser

		# Id attackers and block
		for port, count in self.suspects[dpid].items():

			# Threshold comparison
			if count > self.rho:

				# Block
				match = parser.OFPMatch(in_port=port)
				self.add_flow(datapath, 2, match, [], cookie=2)

		# Repair table-miss
		# match = parser.OFPMatch()
		# actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)]
		# inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
		# mod = parser.OFPFlowMod(datapath=datapath, priority=0, match=match, instructions=inst, cookie=1, command=ofproto.OFPFC_MODIFY_STRICT)
		# datapath.send_msg(mod)

	# Switch defender
	def switch_defender(self, dpid):

		# Log message
		self.logger.info("Switch defender activated for switch id %s", dpid)

		# Add to blocklist
		self.blocked.append(dpid)

	# Install table-miss flow entry
	@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
	def switch_features_handler(self, ev):

		# Get switch info
		datapath = ev.msg.datapath
		ofproto = datapath.ofproto
		parser = datapath.ofproto_parser

		# Add to switch list
		self.switches[datapath.id] = datapath

		# Install table-miss entry
		match = parser.OFPMatch()
		actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER, ofproto.OFPCML_NO_BUFFER)]
		self.add_flow(datapath, 0, match, actions, cookie=1)

	# Handle received packets
	@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
	def packet_in_handler(self, ev):

		# Check if blocked
		if ev.msg.datapath.id in self.blocked:
			dpid = ev.msg.datapath.id
			in_port = ev.msg.match['in_port']
			self.packet_counter[dpid].setdefault(in_port, 0)
			self.packet_counter[dpid][in_port] += 1
			return

		# Get switch info
		msg = ev.msg
		datapath = msg.datapath
		ofproto = datapath.ofproto
		parser = datapath.ofproto_parser

		# Get datapath id and add to mactable if not present
		dpid = datapath.id
		self.mac_to_port.setdefault(dpid, {})
		self.packet_counter.setdefault(dpid, {})

		# Analyze packets
		pkt = packet.Packet(msg.data)
		eth_pkt = pkt.get_protocol(ethernet.ethernet)
		src = eth_pkt.src
		dst = eth_pkt.dst

		# Update mactable
		in_port = msg.match['in_port']
		self.logger.info("packet in %s %s %s %s", dpid, src, dst, in_port)
		self.mac_to_port[dpid][src] = in_port

		# Increment packet count
		self.packet_counter[dpid].setdefault(in_port, 0)
		self.packet_counter[dpid][in_port] += 1

		# Check for existing flow entry and flood if not found
		if dst in self.mac_to_port[dpid]:
			out_port = self.mac_to_port[dpid][dst]
		else:
			out_port = ofproto.OFPP_FLOOD

		# Construct action list
		actions = [parser.OFPActionOutput(out_port)]

		# Add flow entry to avoid further floods
		if out_port != ofproto.OFPP_FLOOD:
			match = parser.OFPMatch(in_port=in_port, eth_dst=dst)
			self.add_flow(datapath, 1, match, actions)

		# Send packet out back to switch
		out = parser.OFPPacketOut(datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER, in_port=in_port, actions=actions, data=msg.data)
		datapath.send_msg(out)

	# Add a flow entry
	def add_flow(self, datapath, priority, match, actions, cookie=0):

		# Get switch info
		ofproto = datapath.ofproto
		parser = datapath.ofproto_parser

		# Compile instruction set
		inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]

		# Send flow mod message
		mod = parser.OFPFlowMod(datapath=datapath, priority=priority, match=match, instructions=inst, cookie=cookie)
		datapath.send_msg(mod)


import time
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains

def move(distance):
    """
    :param distance: 距离 int
    :return: 距离总和为distance的数组 tracks[]
    """
    v = 0
    t = 0.2
    x = distance
    tracks = []
    current = 0
    # x = x+10
    while current < x:
        a = 10
        v0 = v
        # 单位时间内位移公式
        s = v0 * t + 0.5 * a * (t ** 2)
        # 当前位移
        current = current + s
        tracks.append(round(s))
        v = v0 + a * t
    return tracks

def main():
    # 点击登录
    driver = webdriver.Chrome(executable_path='F:/pythonProject/pubilcVenv/seleniumDriver/chrome 91/chromedriver.exe')
    driver.get('https://www.qcc.com/')

    # wait
    sleep(5)

    longin = driver.find_element_by_xpath(r"//a[@onclick='showLoginModal();']/span")
    longin.click()
    sleep(3)

    #sliding_block
    sliding_block = driver.find_element_by_xpath(r"//span[@class='nc_iconfont btn_slide']")
    ActionChains(driver).click_and_hold(sliding_block).perform()
    for x in move(distance=500):
        ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
    ActionChains(driver).release(sliding_block).perform()
    time.sleep(3)

    pass

if __name__ == '__main__':
    main()


"""
Author: D Jayme Green
Extracts the data from the csv given by the NCAA D1 Lacrosse
that I care about (the percentage and per game) that happen to be at
the end of the rows
"""

import csv

"""
Reading in the .csv file and putting it into listOfData which
has the team name and then the data that I want (happens to be
at the end of each block of data). Each block has different width
provided by the NCAA
"""
def openCSVFile(fileName):
    listOfData = list()
    dictOfLaxTeamsList = dict()
    with open(fileName, newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='|')
        rowNum = 0
        for row in reader:
            row = list(filter(None,row))
            colNum = len(row)
            if colNum > 1 and row[1] != 'Name':
                # Where the name is at col 1
                if row[1] not in dictOfLaxTeamsList:
                    dictOfLaxTeamsList[row[1]] = len(dictOfLaxTeamsList)
                    listOfData.append(list())
                    listOfData[dictOfLaxTeamsList[row[1]]].append(row[1])
                college = row[1]
                listOfData[dictOfLaxTeamsList[college]].append(float(row[colNum-1]))
            rowNum += 1
    return listOfData

"""
Writes all of the data into a new CSV file. Each team has a row
with each column being another piece of data
"""
def writeToCSV(listOfData):
    with open('d1LaxRankings.csv', 'w') as f:
        for team in listOfData:
            for stat in team:
                f.write(str(stat) + ',')
            f.write('\n')

listOfData, totalNumberOfVals, numberOfCols = openCSVFile('rankingsRaw.csv')
writeToCSV(listOfData)


from flask import Flask, render_template, request
import base64
from scipy.misc import imsave, imread, imresize
import numpy as np
import pdb
import sys
import os
from load_DL_data import *
app = Flask(__name__)

global model, graph
model,graph = init()

@app.route('/draw_canvas')
def index():
   return render_template('canvas.html')

@app.route('/predict', methods=['POST', 'GET'])
def precict_data():
   print("under predict")
   enc_img = request.get_data()
   # pdb.Pdb(stdout=sys.__stdout__).set_trace()
   enc_img = enc_img[22:]
   with open('canvas_img.png', 'wb') as img :
         img.write(base64.b64decode(enc_img))

   # img_name = 'canvas_img.png'  # I assume you have a way of picking unique filenames
   dec_img = imread('canvas_img.png', mode='L')
   dec_img_swap = np.invert(dec_img)
   dec_img_swap = imresize(dec_img_swap, (28,28))
   dec_img_swap = dec_img_swap.reshape(1, 784)

   with graph.as_default():
       out = model.predict(dec_img_swap)
       response = np.array_str(np.argmax(out,axis=1))
       return response

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


class Restuarant:
    """A simple Restuarant Class """

    def __init__(self, name, cuisine_type):
        self.name = name
        self.cuisine_type = cuisine_type

    def describe_restuarant(self):
            return f"Restuarant Name: {self.name} \nCuisine Type: {self.cuisine_type}."

    def open_restuarant(self):
            # is_open=True
            return "Restuarant is opened!"

print("======   Restuarant   ======")
restuarant=Restuarant("Mr. Biggs", "Cuisine type A")
print(restuarant.name)
print(restuarant.cuisine_type)
print()
print(restuarant.describe_restuarant())
print()
print(restuarant.open_restuarant())

print("======   Three Restuarants   ======")
restuarant1=Restuarant("Mr. Biggs", "Cuisine type-A")
restuarant2=Restuarant("Chiken Republic", "Cuisine type-B")
restuarant3=Restuarant("Tasty Restuarants", "Cuisine type-C")
print(restuarant1.describe_restuarant())
print()
print(restuarant2.describe_restuarant())
print()
print(restuarant3.describe_restuarant())
print()

print("======   User Class   ======")
class User:
    """simple User class"""

    def __init__(self, first_name, last_name, *user_profile):
        self.first_name = first_name
        self.last_name = last_name
        self.user_profile=user_profile

    def describe_user(self):
        return f"My name is {self.first_name} {self.last_name}\nOther characters:{[i for i in self.user_profile]} ."

    def greet_user(self):
        return f"Hi {self.last_name.upper()}!"

user1=User("Abdullahi","Bello","kano","Hausa")
print(user1.describe_user())
print()
print(user1.greet_user())

print()
user2=User("Tijjani","Muhammad","kaduna","Ibira")
print(user2.describe_user())
print()
print(user2.greet_user())

print()
user3=User("Hassan","Muhammad","kano","Hausa")
print(user3.describe_user())
print()
print(user3.greet_user())

print()
print("======  Modifying Restuarant class ======")
class Restuarant:
    """A simple Restuarant Class """

    def __init__(self, name, cuisine_type):
        self.name = name
        self.cuisine_type = cuisine_type
        self.number_served=0

    def describe_restuarant(self):
            return f"Restuarant Name: {self.name} \nCuisine Type: {self.cuisine_type}."

    def open_restuarant(self):
            # is_open=True
            return "Restuarant is opened!"
    def set_number_served(self, num):
        self.number_served = num
        return self.number_served

    def increment_number_served(self, num):
        self.number_served += num
        return self.number_served

r=Restuarant("Pluto's Restuarant", "Cuisine Type-A")
print(f"Initial Number of customers served: {r.number_served}")

r.number_served = 23
print(f"Changed Number of customers served : {r.number_served}")
print(f"Changed Number of customers served through method: {r.set_number_served(23_000)}")
print(f"Incremented Number of customers served through method: {r.increment_number_served(2_000)}")

print()
print("======  Modifying User Class   ======")
class User:
    """simple User class"""

    def __init__(self, first_name, last_name, *user_profile):
        self.first_name = first_name
        self.last_name = last_name
        self.user_profile=user_profile
        self.login_attempts=0

    def describe_user(self):
        return f"My name is {self.first_name} {self.last_name}\nOther informations:{[i for i in self.user_profile]} ."

    def greet_user(self):
        return f"Hi {self.last_name.upper()}!"

    def increment_login_attempts(self):
        self.login_attempts += 1
        return self.login_attempts

    def reset_login_attempts(self):
        self.login_attempts = 0
        return self.login_attempts

u = User("Hassan","Muhammad","kano","Hausa")
print(f"Initial Number of login attempts: {u.login_attempts}")
print(f"Incremented Number of login attempts: {u.increment_login_attempts()}")
print(f"Another Incremented Number of login attempts: {u.increment_login_attempts()}")
print(f"Reset Number of login attempts: {u.reset_login_attempts()}")

print()
print("======  Ice Cream Stand Class   ======")
class IceCreamStand(Restuarant):
    """This an ice cream class that inherit from the restuarant class"""

    def __init__(self, name, cuisine_type):
        super().__init__(name, cuisine_type)
        self.flavors = ['Vanilla', 'Chocolate', 'Strawberry', 'Mint', 'Butter Pecan']

    def display_flavors(self):
        print("List of Flavors are:")
        for flavor in self.flavors:
            print(f" - {flavor}")
        return ""

ice = IceCreamStand("Ice-Cream Palace", "Traditional Chinese Food")
print(ice.display_flavors())

print()
print("======  Privileges Class   ======")
class Privilege:
    """This class models privilages of an admin"""

    def __init__(self, privilages=['can add post', 'can delete post', 'can ban user',
            'Create User', 'Update User', 'Display User\'s information ', 'Delete User', ]
            ):
        self.privilages = privilages

    def show_privileges(self):
        print("List of Admin Privileges are:")
        for privilege in self.privilages:
            print(f" - {privilege}")
        return ""

print()
print("======  Admin Class   ======")
class Admin(User):
    """This an Admin model that inherit from the User class"""

    def __init__(self, first_name, last_name, *user_profile):
        super().__init__(first_name, last_name, *user_profile)
        self.privileges = Privilege()

admin = Admin("Abdullahi","Bello","kano","Hausa")
admin.privileges.show_privileges()
print()

print()
print("======  Car Class   ======")
class Car:
    """A simple attempt to represent a car."""

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self, miles):
        self.odometer_reading += miles

print()
print("======  Battery Class   ======")
class Battery:
    """A simple attempt to model a battery for an electric car."""

    def __init__(self, battery_size=75):
        """Initialize the battery's attributes."""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a statement describing the battery size."""
        return f"This car has a {self.battery_size}-kWh battery."

    def get_range(self):
        """Print a statement about the range this battery provides."""
        range=0
        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315
        return f"This car can go about {range} miles on a full charge."

    def upgrade_battery(self):
        self.battery_size = 100
        return self.battery_size

#
print()
print("======  Electric Car Class   ======")
class ElectricCar(Car):
    """Represent aspects of a car, specific to electric vehicles."""

    def __init__(self, make, model, year, battery_size=75):
        """Initialize attributes of the parent class.
        Then initialize attributes specific to an electric car.
        """
        super().__init__(make, model, year)
        self.battery_size = battery_size
        self.battery = Battery()

        def describe_battery(self):
            """Print a statement describing the battery size."""
            print(f"This car has a {self.battery_size}-kWh battery.")

        def fill_gas_tank(self):
            """Electric cars don't have gas tanks."""
            print("This car doesn't need a gas tank!")

my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

# Battery Upgrade
print()
print("======  Battery Upgrade    ======")
my_tesla = ElectricCar('Toyota', 'Accord', 2021)
print(my_tesla.battery.get_range())
my_tesla.battery.upgrade_battery()
print(my_tesla.battery.get_range())
print()


# pylint: disable=line-too-long, invalid-name

from __future__ import absolute_import, division, print_function

__license__ = """MIT License

Copyright (c) 2014-2019 Sebastian Schoenen and Martin Leuermann

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from warnings import warn

import numpy as np
from scipy.interpolate import RectBivariateSpline as spl2D

from .kde import getLambda_ND, kde_ND
from .pykde import gaussian_kde
from .stat_tools import weighted_cov

class KDE(object):
    """Initialize KDE object

    Parameters
    ----------
    data
    use_cuda
    weights
    alpha
    method

    """
    def __init__(self, data, use_cuda, weights=None, alpha=0.3, method='silverman'):
        self.use_cuda = use_cuda
        if self.use_cuda:
            import pycuda.driver as cuda
            import pycuda.autoinit # pylint: disable=unused-variable
            self.cuda = cuda

        self.data = np.atleast_2d(data)

        self.d, self.n = self.data.shape

        self.alpha = alpha

        if weights is None or len(weights) == 0:
            self.w = np.full(shape=self.n, fill_value=1/self.n, dtype=float)
            self.setCovariance(weights=False)
        elif len(weights) == self.n:
            self.w = np.asarray(weights, dtype=float) / np.sum(weights)
            self.setCovariance(weights=True)
        else:
            raise AssertionError("Length of data (%d) and length of weights"
                                 " (%d) incompatible."
                                 % (self.n, len(weights)))

        self.hMethod = method
        self.lambdas = None
        self.points = None
        self.m = None
        self.d_pt = None
        self.values = None
        self.h = None
        self.weights = None
        self.w_norm = None
        self.w_norm_lambdas = None
        self.preFac = None
        self.logSum = None
        self.invGlob = None

    def setCovariance(self, weights=False):
        """Set covariance from data and weights

        Parameters
        ----------
        weights : bool, optional

        """
        if weights:
            self.c = weighted_cov(self.data, weights=self.w, bias=False)
        else:
            self.c = np.cov(self.data)

        if self.d != 1:
            self.c_inv = np.linalg.inv(self.c)
            self.detC = np.linalg.det(self.c_inv)
        else:
            self.c_inv = 1.0/self.c
            self.detC = self.c_inv

    def calcLambdas(self, weights=False, weightedCov=False, use_grid=False):
        """Calculate bandwidth lambda for data points in KDE function

        Parameters
        ----------
        weights : bool, optional
        weightedCov : bool, optional
        use_grid : bool, optional

        """
        self.configure("lambdas", weights=weights, weightedCov=weightedCov)

        if self.use_cuda:
            self.cuda_calc_lambdas()
        else:
            if use_grid and self.d == 2:
                # grid #
                N_grid = 100
                ext = np.zeros((2, self.d))
                for i in range(self.d):
                    diff = (np.max(self.data[i]) - np.min(self.data[i])) * 0.1
                    ext[i, 0] = np.min(self.data[i]) - diff
                    ext[i, 1] = np.max(self.data[i]) + diff
                spaces1D = [np.linspace(t[0], t[1], N_grid) for t in ext]
                grid = np.array(np.meshgrid(*spaces1D))
                grid = grid.reshape((self.d, grid.size / self.d))

                # kde #
                n_w = len(self.w)
                w = self.w if weights else np.full(shape=n_w, fill_value=1/n_w)
                ss_kde = gaussian_kde(self.data, weights=w, adaptive=False,
                                      weight_adaptive_bw=False,
                                      alpha=self.alpha, bw_method=self.hMethod)

                vals = ss_kde(grid)    # evaluate in log instead of linear to avoid negative values
                spline1 = spl2D(*spaces1D, z=(np.array(vals)).reshape([N_grid, N_grid]).T, kx=3, ky=3)   # TRANSPOSE HERE!!!!
                kde_vals2 = np.array([spline1(x, y)[0][0] for x, y in self.data.T]) # go back to linear world

                #print("Ratio direct:")
                #print(( np.array(kde_vals2) - np.array(kde_vals) ) / np.array(kde_vals))

                # lambdas #
                glob_sum = np.exp(np.sum(np.log(kde_vals2) / len(kde_vals2)))
                self.lambdas = np.power(kde_vals2 / glob_sum, (-1.0) * self.alpha) #self.alpha*(-1.0)) # hack !!!
            else:
                self.lambdas = getLambda_ND(
                    int(self.d),
                    list(self.c_inv.flatten()),
                    list(self.data.flatten()),
                    list(self.w_norm_lambdas),
                    float(self.detC),
                    self.h,
                    self.alpha
                )

    def kde(self, points, weights=True, weightedCov=True):
        """Evaluate kde function

        Parameters
        ----------
        points
        weights : bool, optional
        weightedCov : bool, optional

        """
        self.points = np.atleast_2d(points)
        self.d_pt, self.m = self.points.shape

        if self.d > 1 and self.d != self.d_pt:
            assert self.d == self.m
            points = list(zip(*points[::1]))
            self.d_pt, self.m = np.array(points).shape
            warn("Dimensions of given points did not fit initialized kde"
                 " function. Rotate given sample and proceed with fingers"
                 " crossed.")

        self.configure("kde", weights=weights, weightedCov=weightedCov)

        if self.use_cuda:
            self.cuda_kde(points)
        else:
            self.values = kde_ND(
                int(self.d),
                list(self.c_inv.flatten()),
                list(self.data.flatten()),
                list(self.points.flatten()),
                list(self.w_norm),
                list(self.preFac),
                float(self.detC),
                self.h,
            )

    def configure(self, mode, weights=False, weightedCov=False):
        """Get h, tempNorm, w_norm, w_lambdas, preFac

        Parameters
        ----------
        mode
        weights : bool
        weightedCov : bool

        """
        if isinstance(self.hMethod, str):
            if self.hMethod == 'silverman':
                # (n * (d + 2) / 4.)**(-1. / (d + 4)).
                self.h = np.power(1.0/(self.n*(self.d+2.0)/4.0), 1.0/(self.d+4.0))
            elif self.hMethod == 'scott':
                self.h = np.power(1.0/(self.n), 1.0/(self.d+4.0))
            else:
                raise ValueError("%s unknown string as normalization"
                                 " constant. Implemented are 'scott',"
                                 " 'silverman'" %(self.hMethod,))
        elif isinstance(self.hMethod, (int, float)):
            self.h = self.hMethod
        else:
            raise ValueError("Normalization constant must be of type int,"
                             " float or str!")

        self.setCovariance(weights=weightedCov)

        if weights:
            self.weights = self.w
        else:
            self.weights = np.full(shape=self.n, fill_value=1/self.n,
                                   dtype=float)

        if mode == "lambdas":
            self.w_norm_lambdas = self.weights * np.sqrt(self.detC / np.power(2.0*np.pi*self.h*self.h, self.d))
            self.preFac = -0.5/np.power(self.h, 2)
        elif mode == "kde":
            self.w_norm = self.weights * np.sqrt(self.detC / np.power(2.0*np.pi*self.h*self.h*np.array(self.lambdas)*np.array(self.lambdas), self.d))
            self.preFac = -0.5/np.power(self.h*np.array(self.lambdas), 2)
        else:
            raise ValueError("Could not configure kde object. Unknown mode: %s" %(mode,))

    def cuda_calc_lambdas(self):
        """Calculate lambdas using cuda implementation"""
        from pycuda.compiler import SourceModule

        # conversion of python variables
        n = np.int32(self.n)
        logSum = np.zeros(n)
        kde_val_la = np.zeros(n)

        h_kde_val_la = np.array(kde_val_la).astype(np.float64)
        h_logSum = logSum.astype(np.float64)
        h_w_norm_lambdas = np.array(self.w_norm_lambdas).astype(np.float32)

        # reservation of memory on gpu
        d_kde_val_la = self.cuda.mem_alloc(h_kde_val_la.nbytes)
        d_logSum = self.cuda.mem_alloc(h_logSum.nbytes)
        d_w_norm_lambdas = self.cuda.mem_alloc(h_w_norm_lambdas.nbytes)

        # memory copy to gpu
        self.cuda.memcpy_htod(d_kde_val_la, h_kde_val_la)
        self.cuda.memcpy_htod(d_logSum, h_logSum)
        self.cuda.memcpy_htod(d_w_norm_lambdas, h_w_norm_lambdas)

        # dimension-dependent memory allocation
        if self.d == 2:
            h_x1 = np.array(self.data[0]).astype(np.float32)
            h_x2 = np.array(self.data[1]).astype(np.float32)
            d_x1 = self.cuda.mem_alloc(h_x1.nbytes)
            d_x2 = self.cuda.mem_alloc(h_x2.nbytes)
            self.cuda.memcpy_htod(d_x1, h_x1)
            self.cuda.memcpy_htod(d_x2, h_x2)
            addParam = "const float *x2, const double c11, const double c12, const double c21, const double c22"
            addDeclare = "double ent2;"
            calculation = """
                ent1 = x1[j]-x1[idx];
                ent2 = x2[j]-x2[idx];
                thisKde += w_norm_lambda[j] * exp(preFac * (ent1*(c11*ent1+c12*ent2) + ent2*(c21*ent1+c22*ent2)));
            """
        elif self.d == 1:
            h_x1 = np.array(self.data[0]).astype(np.float32)
            d_x1 = self.cuda.mem_alloc(h_x1.nbytes)
            self.cuda.memcpy_htod(d_x1, h_x1)
            addParam = "const double c"
            addDeclare = ""
            calculation = """
                ent1 = x1[j]-x1[idx];
                thisKde += w_norm_lambda[j] * exp(preFac * (ent1*c*ent1));
            """

        # define function on gpu to be executed
        mod = SourceModule("""
            __global__ void CalcLambda(const float *x1, """+addParam+""", const int n, const double preFac, const float *w_norm_lambda, double *logSum, double *kde){
                int idx = threadIdx.x + blockIdx.x*blockDim.x;
                if (idx < n){
                    double thisKde, ent1;
                    """+addDeclare+"""
                    int j;
                    thisKde = 0.0;
                    for (j=0; j < n; j++) {
                        """+calculation+"""
                    } // for
                   logSum[idx] = 1.0/n * log(thisKde);
                   kde[idx] = thisKde;
                } // if
                __syncthreads();
            } // CalcLambda_2d
        """)

        if n >= 512:
            bx = np.int32(512)
        else:
            bx = np.int32(n)
        gx = np.int32(n/bx)
        if n % bx != 0:
            gx += 1

        func = mod.get_function("CalcLambda") # code compiling
        if self.d == 2:
            # call of gpu function
            func(d_x1, d_x2,
                 self.c_inv[0, 0], self.c_inv[1, 0],
                 self.c_inv[0, 1], self.c_inv[1, 1],
                 n,
                 self.preFac,
                 d_w_norm_lambdas, d_logSum, d_kde_val_la,
                 block=(int(bx), 1, 1),
                 grid=(int(gx), 1, 1))
        elif self.d == 1:
            # call of gpu function
            func(d_x1,
                 self.c_inv,
                 n,
                 self.preFac,
                 d_w_norm_lambdas, d_logSum, d_kde_val_la,
                 block=(int(bx), 1, 1),
                 grid=(int(gx), 1, 1))

        # backward copy from gpu to cpu memory
        self.cuda.memcpy_dtoh(h_logSum, d_logSum)
        self.cuda.memcpy_dtoh(h_kde_val_la, d_kde_val_la)

        self.logSum = sum(h_logSum)
        self.invGlob = 1.0/np.exp(self.logSum)
        self.lambdas = np.array(1.0/np.power(self.invGlob*np.array(h_kde_val_la), self.alpha))

    def cuda_kde(self, points, weights=True):
        """Calculate kde values using CUDA implementation

        Parameters
        ----------
        points
        weights : bool, optional

        """
        from pycuda.compiler import SourceModule

        self.points = np.atleast_2d(points)
        self.d_pt, self.m = self.points.shape

        # conversion of python variables
        n = np.int32(self.n)
        m = np.int32(self.m)
        kde_val = np.zeros(self.m)

        h_preFac = np.array(self.preFac).astype(np.float64)
        h_w_norm = np.array(self.w_norm).astype(np.float64)
        h_kde_val = np.array(kde_val).astype(np.float64)

        # reservation of memory on gpu
        d_preFac = self.cuda.mem_alloc(h_preFac.nbytes)
        d_w_norm = self.cuda.mem_alloc(h_w_norm.nbytes)
        d_kde_val = self.cuda.mem_alloc(h_kde_val.nbytes)

        # memory copy to gpu
        self.cuda.memcpy_htod(d_preFac, h_preFac)
        self.cuda.memcpy_htod(d_w_norm, h_w_norm)
        self.cuda.memcpy_htod(d_kde_val, h_kde_val)

        # dimension-dependent memory allocation
        if self.d == 2:
            h_x1 = np.array(self.data[0]).astype(np.float32)
            h_x2 = np.array(self.data[1]).astype(np.float32)
            h_y1 = np.array(self.points[0]).astype(np.float32)
            h_y2 = np.array(self.points[1]).astype(np.float32)
            d_x1 = self.cuda.mem_alloc(h_x1.nbytes)
            d_x2 = self.cuda.mem_alloc(h_x2.nbytes)
            d_y1 = self.cuda.mem_alloc(h_y1.nbytes)
            d_y2 = self.cuda.mem_alloc(h_y2.nbytes)
            self.cuda.memcpy_htod(d_x1, h_x1)
            self.cuda.memcpy_htod(d_x2, h_x2)
            self.cuda.memcpy_htod(d_y1, h_y1)
            self.cuda.memcpy_htod(d_y2, h_y2)
            addDeclare = "double ent2;"
            addParam = "const float *x2, const float *y2, const double c11, const double c12, const double c21, const double c22"
            calculation = """
                ent1 = x1[j]-y1[idx];
                ent2 = x2[j]-y2[idx];
                thisKde += w_norm[j] * exp(preFac[j] * (ent1*(c11*ent1+c12*ent2) + ent2*(c21*ent1+c22*ent2)));
            """
        elif self.d == 1:
            h_x1 = np.array(self.data[0]).astype(np.float32)
            h_y1 = np.array(self.points[0]).astype(np.float32)
            d_x1 = self.cuda.mem_alloc(h_x1.nbytes)
            d_y1 = self.cuda.mem_alloc(h_y1.nbytes)
            self.cuda.memcpy_htod(d_x1, h_x1)
            self.cuda.memcpy_htod(d_y1, h_y1)
            addParam = "const double c"
            addDeclare = ""
            calculation = """
                ent1 = x1[j]-y1[idx];
                thisKde +=  w_norm[j] * exp(preFac[j] * c * pow(ent1, 2));
            """

        # define executed function
        mod = SourceModule("""
            __global__ void CalcKde(const float *x1, const float *y1, """+addParam+""", const int n, const int m, const double *preFac, const double *w_norm, double *kde){
                int idx = threadIdx.x + blockIdx.x*blockDim.x;
                if (idx < m){
                    double thisKde, ent1;
                    """+addDeclare+"""
                    int j;
                    thisKde = 0.0;
                    for (j=0; j < n; j++) {
                        """+calculation+"""
                    } // for
                    kde[idx] = thisKde;
                } // if
                __syncthreads();
            } // CalcKde_2d
        """)

        if n >= 512:
            bx = np.int32(512)
        else:
            bx = np.int32(n)
        gx = np.int32(self.m/bx)
        if n / bx != 0.0:
            gx += 1

        # code compiling
        func = mod.get_function("CalcKde")
        if self.d == 2:
            # call of gpu function
            func(d_x1, d_y1, d_x2, d_y2,
                 self.c_inv[0, 0], self.c_inv[1, 0],
                 self.c_inv[0, 1], self.c_inv[1, 1],
                 n, m,
                 d_preFac, d_w_norm, d_kde_val,
                 block=(int(bx), 1, 1),
                 grid=(int(gx), 1, 1))
        elif self.d == 1:
            # call of gpu function
            func(d_x1, d_y1,
                 self.c_inv,
                 n, m,
                 d_preFac, d_w_norm, d_kde_val,
                 block=(int(bx), 1, 1),
                 grid=(int(gx), 1, 1))

        # backward copy from gpu to cpu memory
        self.cuda.memcpy_dtoh(h_kde_val, d_kde_val)

        self.values = h_kde_val


"""trainspot URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from rest_framework import routers
from api import views

router = routers.DefaultRouter()

# router.register(r'pusher_auth', views.pusher_auth),
router.register(r'cities', views.CityViewSet)
router.register(r'users', views.UserViewSet)
router.register(r'trainers', views.TrainersListViewSet)
router.register(r'lessons', views.LessonViewSet)
router.register(r'specializations', views.SpecializationViewSet)
router.register(r'gyms', views.GymViewSet)
router.register(r'roomtypes', views.RoomTypeViewSet)
router.register(r'rooms', views.RoomViewSet)
router.register(r'inventories', views.InventoryViewSet)
router.register(r'plans', views.PlanViewSet)
router.register(r'subscriptions', views.SubscriptionViewSet)
router.register(r'financialrecords', views.FinancialRecordViewSet)
router.register(r'exercises', views.ExerciseViewSet)
router.register(r'exercisesets', views.ExerciseSetViewSet)
router.register(r'trainingprograms', views.TrainingProgramViewSet)
router.register(r'trainingsessions', views.TrainingSessionViewSet)
router.register(r'chats', views.ChatViewSet)
router.register(r'messages', views.MessageViewSet)
router.register(r'reactions', views.ReactionViewSet)
router.register(r'mailinglists', views.MailingListViewSet)
router.register(r'newsletters', views.NewsletterViewSet)
router.register(r'mailing', views.MailingViewSet)
# router.register(r'groups', views.GroupViewSet)

urlpatterns = [
    # path('', include(router.urls)),
    # path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    path('streams/', views.StreamList.as_view(), name='stream-list'),
    path('send_signal/', views.send_signal, name='send-signal'),
    path('video_feed/', views.video_feed, name='video_feed'),
    path('start-stream', views.start_stream),
    path('api/', include((router.urls, 'api'), namespace='instance_name')),
    path('api/', include('rest_registration.api.urls')),
    path('get-message-reactions/', views.getMessageReactions, name='message-reactions-api'),
    path('pusher_auth', views.pusher_auth, name='pusher_auth'),
]


from datetime import date
import os

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from preprocessors import ToDatetime
from transformers.gamestate import (
    ComputeDaysSinceStart,
    ComputeNetScore,
    EncodeOnBaseOccupancy,
    Identity,
    EncodeHandedness,
    EncodeInningTopBot,
)
from transformers.movingaverage import MovingAverage
from transformers.headtohead import HeadToHead
from transformers.parkfactor import ParkFactor
from constants import IDENTITY_COLS, ROOT_DIR

def make_data_pipeline(
    training_data_start_date: date,
    training_data_end_date: date,
    ma365_start_date: date,
    ma30_start_date: date
):

    preprocessors = Pipeline(steps=[
        ("game_date_to_datetime", ToDatetime(input_col="game_date")),
    ])

    feature_transformers = ColumnTransformer(
        [
            (
                "identity",
                Identity(),
                IDENTITY_COLS,
            ),
            (
                "encode_on_base_occupancy",
                EncodeOnBaseOccupancy(output_cols=["on_1b", "on_2b", "on_3b"]),
                ["on_1b", "on_2b", "on_3b", ],
            ),
            (
                "compute_net_score",
                ComputeNetScore(output_col="net_score"),
                ["bat_score", "fld_score", ],
            ),
            (
                "compute_days_since_start",
                ComputeDaysSinceStart(output_col="days_since_start"),
                ["game_date", ],
            ),
            (
                "encode_handedness",
                EncodeHandedness(output_cols=["batter_stand", "pitcher_throws"]),
                ["stand", "p_throws", ],
            ),
            (
                "encode_inning",
                EncodeInningTopBot(output_col="topbot"),
                ["inning_topbot", ],
            ),
            (
                "batter_365_days_ma",
                MovingAverage(
                    output_cols=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "DP", "FO", "HBP", "SF", "SH", "wOBA", "mEV", "aEV", "pwOBA", "pPA"],
                    player_type="batter",
                    ma_days=365,
                    stats_to_compute=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "DP", "FO", "HBP", "SF", "SH", "wOBA", "mEV", "aEV", "pwOBA", "pPA"],
                    training_data_start_date=training_data_start_date, #date(2008, 2, 27),
                    training_data_end_date=training_data_end_date, #date(2023, 5, 3),
                    ma_start_date=ma365_start_date, #date(2009, 2, 26), # datetime(2022, 4, 7) + timedelta(365)
                ),
                ["game_date", "batter", "launch_speed", "p_throws", ],
            ),
            (
                "pitcher_365_days_ma",
                MovingAverage(
                    output_cols=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "DP", "FO", "HBP", "SF", "SH", "wOBA", "mEV", "aEV", "pwOBA", "pPA"],
                    player_type="pitcher",
                    ma_days=365,
                    stats_to_compute=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "DP", "FO", "HBP", "SF", "SH", "wOBA", "mEV", "aEV", "pwOBA", "pPA"],
                    training_data_start_date=training_data_start_date, #date(2008, 2, 27),
                    training_data_end_date=training_data_end_date, #date(2023, 5, 3),
                    ma_start_date=ma365_start_date, #date(2009, 2, 26), # datetime(2022, 4, 7) + timedelta(365)
                ),
                ["game_date", "pitcher", "launch_speed", "stand", ],
            ),
            (
                "batter_30_days_ma",
                MovingAverage(
                    output_cols=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "wOBA"],
                    player_type="batter",
                    ma_days=30,
                    stats_to_compute=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "wOBA"],
                    training_data_start_date=training_data_start_date, #date(2008, 2, 27),
                    training_data_end_date=training_data_end_date, #date(2023, 5, 3),
                    ma_start_date=ma30_start_date, #date(2008, 3, 28), # datetime(2022, 4, 7) + timedelta(30)
                ),
                ["game_date", "batter", "launch_speed", "p_throws", ],
            ),
            # (
            #     "pitcher_30_days_ma",
            #     MovingAverage(
            #         output_cols=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "wOBA"],
            #         player_type="pitcher",
            #         ma_days=30,
            #         stats_to_compute=["PA", "1B", "2B", "3B", "HR", "BB", "SO", "wOBA"],
            #         training_data_start_date=training_data_start_date, #date(2008, 2, 27),
            #         training_data_end_date=training_data_end_date, #date(2023, 5, 3),
            #         ma_start_date=ma30_start_date, #date(2008, 3, 28), # datetime(2022, 4, 7) + timedelta(30)
            #     ),
            #     ["game_date", "pitcher", "launch_speed", "stand", ],
            # ),
            (
                "head_to_head",
                HeadToHead(
                    output_cols=["1B", "2B", "HR", "BB", "SO", "PA", "wOBA"],
                    stats_to_compute=["1B", "2B", "HR", "BB", "SO", "PA", "wOBA"],
                ),
                ["batter", "pitcher", ],
            ),
            (
                "ball_park",
                ParkFactor(
                    output_cols=["1B", "2B", "3B", "HR", "BB"],
                    stats_to_compute=["1B", "2B", "3B", "HR", "BB"],
                    park_factors_file_path=os.path.join(ROOT_DIR, "intermediate/park_factors.json"),
                ),
                ["home_team", "game_year", ],
            ),
        ],
        remainder='drop',
    )

    data_pipeline = Pipeline(
        [
            ("preprocessors", preprocessors),
            ("feature_transformers", feature_transformers),
        ]
    )
    return data_pipeline


import torch
import torch.nn as nn
import numpy as np

def softmax(x):
    return np.exp(x) / np.sum(np.exp(x), axis=0)

def cross_entropy(actual, preds):
    loss = -np.sum(actual * np.log(preds))
    return loss / float(preds.shape[0])

x = np.array([2.0, 1.0, 0.1])
outputs = softmax(x)
print("softmax numpy: ", outputs)

# Torch Softmax
x = torch.tensor([2.0, 1.0, 0.1])
print(torch.softmax(x, dim=0))

###############
# Cross Entropy
###############
Y = np.array([1, 0, 0])
# y_pred has probabilities
Y_pred_good = np.array([0.7, 0.2, 0.1])
Y_pred_bad = np.array([0.1, 0.3, 0.6])
l1 = cross_entropy(Y, Y_pred_good)
l2 = cross_entropy(Y, Y_pred_bad)
print(f'Loss1 numpy: {l1:.4f}')
print(f'Loss2 numpy: {l2:.4f}')

# Torch Cross Entropy Loss
"""
nn.CrossEntropyLoss:
It applies nn.LogSoftmax + nn.NLLLoss (negative log likehood loss)
So, there is no Softmax in last Layer!
Y has class labels, not One-Hot!
Y_pred has raw scores (logits), no Softmax!

"""

loss = nn.CrossEntropyLoss()
Y = torch.tensor([2, 0, 1]) # not one-hot encoding
# Nsamplses x Nclasses = 3 x 3
Y_pred_good = torch.tensor([[0.1, 2.0, 3.0],
                            [2.0, 1.0, 0.1],
                            [2.0, 3.0, 0.1]
                            ]) # Not apply softmax
Y_pred_bad = torch.tensor([[2.1, 1.0, 0.1],
                            [0.1, 1.0, 2.1],
                            [2.0, 0.1, 3.1]
                            ]) # Not apply softmax

l1 = loss(Y_pred_good, Y)
l2 = loss(Y_pred_bad, Y)

print(l1.item()) # 0.11..
print(l2.item()) # 0.76..

_, predictions1 = torch.max(Y_pred_good, 1)
_, predictions2 = torch.max(Y_pred_bad, 1)
print(predictions1) # [2, 0, 1]
print(predictions2) # [0, 2, 2]


import numpy as np
import os
from PIL import Image
import pandas as pd
import argparse
import thread, time
from colorama import init
from termcolor import colored
import logging

values=[]
compared=[]

def compare(file1, path2):
  im = [None, None]
  im[0] = (np.array(Image.open(file1))).astype(np.int)
  for file2 in os.listdir(path2):
    compared.append(file1 + ' - ' + file2)
    try:
      im[1] = (np.array(Image.open(path2+'/'+file2))).astype(np.int)
      c=np.abs(im[0] - im[1]).sum()
      if c <= 500:
        values.append((file1.split("/")[-1],file2,c))
        logging.warning(colored("\tPositive (<treshold): "+ file1 + " " + file2 + "Treshold: "+str(c), "yellow", "on_blue"))
    except:
      logging.warning(colored("\tComparisson error: "+file1+ " vs "+ file2, "yellow", "on_blue"))

def thumbnails(path):
  for file1 in os.listdir(path):
    try:
      img=Image.open(path + "/" + file1).convert('L').resize((32,32), resample=Image.BICUBIC)
      img.save(path + "../thumbX/" + file1)
    except:
      pass

if __name__=='__main__':
  import sys
  init()
  logging.warning(colored('image comparer. Identify equal or similar images in two folders', "green"))
  parser = argparse.ArgumentParser(description='image comparer. Identify equal or similar images in two folders.')
  parser.add_argument('-p1','--path1', help='path for the first folder containing only images', required=True)
  parser.add_argument('-p2','--path2', help='path for the second folder containing only images', required=True)
  parser.add_argument('-c','--case', help='casename, for results filename', required=True)
  args = parser.parse_args()
  argsdict = vars(args)
  path1 = argsdict['path1']
  path2 = argsdict['path2']
  logging.warning(colored("Comparing images using resize(32x32), Gray Scale and verifying pizel by pixel. (Treshold < 500)","yellow"))
  logging.warning(colored("\tpaths: "+ path1 + " " + path2, "yellow"))
  values.append((path1,path2,"compare"))
  logging.warning("\tCreating thumbnails for images on paths ")

  for path in values[0][:2]:
    if not os.path.exists(path + "../thumbX/"):
      os.makedirs(path + "../thumbX/")
    logging.warning(colored("\t - Working on path "+path, "yellow"))
    thumbnails(path)

  logging.warning("\tComparing thumbails ...")
  num_files=len(os.listdir(path1 + "../thumbX/"))*len(os.listdir(path2 + "../thumbX/"))
  logging.warning(colored("\n - Total images to compare: "+ str(num_files) + "\n", "yellow"))
  for file1 in os.listdir(path1 + "../thumbX/"):
     thread.start_new_thread(compare, (path1+"../thumbX/"+file1, path2+"../thumbX/"))
  p=0
  while len(compared) != num_files:
    p=p+1
    if p%2==0:
      logging.warning("\tCompared files: "+str(len(compared)))
    time.sleep(5)

  with open(argsdict['case']+'.txt', 'w') as f:
      for img in values:
        f.write("%s\n" %str(img) )

  logging.warning(colored("Comparison finished.","green"))


# This module's future home should be inside userdata/addon_data/script.cinema.experience/ha_scripts
# to make sure it does not get over written when updating the script

import xbmc, xbmcaddon

_A_ = xbmcaddon.Addon('script.cinema.experience')
_L_ = _A_.getLocalizedString
_S_ = _A_.getSetting

def activate_on( trigger = "None" ):
    """
        Scripting to trigger almost anything(HA, other scripts, etc...) when videos start.

        Usage:
            activate_on( "Movie" )
            will trigger code that is set under the Movie heading.

    """
    if trigger == "None":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - No Trigger Sent, Returning", level=xbmc.LOGNOTICE )
        return
    xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - activate_on( %s ) Triggered" % trigger, level=xbmc.LOGNOTICE )
    # Script Start
    if trigger == _L_( 32613 ) and _S_( "ha_script_start" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32613 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Trivia Intro
    elif trigger == _L_( 32609 ) and _S_( "ha_trivia_intro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32609 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Trivia
    elif trigger ==_L_( 32615 ) and _S_( "ha_trivia_start" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32615 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Trivia Outro
    elif trigger ==_L_( 32610 ) and _S_( "ha_trivia_outro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32610 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Movie Theatre Intro
    elif trigger ==_L_( 32607 ) and _S_( "ha_mte_intro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32607 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Coming Attractions Intro
    elif trigger ==_L_( 32600 ) and _S_( "ha_cav_intro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32600 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Trailer
    elif trigger ==_L_( 32605 ) and _S_( "" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32605 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Coming Attractions Outro
    elif trigger ==_L_( 32608 ) and _S_( "ha_cav_outro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32608 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Feature Presentation Intro
    elif trigger ==_L_( 32601 ) and _S_( "ha_fpv_intro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32601 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # MPAA Rating
    elif trigger ==_L_( 32603 ) and _S_( "ha_mpaa_rating" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32603 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Countdown
    elif trigger ==_L_( 32611 ) and _S_( "ha_countdown_video" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32611 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Audio Format
    elif trigger ==_L_( 32606 ) and _S_( "ha_audio_format" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32606 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Movie
    elif trigger ==_L_( 32616 ) and _S_( "ha_movie" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32616 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Feature Presentation Outro
    elif trigger ==_L_( 32602 ) and _S_( "ha_fpv_outro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32602 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Movie Theatre Intro
    elif trigger ==_L_( 32617 ) and _S_( "ha_mte_outro" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32617 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Intermission
    elif trigger ==_L_( 32612 ) and _S_( "ha_intermission" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32612 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Script End
    elif trigger ==_L_( 32614 ) and _S_( "ha_script_end" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32614 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Paused
    elif trigger ==_L_( 32618 ) and _S_( "ha_paused" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32618 ), level=xbmc.LOGNOTICE )
        # place code below this line
    # Resumed
    elif trigger ==_L_( 32619 ) and _S_( "ha_resumed" ) == "true":
        xbmc.output( "[script.cinema.experience] - [ home_automation.py ] - %s Triggered" % _L_( 32619 ), level=xbmc.LOGNOTICE )
        # place code below this line


# Import statements

# Functions go here

# Checks that ticket name is not blank
def not_blank(question):
    valid = False

    while not valid:
        response = input(question)

        # If the name is not blank, program continues
        if response != "":
            return response

        # If the name is blank, show error and repeat the loop
        else:
            print("Sorry - this can't be blank, please enter your name")

# Checks for an integer more than 0
def int_check(question):

    error = "Please enter a whole number that is more than 0"

    valid = False
    while not valid:

        # ask user for number and check it is valid
        try:
            response = int(input(question))

            # if the response is zero or lower print an error
            if response <= 0:
                print(error)

            # if the response is greater than zero, the code continues
            else:
                return response

        # if an integer is not entered, display an error
        except ValueError:
            print(error)

# ----- Main Routine -----

# Set up dictionaries / lists needed to hold data

# Ask user if they have used the program before & show instructions if answer is no

# Loop to get ticket details
MAX_TICKETS = 5

name = ""
ticket_count = 0
ticket_sales = 0

while name != "xxx" and ticket_count < MAX_TICKETS:

    # print number of tickets left
    if ticket_count < MAX_TICKETS - 1:
        print("You have {} seats left".format(MAX_TICKETS - ticket_count))

    # Warns user that only one seat is left
    else:
        print("*** There is only ONE seat left! ***")

    # Get name (can't be blank), if the name is not 'xxx' add one to the ticket_counter
    name = not_blank("Name: ")

    if name == "xxx":
        break

    # Get age (between 12 and 130)
    age = int_check("Age: ")
    print()

    # Check that age is valid
    if age < 12:
        print("Sorry, you are too young for this movie")
        continue

    elif age > 130:
        print("That is very old - it looks like a mistake")
        continue

    # Calculate ticket price
    if age < 16:
        ticket_price = 7.5
    elif age < 65:
        ticket_price = 10.5
    else:
        ticket_price = 6.5

    ticket_count += 1
    ticket_sales += ticket_price

    # Loop to ask for snacks

    # Calculate snack price

    # Ask for payment method (apply surcharge if needed)

# End of ticket loop

# Calculate ticket profit
print()
ticket_profit = ticket_sales - (5 * ticket_count)
print("Ticket profit: ${:.2f}".format(ticket_profit))

# If all tickets are sold print statement
if ticket_count == MAX_TICKETS:
    print()
    print("You have sold all the available tickets!")

# If not all tickets are sold, print how many were sold and how many were left
else:
    print()
    print("You have sold {} tickets. \n"
          "There are {} places still available".format(ticket_count, MAX_TICKETS - ticket_count))

# Output data to text file


import asyncio

def format_response(given_command_type: str, command_dict: dict, execution_result: str) -> dict:
    """Format the response to be sent back to the client."""
    math_expression = command_dict.get("expression", None)
    output = {
        given_command_type: command_dict.get('command_name', math_expression) + " " + " ".join(
            command_dict.get("parameters", [])),
        "result": execution_result
    }
    return output

async def systemic_processing(command_name: str, parameters: list) -> str:
    """Perform some systemic processing on the command."""
    proc = await asyncio.create_subprocess_exec(command_name, *parameters, stdout=asyncio.subprocess.PIPE,
                                                stderr=asyncio.subprocess.PIPE)
    await proc.wait()
    result = await proc.stdout.read()

    # If the result is empty, then there was an error
    if result == b'':
        result = await proc.stderr.read()

    return result.decode()

async def computational_command_processing(expression: str) -> str:
    result = eval(expression)
    return str(result)


#x,y=3,5
#cont=1
#while not(x%y==0 or y%x==0):                 #se utilza la variable while cuando la variable que este en el programa comiensa en cero
    #print(f'intento numero {cont}')
    #x=int(input('ingrese numero'))
    #y=int(input('ingrese numero'))
    #cont+=1

#print(f'{x} y {y} son factor')
import random
lista=[]
sum=0
total=0
prod=0
mayor=0
menor=0
moda=0
resta=0
contador=0
raiz=0
cuadrado=0
tam=random.randint(10,11)
print(tam)
for i in range(tam):
    num=random.randrange(5)
    lista.append(num)
    print(lista)

for i in range(len(lista)):
    sum+=lista[i]
    total=sum
    prod=total//len(lista)
    print(f"la suma total{total} ")
    print(f"promedio es {prod}")

for i in lista:
    if i >mayor:
        mayor=i
    if i <menor:
        menor=i
    print(f"el mayor es={mayor}")
    print(f"el menor es={menor}")

for i in lista:
    if tam==i:
     moda=i
    print(f"la moda es={moda}")

for i in range(tam):
    num = random.randrange(5)
    lista.append(num)

print(lista)

desviacion_estandar = (lista)
print("La desviación estándar de la lista es:", desviacion_estandar)

for i in range(tam):
    num = random.randrange(5)
    lista.append(num)

print(lista)


# This file contains code for finding occurrences of techniques in a hobby training log
#
# Author: Josh McIntyre
#

import re
import csv

import config

# Build a regular expression from technique name variations
def build_regex(technique_variations):

    regex_str = "|".join(technique_variations) if len(technique_variations) > 1 else technique_variations[0]
    regex = re.compile(regex_str, re.IGNORECASE)

    return regex

# Find all instances of the specified regex
def count_instances(data, regex):

    count = 0
    for row in data:
        if regex.search(row[config.HEADER]):
            count += 1

    return count

# Parse the CSV log
def parse_log(log):

    data = []
    with open(log) as f:
        dr = csv.DictReader(f)
        for row in dr:
            data.append(row)

    return data

# The main entry point for the program
def main():

    data = parse_log(config.LOGFILE)
    for variation_list in config.TECHNIQUE_VARIATIONS:
        regex = build_regex(variation_list)
        name = variation_list[0]
        count = count_instances(data, regex)
        print(f"Instances of technique {name}: {count}")

if __name__ == "__main__":
    main()


import sys
from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter, QColor, QFont
from PyQt6.QtCore import Qt

# We begin with drawing some Unicode text on the client area of a window.
class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.text = None
        self.initUI()

    def initUI(self):
        self.text = "Shaxzodbek Sobitov Ravshan o'g'li\nInagamova Shoira"

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Drawing text')
        self.show()

    # In our example, we draw some text in Cylliric.
    # The text is vertically and horizontally aligned.
    def paintEvent(self, event):
        # Drawing is done within the paint event.
        qp = QPainter()
        qp.begin(self)

        """
        The QPainter class is responsible for all the low-level painting.
        All the painting methods go between begin and end methods.
        The actual painting is delegated to the drawText method.
        """
        self.drawText(event, qp)
        qp.end()

    def drawText(self, event, qp):
        # Here we define a pen and a font which are used to draw the text.
        qp.setPen(QColor(168, 34, 3))
        qp.setFont(QFont('Decorative', 10))

        """
        The drawText method draws text on the window.
        The rect method of the paint event returns the rectangle that needs to be updated.
        With the Qt.Alignment.AlignCenter we align the text in both dimensions.
        """
        qp.drawText(event.rect(), Qt.AlignmentFlag.AlignCenter, self.text)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()