'''
this is a skeleton code to integrate OpenGL and OpenCV in python

it is a translation (with minor modifications) of the cpp code found here:
http://www.cs.ucsb.edu/~holl/CS291A/opengl_cv.cpp

installation of related libraries:
pip install opencv-contrib-python
pip install PyOpenGL PyOpenGL_accelerate

you can invoke this script in two ways:
python OpenGL_CV.py                  -----> captures from webcam
python OpenGL_CV.py <video-filename> -----> captures from the video file

2019, Nazmus Saquib
'''

import cv2
import numpy as np
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math
#from scipy import linalg

board_width=8
board_height=6
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((board_height*board_width,3), np.float32)
objp[:,:2] = np.mgrid[0:board_width,0:board_height].T.reshape(-1,2)
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

dist = np.array([[ 0.05267650832192627, -0.4956190413924691, 0.0052524038601472495, 0.003143951311043761, 1.7247203077112738]])
mtx = np.array([[654.0386532237726, 0., 327.34270215404126],
                [0., 654.9263071068098, 251.69899149056258],
                [0., 0., 1.]])

# my calibration matrix
#dist = np.array([[ 0.09016813588756717, -0.196871593424749, -0.005570823681104732, -0.0011444615644275139, -0.11395723224378385]])
#mtx = np.array([[910.8843804968606, 0., 620.0830549034282],
#                [0., 914.9719257777986, 373.9797758912618],
#                [0., 0., 1.]])

H_IDX = 0 # calling shape on frame returns tuple, 0th index represents height
W_IDX = 1 # calling shape on frame returns tuple, 1st index represents width

axis = np.float32([[3,0,0], [0,3,0], [0,0,-3]]).reshape(-1,3)

class OpenGL_CV:

    def __init__(self, source):
        self.cap = cv2.VideoCapture(source)
        if self.cap.isOpened() == False:
            print("Error opening video stream...exiting")
            sys.exit(0)
        self.width = int(self.cap.get(3))
        self.height = int(self.cap.get(4))
        self.frame = None
        self.flipped_frame = None
        pass

    def draw_axes(self, length):
        '''a useful function to display your coordinate system'''
        glPushAttrib(GL_POLYGON_BIT | GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        glDisable(GL_LIGHTING)

        glBegin(GL_LINES)
        glColor3f(1,0,0)
        glVertex3f(0,0,0)
        glVertex3f(length,0,0)

        glColor3f(0,1,0)
        glVertex3f(0,0,0)
        glVertex3f(0,length,0)

        glColor3f(0,0,1)
        glVertex3f(0,0,0)
        glVertex3f(0,0,length)
        glEnd()

        glPopAttrib()

    def drawAxis(self, img, corners, imgpts):
        corner = tuple(corners[0].ravel())
        img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5)
        img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5)
        img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5)
        return img

    def drawTeaPot(self):
        # you will have to set modelview matrix using extrinsic camera params
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        #gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)

        ########################################################################################################################
        # drawing routine

        #undistortion
        img = self.flipped_frame
        h,  w = img.shape[:2]
        newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))

        # undistort
        dst = cv2.undistort(img, mtx, dist, None, newcameramtx)

        # crop the image
        x,y,w,h = roi
        dst = dst[y:y+h, x:x+w]
        #cv2.imwrite('calibresult.png',dst)
        self.flipped_frame = dst

        gray = cv2.cvtColor(self.flipped_frame, cv2.COLOR_BGR2GRAY)
        ret, corners = cv2.findChessboardCorners(gray, (board_width, board_height), None)
        if ret == True:
            #corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
            corners2 = corners
            ret, rvecs, tvecs = cv2.solvePnP(objp, corners2, mtx, dist)

            rmtx = cv2.Rodrigues(rvecs)[0]

            view_matrix = np.array([[rmtx[0][0],rmtx[0][1],rmtx[0][2],tvecs[0]+board_width/2],
                                [rmtx[1][0],rmtx[1][1],rmtx[1][2],tvecs[1]+board_height/2+0.5],
                                [rmtx[2][0],rmtx[2][1],rmtx[2][2],tvecs[2]],
                                [0.0       ,0.0       ,0.0       ,1.0    ]])

            inverse_matrix = np.array([[ 1.0, 1.0, 1.0, 1.0],
                                   [1.0,1.0,1.0,1.0],
                                   [-1.0,-1.0,-1.0,-1.0],
                                   [ 1.0, 1.0, 1.0, 1.0]])

            view_matrix = view_matrix * inverse_matrix
            view_matrix = np.transpose(view_matrix)

            glPushMatrix()
            glLoadMatrixd(view_matrix)
            glutSolidTeapot(1.0)
            self.draw_axes(1.0)
            glPopMatrix()

    def drawSpheres(self):
        #glTranslatef(1.0, 1.0, 1.0)

        # you will have to set modelview matrix using extrinsic camera params
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        #gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)

        gray = cv2.cvtColor(self.flipped_frame, cv2.COLOR_BGR2GRAY)
        ret, corners = cv2.findChessboardCorners(gray, (board_width, board_height), None)

        #undistortion
        img = self.flipped_frame
        h,  w = img.shape[:2]
        newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))

        # undistort
        dst = cv2.undistort(img, mtx, dist, None, newcameramtx)

        # crop the image
        x,y,w,h = roi
        #dst = dst[y:y+h, x:x+w]
        #cv2.imwrite('calibresult.png',dst)
        self.flipped_frame = dst

        self.flipped_frame = cv2.drawChessboardCorners(self.flipped_frame, (board_width, board_height), corners, True)
        glDrawPixels(self.flipped_frame.shape[W_IDX], self.flipped_frame.shape[H_IDX], GL_BGR, GL_UNSIGNED_BYTE, self.flipped_frame)

        if ret == True:
            #corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
            corners2 = corners
            print("corners2: "+str((corners2)))

            ret, rvecs, tvecs = cv2.solvePnP(objp, corners2, mtx, dist)
            print("rvecs: "+str(rvecs))
            print("tvecs: "+str(tvecs))
            rmtx = cv2.Rodrigues(rvecs)[0]

            # project 3D points to image plane
            #imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist)
            #self.flipped_frame = self.drawAxis(self.flipped_frame, corners2, imgpts)
            #glDrawPixels(self.flipped_frame.shape[W_IDX], self.flipped_frame.shape[H_IDX], GL_BGR, GL_UNSIGNED_BYTE, self.flipped_frame)

            view_matrix = np.array([[rmtx[0][0],rmtx[0][1],rmtx[0][2],tvecs[0]+0.5],
                                [rmtx[1][0],rmtx[1][1],rmtx[1][2],tvecs[1]+0.5],
                                [rmtx[2][0],rmtx[2][1],rmtx[2][2],tvecs[2]],
                                [0.0       ,0.0       ,0.0       ,1.0    ]])

            inverse_matrix = np.array([[ 1.0, 1.0, 1.0, 1.0],
                                   [1.0,1.0,1.0,1.0],
                                   [-1.0,-1.0,-1.0,-1.0],
                                   [ 1.0, 1.0, 1.0, 1.0]])

            view_matrix = view_matrix * inverse_matrix
            view_matrix = np.transpose(view_matrix)

            glPushMatrix()
            glLoadMatrixd(view_matrix)
            self.draw_axes(1.0)
            for i in range(8):
                for j in range(6):
                    glutSolidSphere(0.2, 20, 20)
                    #print("corners[i]: "+str(corners2[i]))
                    glTranslatef(0, 1, 0)
                glTranslatef(1, 0, 0)
                glTranslatef(0, -6, 0)
            glPopMatrix()

    def display(self):
        # clear the window
        #glClear(GL_COLOR_BUFFER_BIT)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # show the current camera frame
        # based on the way opencv stores data, you need to flip it before displaying it
        self.flipped_frame = cv2.flip(self.frame, 0)
        glDrawPixels(self.flipped_frame.shape[W_IDX], self.flipped_frame.shape[H_IDX], GL_BGR, GL_UNSIGNED_BYTE, self.flipped_frame)

        ########################################################################################################################
        # here, set up new parameters to render a scene viewed from the camera

        # set viewport
        glViewport(0, 0, self.flipped_frame.shape[W_IDX], self.flipped_frame.shape[H_IDX])

        # set projection matrix using intrinsic camera params
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        # gluPerspective is arbitrarily set, you will have to determine these values based on the intrinsic camera parameters
        fovy = 2*math.atan(self.flipped_frame.shape[H_IDX]/(2*mtx[1,1]))*180/math.pi
        #fovx, fovy, _ = cv2.calibrationMatrixValues(mtx, (self.flipped_frame.shape[H_IDX], self.flipped_frame.shape[W_IDX]), 0)
        #print("fovy: "+str(fovy_old)+"::"+str(fovy))
        gluPerspective(fovy, self.flipped_frame.shape[W_IDX] * 1.0 / self.flipped_frame.shape[H_IDX], 0.01, 200)

        #self.drawTeaPot()
        self.drawSpheres()

        '''# now that the camera params have been set, draw your 3D shapes
        # first, save the current matrix
        glPushMatrix()
        # move to the position where you want the 3D object to go
        glTranslatef(0, 0, 0) # this is an arbitrary position for demonstration
        # you will need to adjust your transformations to match the positions where
        # you want to draw your objects(i.e. chessboard center, chessboard corners)
        glutSolidTeapot(0.5)
        # glutSolidSphere(.3, 100, 100);
        self.draw_axes(1.0)
        glPopMatrix()'''

        # show the rendering on the screen
        glutSwapBuffers()

        # post the next redisplay
        glutPostRedisplay()

    def reshape(self, w, h):
        '''set openGL viewport (drawable area)'''
        glViewport(0, 0, w, h)

    def mouse(self, button, state, x, y):
        if button == GLUT_LEFT_BUTTON and state == GLUT_UP:
            pass

    def keyboard(self, key, x, y):
        if key == b'q':
            # quit when 'q' is pressed
            sys.exit(0)
        elif key == b's':
            cv2.imwrite('screenshot'+'.png', self.frame)
        else:
            pass

    def idle(self):
        '''grabs a frame from the camera'''
        ret, frame = self.cap.read()
        if ret == False:
            print('no frames to grab, exiting')
            sys.exit(0)
        self.frame = frame

def main(argv):
    if len(argv) == 1:
        source = 0
    else:
        source = argv[1]

    ogl_cv = OpenGL_CV(source)
    ogl_cv.idle()

    # initialize GLUT
    glutInit()
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowPosition(20, 20)
    glutInitWindowSize(ogl_cv.width, ogl_cv.height)
    glutCreateWindow("OpenGL / OpenCV Example")

    #shading in openGL
    glShadeModel(GL_SMOOTH)
    #glEnable(GL_CULL_FACE)
    #glEnable(GL_DEPTH_TEST)
    glClearDepth(1.0)
    glEnable(GL_LIGHTING)
    lightZeroPosition = [-20.,2.,-2.,1.]
    lightZeroColor = [1.8,1.0,0.8,1.0] #green tinged
    glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor)
    glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1)
    glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05)
    glEnable(GL_LIGHT0)

    # set up GUI callback functions
    glutDisplayFunc(ogl_cv.display)
    glutReshapeFunc(ogl_cv.reshape)
    glutMouseFunc(ogl_cv.mouse)
    glutKeyboardFunc(ogl_cv.keyboard)
    glutIdleFunc(ogl_cv.idle)

    # start GUI loop
    #while(1):
    glutMainLoop()

if __name__ == '__main__':
    main(sys.argv)


class Solution:
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ''.join(c*-n for n,c in sorted((-s.count(c),c)for c in set(s)))

if __name__ == "__main__":
    s = "abcc"
    print(Solution().frequencySort(s))


import random
from copy import deepcopy

from typing import List
from behaviors import common_behaviors

class BehaviorLists():
    """A list of all the available nodes."""

    def __init__(
        self,
        fallback_nodes: List[str] = None,
        sequence_nodes: List[str] = None,
        condition_nodes: List[str] = None,
        action_nodes: List[str] = None,
        root_nodes: List[str] = None
    ):
        # A list of all types of fallback nodes used, typically just one
        if fallback_nodes is not None:
            self.fallback_nodes = fallback_nodes
        else:
            self.fallback_nodes = ['f(']

        # A list of all types of sequence nodes used, typically just one
        if sequence_nodes is not None:
            self.sequence_nodes = sequence_nodes
        else:
            self.sequence_nodes = ['s(']

        # Control nodes are nodes that may have one or more children/subtrees.
        # Subsequent nodes will be children/subtrees until the related up character is reached.
        # List will contain fallback_nodes, sequence_nodes and any other control nodes.
        self.control_nodes = self.fallback_nodes + self.sequence_nodes

        # Conditions nodes are childless leaf nodes that never return RUNNING state.
        self.condition_nodes = []
        if condition_nodes is not None:
            self.condition_nodes = condition_nodes

        # Action nodes are also childless leaf nodes but may return RUNNING state.
        self.action_nodes = []
        if action_nodes is not None:
            self.action_nodes = action_nodes

        # A list of all allowed root node types
        self.root_nodes = root_nodes

        # Atomic fallback nodes are fallback nodes that have a predetermined set of
        # children/subtrees that cannot be changed.
        # They behave mostly like action nodes except that they may not be
        # the children of fallback nodes. Length is counted as one.
        self.atomic_fallback_nodes = []

        # Atomic sequence nodes are sequence nodes that have a predetermined set of
        # children/subtrees that cannot be changed.
        # They behave mostly like action nodes except that they may not be
        # the children of sequence nodes. Length is counted as one.
        self.atomic_sequence_nodes = []

        # The up node is not a node but a character that marks the end of a control nodes
        # set of children and subtrees.
        self.up_node = [')']

        self.behavior_nodes =\
            self.action_nodes + self.atomic_fallback_nodes + self.atomic_sequence_nodes
        self.leaf_nodes = self.condition_nodes + self.behavior_nodes
        self.nonleaf_nodes = self.control_nodes + self.up_node

    def merge_behaviors(self, other_bl: 'BehaviorLists') -> None:
        """Merge this behaviors with those of another BehaviorList."""
        self.action_nodes += [
            node for node in other_bl.action_nodes if node not in self.action_nodes]
        self.condition_nodes += [
            node for node in other_bl.condition_nodes if node not in self.condition_nodes]
        self.atomic_fallback_nodes += [
            node for node in other_bl.atomic_fallback_nodes
            if node not in self.atomic_fallback_nodes]
        self.atomic_sequence_nodes += [
            node for node in other_bl.atomic_sequence_nodes
            if node not in self.atomic_sequence_nodes]
        self.fallback_nodes += [
            node for node in other_bl.fallback_nodes if node not in self.fallback_nodes]
        self.sequence_nodes += [
            node for node in other_bl.sequence_nodes if node not in self.sequence_nodes]

    def convert_from_string(self, behavior_tree):
        """ Converts nodes in behavior tree from string format to parameterized nodes """
        for i, node in enumerate(behavior_tree):
            if isinstance(node, str):
                for parameterized_node_template in self.action_nodes + self.condition_nodes:
                    if parameterized_node_template.name in node:
                        behavior_tree[i] = deepcopy(parameterized_node_template)
                        behavior_tree[i].set_parameters_from_string(node)
                        break

    def is_fallback_node(self, node: str) -> bool:
        """Is node a fallback node."""
        if node in self.fallback_nodes:
            return True
        return False

    def is_sequence_node(self, node: str) -> bool:
        """Is node a sequence node."""
        if node in self.sequence_nodes:
            return True
        return False

    def is_control_node(self, node: str) -> bool:
        """Is node a control node."""
        if node in self.control_nodes:
            return True
        return False

    def is_root_node(self, node: str) -> bool:
        """Is node a valid root node."""
        if self.root_nodes is not None and node not in self.root_nodes:
            return False
        return True

    def get_random_control_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random control node."""
        node = random.choice(self.control_nodes)

        return node

    def get_random_fallback_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random control node."""
        node = random.choice(self.fallback_nodes)

        return node

    def get_random_sequence_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random sequence node."""
        node = random.choice(self.sequence_nodes)

        return node

    def get_random_root_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random root node."""
        if self.root_nodes is not None:
            node = random.choice(self.root_nodes)
        else:
            node = random.choice(self.control_nodes)
        return node

    def is_condition_node(self, node: common_behaviors.ParameterizedNode) -> bool:
        # pylint: disable=no-self-use
        """Is node a condition node."""
        if isinstance(node, common_behaviors.ParameterizedNode):
            return node.condition
        return False

    def get_random_condition_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random condition node."""
        node = deepcopy(random.choice(self.condition_nodes))
        node.randomize_parameters()
        return node

    def is_action_node(self, node: common_behaviors.ParameterizedNode) -> bool:
        # pylint: disable=no-self-use
        """Is node an action node."""
        if isinstance(node, common_behaviors.ParameterizedNode):
            return not node.condition
        return False

    def get_random_action_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random condition node."""
        node = deepcopy(random.choice(self.action_nodes))
        node.randomize_parameters()
        return node

    def is_behavior_node(self, node: common_behaviors.ParameterizedNode) -> bool:
        # pylint: disable=no-self-use
        """Is node a behavior node."""
        if isinstance(node, common_behaviors.ParameterizedNode):
            return not node.condition
        return False

    def get_random_behavior_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random behavior node."""
        node = deepcopy(random.choice(self.behavior_nodes))
        node.randomize_parameters()
        return node

    def is_leaf_node(self, node: common_behaviors.ParameterizedNode) -> bool:
        """Is node a leaf node."""
        return isinstance(node, common_behaviors.ParameterizedNode)

    def get_random_leaf_node(self) -> common_behaviors.ParameterizedNode:
        """Return a random leaf node."""
        node = deepcopy(random.choice(self.leaf_nodes))
        node.randomize_parameters()
        return node

    def is_up_node(self, node: str) -> bool:
        """Is node an up node."""
        return node in self.up_node

    def get_up_node(self) -> str:
        """Return up node."""
        return self.up_node[0]

    def is_valid_node(self, node: common_behaviors.ParameterizedNode) -> bool:
        """Return True if node is valid node, False otherwise."""
        return isinstance(node, common_behaviors.ParameterizedNode) or node in self.nonleaf_nodes


from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import pygame
import sys
import os
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys, time

class MyWindow(QMainWindow):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setGeometry(200, 200, 300, 300)
        self.setWindowTitle("Coding with Andy!")
        self.initUI()

    def initUI(self):
        self.label = QtWidgets.QLabel(self)
        self.label.setText("My first label!")
        self.label.move(50, 50)

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("Click Me!")
        self.b1.clicked.connect(self.clicked)

    def clicked(self):
        print("Clicked button")
        #self.label.setText("you pressed the button! \n Boom!")
        #self.update()
        #self.label.repaint() # Need this to work on Mac OS
        self.hide()
        splash_screen()

    def update(self):
        self.label.adjustSize()

    def reshow_page(self):
        end_game_loop()
        self.show()

#def clicked():
#    print("clicked")

def window():
    app = QApplication(sys.argv)

    win = MyWindow()
    win.show()
    sys.exit(app.exec_())

    # Taking code to the class

    '''
    win = QMainWindow()

    win.setGeometry(200, 200, 300, 300)
    win.setWindowTitle("Coding with Andy!")

    label = QtWidgets.QLabel(win)
    label.setText("My first label!")
    label.move(50,50)

    b1 = QtWidgets.QPushButton(win)
    b1.setText("Click Me!")
    b1.clicked.connect(clicked) # Name of function with the ()
    '''

current_path = os.getcwd()
print(current_path)

app = QApplication(sys.argv)
win = MyWindow()
web = QWebEngineView()
web.load(QUrl("https://www.nintendo.co.uk/"))

#class Background(pygame.sprite.Sprite):
#    def __init__(self, image_file, location):
#        pygame.sprite.Sprite.__init__(self)  # call Sprite initializer
#        self.image = pygame.image.load(image_file)
#        self.rect = self.image.get_rect()
#        self.rect.left, self.rect.top = location

'''
pygame.init()
screen = pygame.display.set_mode((910, 607))

splash_screen_img = pygame.image.load(current_path+'/Images/artificial-intelligence-codes-developing-screen.jpg')

splash_screen_img.convert()
screen.fill([255, 255, 255])
rect = splash_screen_img.get_rect()
screen.blit(splash_screen_img, rect)

clock = pygame.time.Clock()
fps = 30

screen.fill([255, 255, 255])
rect = splash_screen_img.get_rect()
screen.blit(splash_screen_img, rect)
while True:

    pygame.display.update()
    clock.tick(fps)

clock.tick(fps)
'''

# initialize game engine
pygame.init()

#window_width = 910
#window_height = 607

animation_increment = 10
clock_tick_rate = 20

black = (0, 0, 0)
red = (200, 0, 0)
green = (0, 200, 0)

bright_red = (255, 0, 0)
bright_green = (0, 255, 0)

# Open a window
#size = (window_width, window_height)
#screen = pygame.display.set_mode(size)

# Set title to the window
pygame.display.set_caption("Hello World!")

dead = False

clock = pygame.time.Clock()
#background_image = pygame.image.load(current_path+'/Images/artificial-intelligence-codes-developing-screen.jpg').convert()
count = 0

# Creating text

def text_objects(text, font):
    text_surface = font.render(text, True, black)
    return text_surface, text_surface.get_rect()

def button(screen, msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    #print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, w, h))

        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic, (x, y, w, h))

    smallText = pygame.font.SysFont("comicsansms", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x+(w/2)), (y+(h/2)))
    screen.blit(textSurf, textRect)

def web_init():
    app = QApplication(sys.argv)
    web = QWebEngineView()
    web.load(QUrl("https://www.nintendo.co.uk/"))

    #########

def show_web_page():
    ###### Trying QT Web #######
    pygame.display.quit()
    reading = True
    #app, web = web_init()
    print("In show web page")
    web.show()

    while reading:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:

                # -> Figure out a better way to close the application
                #web.hide()
                #web_init()
                reading = False
                menu()
        #pygame.display.update()

def end_game_loop():
    dead = True
    window_width = 1024
    window_height = 640
    screen = set_screen_size(window_width, window_height)
    menu(screen)

dead = False

def menu(screen):
    print("In menu")
    pygame.display.set_caption("Main Menu")
    window_width = 1024
    window_height = 640
    #screen = screen_display
    screen = set_screen_size(window_width, window_height)

    count = 0
    dead = False

    background_image = pygame.image.load(
        current_path+'/Images/AI Brain.jpg').convert()
    #background_image = pygame.transform.scale(background_image, (1024,640))

    while(dead == False):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                dead = True

        screen.blit(background_image, [0, 0])

        mouse = pygame.mouse.get_pos()

        #print(mouse)

        if 150+100 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(screen, bright_green, (150, 450, 100, 50))
        else:
            pygame.draw.rect(screen, green, (150, 450, 100, 50))

        button(screen, "GO!", 150, 450, 100, 50, green, bright_green, splash_screen)
        button(screen, "Quit", 550, 450, 100, 50, red, bright_red, win.reshow_page)

        '''
        # Creating buttons
        #pygame.draw.rect(screen, (0, 255, 0), (150, 450, 100, 50))
        pygame.draw.rect(screen, (255, 0, 0), (550, 450, 100, 50)) # ('screen to place',('Colour'),(location))

        smallText = pygame.font.Font("freesansbold.ttf", 20)
        textSurf, textRect = text_objects("Button 1!", smallText)
        textRect.center = ((150+(100/2)), (450+(50/2)))
        screen.blit(textSurf, textRect)
        '''
        pygame.display.update()
        clock.tick(clock_tick_rate)
        count += 1

    pygame.display.quit()
    pygame.display.update()

def set_screen_size(width, height):
    size = (width, height)
    return pygame.display.set_mode(size)

def splash_screen():
    pygame.init()

    # Set title to the window
    pygame.display.set_caption("Hello World!")
    count = 0
    dead = False
    window_width = 910
    window_height = 607
    #size = (window_width, window_height)
    screen = set_screen_size(window_width, window_height)

    background_image = pygame.image.load(
        current_path + '/Images/artificial-intelligence-codes-developing-screen.jpg').convert()
    while(dead == False):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                dead = True

        screen.blit(background_image, [0, 0])

        pygame.display.update()
        clock.tick(clock_tick_rate)
        count += 1
        if count == 10:
            menu(screen)

#screen = set_screen_size(200, 200)

window()


import argparse
import csv
import uuid
import hashlib
import itertools
import pathlib
import json
import random
import copy
import requests
import traceback
import xml
import xml.etree.ElementTree as ET
import collections
from folioclient.FolioClient import FolioClient
from faker import Faker
from datetime import datetime, timedelta

class Worker:
    def __init__(self, folio_client, args):
        csv.register_dialect("tsv", delimiter="\t")
        self.folio_client = folio_client
        self.user_list = {}
        with open(args.file_path) as location_map_f:
            self.user_list = list(csv.DictReader(location_map_f, dialect="tsv"))

    def work(self):
        permissions = set()
        for user in self.user_list:
            permission = user["PERMISSION GROUP"].strip()
            user_id = user["USER ID"].strip()
            permissions.add(permission)
            url = f"{self.folio_client.okapi_url}/perms/users"
            print(f'checking for existing user{url}?query=(userId=="{user_id}")')
            req = requests.get(
                url + f'?query=(userId=="{user_id}")',
                headers=self.folio_client.okapi_headers,
            )
            if req.status_code == 200:
                resp = json.loads(req.text)
                if resp["totalRecords"] == 0:
                    permission_user = json.dumps(
                        {"userId": user_id, "permissions": [permission],}
                    )
                    print(
                        f"user {user_id}) not found. Adding Permissions User record {permission_user} to {url}"
                    )
                    post_resp = requests.post(
                        url,
                        headers=self.folio_client.okapi_headers,
                        data=permission_user,
                    )
                    if post_resp.status_code == 201:
                        print(f"OK! Added user {user_id} with permission {permission}")
                    else:
                        print(
                            f"ERROR {post_resp.status_code} adding user {user_id} with permission {permission} {post_resp.text}"
                        )
                else:
                    print(f"FOUND!\t{permission}\t{req.status_code}")
                    existing_perm_user = resp["permissionUsers"][0]
                    if permission not in existing_perm_user["permissions"]:
                        existing_perm_user["permissions"].append(permission)
                        print(
                            f"user {user_id}) found. Appending Permission to Permission User record {permission_user} to {url}"
                        )
                        put_resp = requests.put(
                            url + f"/{user_id}",
                            headers=self.folio_client.okapi_headers,
                            data=json.dumps(existing_perm_user),
                        )
                        if put_resp.status_code == 201:
                            print(
                                f"Successfully added user {user_id} with permission {permission}"
                            )
                        else:
                            print(
                                f"ERROR {put_resp.status_code} adding user {user_id} with permission {permission}"
                            )
                    else:
                        print("Already has permission")
            else:
                print(req.status_code)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "file_path", help=("path to CSV file with UserId and Permission id")
    )
    parser.add_argument(
        "okapi_url",
        help=(
            "url of your FOLIO OKAPI endpoint."
            "See settings->software version in FOLIO"
        ),
    )
    parser.add_argument(
        "tenant_id",
        help=("id of the FOLIO tenant. " "See settings->software version in FOLIO"),
    )
    parser.add_argument("username", help=("the api user"))
    parser.add_argument("password", help=("the api users password"))
    args = parser.parse_args()
    return args

def main():
    args = parse_args()
    folio_client = FolioClient(
        args.okapi_url, args.tenant_id, args.username, args.password
    )
    worker = Worker(folio_client, args)
    worker.work()

if __name__ == "__main__":
    main()


import serial.tools.list_ports
import time
import datetime
import info_multicont
from helpers import helper
import sqlite3
from services import sqlite_service

def query_probes():
	#store all connected ports in a list
	portsInfo = serial.tools.list_ports.comports()

	ComPorts = []
	for i in range(len(portsInfo)):
		ComPorts.append(portsInfo[i].device)

	#USB PORTS
	usbPorts = [port for port in ComPorts if 'USB' in port]
	print(usbPorts)
	ser = []  #List of objects of Serial instances
	for port in range(len(usbPorts)):
		conn = serial.Serial(
		port=usbPorts[port],
		baudrate=9600,
		parity=serial.PARITY_ODD,
		stopbits=serial.STOPBITS_ONE,
		bytesize=serial.EIGHTBITS,
		)
		ser.append(conn)

	MAC = helper.get_device_mac_address()
	print(MAC)
	for conn in ser:
		if conn.port == '/dev/ttyUSB0':
			address = [1,2,3]
			for add in address:
				try:
					Var = info_multicont.multiCont_Var()
					index = list(range(0,8))
					time.sleep(1)
					for i in index:
						try:
							command = Var.command(add, i)
							conn.write(bytearray(command))
							time.sleep(0.8)
							res = conn.read(size=conn.in_waiting)
							data = Var.responseData(res)
							#determine the flag type based on last enterted value
							cursor = sqlite_service.get_last_entered_pv_value(data['PV'][0]['Tank'], data['PV'][0]['MultiCONT'],'MTC' )
							last_pv = 0

							for (value) in cursor:
								last_pv = float(value[0])

							pv_flag = 0
							#print(data['PV'][0]['Value'])
							print('last pv '+' '+str(last_pv)+' new '+str(data['PV'][0]['Value']))
							if (last_pv-5 <= data['PV'][0]['Value'] <= last_pv+10):
								pv_flag = 1 #same value

							elif(data['PV'][0]['Value'] < last_pv-5):
								pv_flag = 2 #consumption

							else:#(data['PV'][0]['Value'] > last_pv+10):
								#Tolerance of 10 litres to account for noise
								pv_flag = 3 #delivery

							log = {
							"read_at": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
							"device_address": MAC,
							"multicont_polling_address": data['PV'][0]['MultiCONT'],
							"tank_index": data['PV'][0]['Tank'],
							"pv": data['PV'][0]['Value'],
							"pv_flag": pv_flag,
							"sv": data['SV'][0]['Value'],
							"controller_type" : 'MTC'
							}

							if  float(log['pv']) >= 1 or float(log['sv']) >= 1:
								sqlite_service.mtc_probe_log_insert_one(log)
								sqlite_service.update_tank_latest_reading(log)
						except IndexError:
                                                        log = {}
							#print('Tank {} not available.'.format(i))
				except IndexError:
					print('Cont address {} not available'.format(add))

def main():
	query_probes()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Mon Dec  5 00:08:19 2022

@author: glenm

Advent of Code Day 3 Solution

Problem:
The elf who loaded the rucksacks made a mistake by not placing
all of the necessary componennts in each compartment of the bag.

The compartments are found by taking the length of each element in the array and spliting it in half

Our goal is to find the letter that each compartment has in common.

Afterwards we can assign a numerical priority to them and find to sum of the priorities of those item types

Algorithm:

 1. Divide the current input array into two arrays for compartment 1 and compartment 2
 2. Convert the characters to their numerical equivalent from a dictionary
 3. Sort each array
 4. Use binary search to find which character/priority each array has in common
 5. Add the pirority number to a scoring array

"""
import string

def OpenText(Data):
    F = open(Data, 'r+')
    lines = [line for line in F.readlines()]
    F.close()

    return lines

# Example file for validation
#Day3 = OpenText("ExDay3.txt")

# Puzzle input file
Day3 = OpenText("Day3.txt")

def binary_search(arr_search, item):
    low = 0
    high = len(arr_search)-1

    while low <= high:
        mid = (low + high)
        guess = arr_search[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid -1
        else:
            low = mid +1
    return None

def Day3_Task1(data):
    # Scoring file
    score = []

    guide = []

    for char in string.ascii_lowercase:
        guide.append(char)

    for char in string.ascii_uppercase:
        guide.append(char)

    scoring_guide = dict(zip(guide, list(range(1, 53))))

    for compar in data:
        n = len(compar)

        if n%2 == 0:
            compar1 = compar[0:n//2]
            compar2 = compar[n//2:]

        else:
            compar1 = compar[0:(n//2+1)]
            compar2 = compar[(n//2):]

        # Decouples a string into an array for each characters
        list1 = []
        for element in range(0, len(compar1)-1):
            list1.append(compar1[element])

        list2 = []
        for element in range(0, len(compar2)-1):
            list2.append(compar2[element])

        # Changes letters for numbers
        list1_num = [scoring_guide.get(n, n) for n in list1]
        list2_num = [scoring_guide.get(n, n) for n in list2]

        list1_num.sort()

        list2_num.sort()

        for i in list1_num:

            x = binary_search(list2_num, i)

            if x != None:
                helper = x
                break
            else:
                continue

        score.append(list2_num[helper])

    return sum(score)

print(Day3_Task1(Day3))

# Task 2

def Day3_Task2(Data):
    # Scoring file
    score = []

    guide = []

    for char in string.ascii_lowercase:
           guide.append(char)

    for char in string.ascii_uppercase:
           guide.append(char)

    Scoring_guide = dict(zip(guide, list(range(1, 53))))

    begin = 0
    end = 2

    while end <= len(Day3):

        Set1 = set(Data[begin])
        Set2 = set(Data[end-1])
        Set3 = set(Data[end])

        Set1.discard("\n")
        Set2.discard("\n")
        Set3.discard("\n")

        begin = begin + 3
        end = end + 3

        # Finding the common element in all three sets
        common = Set1 & Set2 & Set3

        common_list = list(common)

        score.append(common_list[0])

    score_num = [Scoring_guide.get(n, n) for n in score]

    return sum(score_num)

print(Day3_Task2(Day3))

AdventOfCode2022_Py/Advent Of Code Day 3/AOC_Day3.py


import time
from collections import Counter
from operator import concat, length_hint
from os import name
import string

def getAssignments():
	assignmentList = []
	while True:
		assignmentName = input("What is the name of the assignment? (Press enter to finish) ")
		if assignmentName == "":
			break
		validLength = False
		time.sleep(0.3)
		print()
		while validLength == False:
			assignmentLength = input("What is the length (in hours) of the assignment? ")
			if not assignmentLength.isdigit():
				print("Invalid input")
			else:
				validLength = True
		validDay = False
		time.sleep(0.3)
		print()
		while validDay == False:
			assignmentDueDay = input("What day is the assignment due?\n(1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday) ")
			if not assignmentDueDay.isdigit() or (int(assignmentDueDay) > 7 or int(assignmentDueDay) <= 0):
				print("Invalid input")
			else:
				validDay = True
		time.sleep(0.3)
		print()
		assignmentList.append({"name":assignmentName, "day": int(assignmentDueDay), "length":int(assignmentLength), "hoursScheduled":0})
	assignmentList.sort(key=lambda x: x["length"], reverse=True)
	assignmentList.sort(key=lambda x: x["day"])
	print()
	time.sleep(0.4)
	return assignmentList

def getSchedule():
	dayFreeTimeDictionary = {}
	dayFreeTimeDictionary["Sunday"] = getFreeTimeInDay("Sunday")
	dayFreeTimeDictionary["Monday"] = getFreeTimeInDay("Monday")
	dayFreeTimeDictionary["Tuesday"] = getFreeTimeInDay("Tuesday")
	dayFreeTimeDictionary["Wednesday"] = getFreeTimeInDay("Wednesday")
	dayFreeTimeDictionary["Thursday"] = getFreeTimeInDay("Thursday")
	dayFreeTimeDictionary["Friday"] = getFreeTimeInDay("Friday")
	dayFreeTimeDictionary["Saturday"] = getFreeTimeInDay("Saturday")
	return dayFreeTimeDictionary

def isHoursValid(hours):
	if not hours.isdigit():
		return False
	if int(hours) > 24:
		return False
	return True

def getFreeTimeInDay(day):
	isValid = False
	while not isValid:
		freeTime = input("How many hours of free time do you have on " + day + "? ")
		isValid = isHoursValid(freeTime)
		if not isValid:
			print("Invalid input")
		time.sleep(0.3)
		print()
	return int(freeTime)

def makeSchedule(freeTimeInDays, assignments):
	schedule = [
		{"dayName":"Sunday", "freeTime":freeTimeInDays["Sunday"], "workUnits":[]},
		{"dayName":"Monday", "freeTime":freeTimeInDays["Monday"], "workUnits":[]},
		{"dayName":"Tuesday", "freeTime":freeTimeInDays["Tuesday"], "workUnits":[]},
		{"dayName":"Wednesday", "freeTime":freeTimeInDays["Wednesday"], "workUnits":[]},
		{"dayName":"Thursday", "freeTime":freeTimeInDays["Thursday"], "workUnits":[]},
		{"dayName":"Friday", "freeTime":freeTimeInDays["Friday"], "workUnits":[]},
		{"dayName":"Saturday", "freeTime":freeTimeInDays["Saturday"], "workUnits":[]}
		]
	for assignment in assignments:
		for i in range(assignment["day"]):
			assignmentHoursLeft = assignment["length"] - assignment["hoursScheduled"]
			if assignmentHoursLeft != 0:
				if schedule[i]["freeTime"] - len(schedule[i]["workUnits"]) != 0:
					if assignmentHoursLeft <= schedule[i]["freeTime"] - len(schedule[i]["workUnits"]):
						for x in range(assignmentHoursLeft):
							schedule[i]["workUnits"].append(assignment["name"])
							assignment["hoursScheduled"] += 1
					else:
						for x in range(schedule[i]["freeTime"] - len(schedule[i]["workUnits"])):
							schedule[i]["workUnits"].append(assignment["name"])
							assignment["hoursScheduled"] += 1
		if(assignment["hoursScheduled"] - assignment["length"] != 0):
			print(assignment["name"] + " is too long to complete in the free time given, " + str(assignment["length"] - assignment["hoursScheduled"]) + " more hours are needed.")
			print()
	return schedule

def main():
	dayFreeTimeDictionary = getSchedule()
	assignmentList = getAssignments()
	schedule = makeSchedule(dayFreeTimeDictionary, assignmentList)
	for day in schedule:
		scheduleMsg = "On " + day["dayName"] + " you will work on "
		assignmentsThatDay = day["workUnits"]
		assignmentAndHours = {}
		for i in assignmentsThatDay:
			assignmentAndHours[i] = assignmentsThatDay.count(i)
		assignmentNameList = assignmentAndHours.keys()
		stringList = []
		for assignment in assignmentNameList:
			hoursHolder = assignmentAndHours[assignment]
			stringList.append(assignment + " for " + str(hoursHolder) + " hours")
		if len(stringList) == 0:
			scheduleMsg += "nothing."
		elif len(stringList) == 2:
			scheduleMsg += stringList[0] + " and " + stringList[1]
		elif len(stringList) == 1:
				scheduleMsg += stringList[0] + "."
		else:
			for i in range(len(stringList)):
				if stringList[i] == stringList[-1]:
					scheduleMsg += "and " + stringList[i] + "."
				else:
					scheduleMsg += stringList[i] + ", "

		print(scheduleMsg)
		time.sleep(0.3)
		print()

main()


from django.conf.urls.defaults import *
from fashionista.socialgraph import views

urlpatterns = patterns('',
    url(
        r'^followers/(?P<username>[a-zA-Z0-9_-]+)/$',
        views.friend_list,
        {'list_type': 'followers'},
        name='sg_followers'
    ),
    url(
        r'^following/(?P<username>[a-zA-Z0-9_-]+)/$',
        views.friend_list,
        {'list_type': 'following'},
        name='sg_following'
    ),
    url(
        r'^mutual/(?P<username>[a-zA-Z0-9_-]+)/$',
        views.friend_list,
        {'list_type': 'mutual'},
        name='sg_mutual'
    ),
    url(
        r'^follow/(?P<username>[a-zA-Z0-9_-]+)/$',
        views.follow,
        name='sg_follow'
    ),
    url(
        r'^unfollow/(?P<username>[a-zA-Z0-9_-]+)/$',
        views.unfollow,
        name='sg_unfollow'
    ),
    url(
        r'^search/$',
        views.find_and_add,
        name='sg_find_add'
    ),
)


import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal

from mne import Annotations, events_from_annotations
from mne.chpi import read_head_pos
from mne.datasets import testing
from mne.io import read_raw_fif
from mne.preprocessing import (
    annotate_break,
    annotate_movement,
    annotate_muscle_zscore,
    compute_average_dev_head_t,
)
from mne.tests.test_annotations import _assert_annotations_equal

data_path = testing.data_path(download=False)
sss_path = data_path / "SSS"
pos_fname = sss_path / "test_move_anon_raw.pos"
raw_fname = sss_path / "test_move_anon_raw.fif"

@testing.requires_testing_data
@pytest.mark.parametrize("meas_date", (None, "orig"))
def test_movement_annotation_head_correction(meas_date):
    """Test correct detection movement artifact and dev_head_t."""
    raw = read_raw_fif(raw_fname, allow_maxshield="yes").load_data()
    pos = read_head_pos(pos_fname)
    if meas_date is None:
        raw.set_meas_date(None)
    else:
        assert meas_date == "orig"

    # Check 5 rotation segments are detected
    annot_rot, [] = annotate_movement(raw, pos, rotation_velocity_limit=5)
    assert annot_rot.orig_time == raw.info["meas_date"]
    assert annot_rot.duration.size == 5

    # Check 2 translation vel. segments are detected
    annot_tra, [] = annotate_movement(raw, pos, translation_velocity_limit=0.05)
    assert annot_tra.duration.size == 2

    # Check 1 movement distance segment is detected
    annot_dis, _ = annotate_movement(raw, pos, mean_distance_limit=0.02)
    assert annot_dis.duration.size == 1

    # Check correct trans mat
    annot_all_2 = annotate_movement(
        raw,
        pos,
        rotation_velocity_limit=5,
        translation_velocity_limit=0.05,
        mean_distance_limit=0.02,
    )[0]
    assert (
        annot_rot.orig_time
        == annot_tra.orig_time
        == annot_dis.orig_time
        == raw.info["meas_date"]
    )
    annot_all = annot_rot + annot_tra + annot_dis
    _assert_annotations_equal(annot_all_2, annot_all)
    assert annot_all.orig_time == raw.info["meas_date"]
    raw.set_annotations(annot_all)
    dev_head_t = compute_average_dev_head_t(raw, pos)

    dev_head_t_ori = np.array(
        [
            [0.9957292, -0.08688804, 0.03120615, 0.00698271],
            [0.09020767, 0.9875856, -0.12859731, -0.0159098],
            [-0.01964518, 0.1308631, 0.99120578, 0.07258289],
            [0.0, 0.0, 0.0, 1.0],
        ]
    )

    assert_allclose(dev_head_t_ori, dev_head_t["trans"], rtol=1e-5, atol=0)

    # Smoke test skipping time due to previous annotations.
    raw.set_annotations(Annotations([raw.times[0]], 0.1, "bad"))
    annot_dis, _ = annotate_movement(raw, pos, mean_distance_limit=0.02)
    assert annot_dis.duration.size == 1

@testing.requires_testing_data
@pytest.mark.parametrize("meas_date", (None, "orig"))
def test_muscle_annotation(meas_date, events):
    """Test correct detection muscle artifacts."""
    raw = read_raw_fif(raw_fname, allow_maxshield="yes").load_data()
    if meas_date is None:
        raw.set_meas_date(None)
    raw.notch_filter([50, 110, 150])
    # Check 2 muscle segments are detected
    annot_muscle, scores = annotate_muscle_zscore(raw, ch_type="mag", threshold=10)
    assert annot_muscle.orig_time == raw.info["meas_date"]
    onset = annot_muscle.onset * raw.info["sfreq"]
    if meas_date is not None:
        onset -= raw.first_samp
    onset = onset.astype(int)
    assert_array_equal(scores[onset].astype(int), np.array([23, 10]))
    assert annot_muscle.duration.size == 2
    raw.set_annotations(annot_muscle)

@testing.requires_testing_data
@pytest.mark.parametrize("meas_date", (None, "orig"))
def test_muscle_annotation_without_meeg_data(meas_date):
    """Call annotate_muscle_zscore with data without meg or eeg."""
    raw = read_raw_fif(raw_fname, allow_maxshield="yes")
    if meas_date is None:
        raw.set_meas_date(None)
    raw.crop(0, 0.1).load_data()
    raw.pick("stim")
    with pytest.raises(ValueError, match="No M/EEG channel types found"):
        annotate_muscle_zscore(raw, threshold=10)

@pytest.mark.parametrize("meas_date", (None, "orig"))
@testing.requires_testing_data
def test_annotate_breaks(meas_date):
    """Test annotate_breaks."""
    raw = read_raw_fif(raw_fname, allow_maxshield="yes")
    if meas_date is None:
        raw.set_meas_date(None)

    annots = Annotations(
        onset=[12, 15, 16, 20, 21],
        duration=[1, 1, 1, 2, 0.5],
        description=["test"],
        orig_time=raw.info["meas_date"],
    )

    if raw.info["meas_date"] is None:
        annots.onset -= raw.first_time

    raw.set_annotations(annots)

    min_break_duration = 0.5
    t_start_after_previous = 0.1
    t_stop_before_next = 0.1

    expected_onsets = np.array(
        [
            raw.first_time,
            13 + t_start_after_previous,
            17 + t_start_after_previous,
            22 + t_start_after_previous,
        ]
    )

    if raw.info["meas_date"] is None:
        expected_onsets -= raw.first_time

    expected_durations = np.array(
        [
            12 - raw.first_time - t_stop_before_next,
            15 - 13 - t_start_after_previous - t_stop_before_next,
            20 - 17 - t_start_after_previous - t_stop_before_next,
            raw._last_time - 22 - t_start_after_previous,
        ]
    )

    break_annots = annotate_break(
        raw=raw,
        min_break_duration=min_break_duration,
        t_start_after_previous=t_start_after_previous,
        t_stop_before_next=t_stop_before_next,
    )

    assert break_annots.orig_time == raw.info["meas_date"]
    assert_allclose(break_annots.onset, expected_onsets)
    assert_allclose(break_annots.duration, expected_durations)
    assert all(description == "BAD_break" for description in break_annots.description)

    # try setting the annotations, this should not omit anything
    raw.set_annotations(break_annots)
    current_annotations = raw.annotations
    if raw.info["meas_date"] is None:
        current_annotations.onset -= raw.first_time
    raw.set_annotations(current_annotations + break_annots)

    # reset before next test
    raw.set_annotations(annots)

    # `ignore` parameter should be respected
    raw.annotations.description[0] = "BAD_"
    break_annots = annotate_break(
        raw=raw,
        min_break_duration=min_break_duration,
        t_start_after_previous=t_start_after_previous,
        t_stop_before_next=t_stop_before_next,
    )

    assert_allclose(break_annots.onset, expected_onsets[[True, False, True, True]])
    assert_allclose(
        break_annots.duration,
        [15 - raw.first_time - t_stop_before_next] + list(expected_durations[2:]),
    )

    # try setting the annotations, this should not omit anything
    raw.set_annotations(break_annots)
    current_annotations = raw.annotations
    if raw.info["meas_date"] is None:
        current_annotations.onset -= raw.first_time
    raw.set_annotations(current_annotations + break_annots)

    # Restore annotations for next test
    raw.set_annotations(annots)
    raw.annotations.description[0] = "test"

    # Test with events
    events, _ = events_from_annotations(raw=raw)
    raw.set_annotations(None)

    expected_onsets = np.array(
        [
            raw.first_time,
            12 + t_start_after_previous,
            15 + t_start_after_previous,
            16 + t_start_after_previous,
            20 + t_start_after_previous,
            21 + t_start_after_previous,
        ]
    )

    expected_durations = np.array(
        [
            12 - raw.first_time - t_stop_before_next,
            15 - 12 - t_start_after_previous - t_stop_before_next,
            16 - 15 - t_start_after_previous - t_stop_before_next,
            20 - 16 - t_start_after_previous - t_stop_before_next,
            21 - 20 - t_start_after_previous - t_stop_before_next,
            raw._last_time - 21 - t_start_after_previous,
        ]
    )

    break_annots = annotate_break(
        raw=raw,
        events=events,
        min_break_duration=min_break_duration,
        t_start_after_previous=t_start_after_previous,
        t_stop_before_next=t_stop_before_next,
    )

    if raw.info["meas_date"] is None:
        expected_onsets -= raw.first_time

    assert_allclose(break_annots.onset, expected_onsets)
    assert_allclose(break_annots.duration, expected_durations)

    # try setting the annotations, this should not omit anything
    raw.set_annotations(break_annots)
    current_annotations = raw.annotations
    if raw.info["meas_date"] is None:
        current_annotations.onset -= raw.first_time
    raw.set_annotations(current_annotations + break_annots)

    # reset before next test
    raw.set_annotations(annots)

    # Not finding any break periods
    break_annots = annotate_break(
        raw=raw,
        events=events,
        min_break_duration=1000,
    )

    assert len(break_annots) == 0

    # Implausible parameters (would produce break annot of duration < 0)
    with pytest.raises(ValueError, match="must be greater than 0"):
        annotate_break(
            raw=raw,
            min_break_duration=5,
            t_start_after_previous=5,
            t_stop_before_next=5,
        )

    # Empty events array
    with pytest.raises(ValueError, match="events array must not be empty"):
        annotate_break(raw=raw, events=np.array([]))

    # Invalid `ignore` value
    with pytest.raises(TypeError, match="must be an instance of str"):
        annotate_break(raw=raw, ignore=("foo", 1))

    # No annotations to work with
    raw.set_annotations(None)
    with pytest.raises(ValueError, match="Could not find.*annotations"):
        annotate_break(raw=raw)


import re, sys

#pat = re.compile('[0-9]* (.*) ([a-z]*_[a-z_]*) (.*)')
pat = re.compile('[0-9]* (.*) ([a-z]*_[a-z_]*) (.*)')

for line in sys.stdin :
	m = pat.search(line)
	if m:
		relation = m.group(2)
		if relation in ['directed_by','starred_actors','written_by','has_genre','has_tags','in_language'] :
			answers = re.split(', ',m.group(3))
			for answer in answers :
				print('{}\t{}\t{}'.format(m.group(1).lower(),answer.lower(),relation ) )
		else :
			True
	else :
		True

#  grep -o '[a-z]*_[a-z_]*' movieqa/knowledge_source/wiki_entities/wiki_entities_kb.txt |sortnr
#  17341 has_plot
#  16726 release_year
#  15234 directed_by
#  13565 starred_actors
#  13130 written_by
#  12483 has_genre
#   9697 has_tags
#   3174 in_language
#    328 has_imdb_rating
#    122 has_imdb_votes


from random import random
import time

class str:
    '''
    >>> from shitpy import str
    >>> str(4) + str('abc')
    Life is not always what we want it to be (o_o)
    Wtf is this! I can't add it!
    But wait! I'll give you some random shit!
    12.9651505349 #some random number

    >>> str(45) + str(78)
    Life is not always what we want it to be (o_o)
    Computing some Shit!
    123
    '''
    def __init__(self, s):
        self.string = s

    def __add__(self, x):
        print("Life is not always what we want it to be (o_o)")
        time.sleep(2)
        a = self.string
        b = x.string
        try:
            a = int(a)
            b = int(b)
            print("Computing some Shit!")
            c = a + b
            time.sleep(2)
            return str(c)
        except:
            print("Wtf is this! I can't add it!")
            time.sleep(2)
            print("But wait! I'll give you some random shit!")
            time.sleep(2)
            return str(random() * 100)

    def __str__(self):
        return "%s"%self.string

    def __repr__(self):
        return "%s"%self.string


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 24 14:51:43 2023

@author: hafizzzh
"""
import json
import time
import calendar
import hashlib
import requests
import pandas as pd
import os
from dotenv import load_dotenv

load_dotenv()
df_ev = pd.DataFrame()
getLoop = True

url = "https://gateway.marvel.com/v1/public/events"
name = ""
nameStartsWith = ""
modifiedSince = ""
creators = ""
characters = ""
series = ""
comics = ""
stories = ""
orderBy = "startDate"
limit = 100
offset = 0

current_GMT = time.gmtime()
ts = str(calendar.timegm(current_GMT))
pvkey = os.getenv("MARVEL_PVKEY")
pbkey = os.getenv("MARVEL_PBKEY")
assemble = ts+pvkey+pbkey
juru = hashlib.md5(assemble.encode())

while(getLoop):
    querystring = {"orderBy": str(orderBy),
                   "apikey": str(pbkey),
                   "ts": ts,
                   "hash": juru.hexdigest(),
                   "limit": limit,
                   "offset": offset}

    response = requests.request("GET",
                                url,
                                params=querystring)

    jsondata = json.loads(response.text)

    for i in range(limit):
        try:
            ev = jsondata['data']['results'][i]

            ev_id = ev['id']
            ev_title = ev['title']
            ev_start = ev['start']
            ev_end = ev['end']
            ev_next = ev['next']
            ev_previous = ev['previous']
            ev_modified = ev['modified']

            rev_row = pd.Series([ev_id, ev_title, ev_start, ev_end, ev_next, ev_previous, ev_modified])
            row_df_rev = pd.DataFrame([rev_row], index=[i+offset])

            df_ev = pd.concat([df_ev, row_df_rev])
        except IndexError:
             getLoop = False
             print("All Done. Retrieved items:", df_ev.shape[0])
             break
    print("\t offset", offset, ". limit:", limit, ". items: ", df_ev.shape[0])
    offset = limit+offset

df_ev = df_ev.rename(columns={
    0: "id",
    1: "title",
    2: "start",
    3: "end",
    4: "next",
    5: "previous",
    6: "modified"})
df_ev.to_csv("result_events.csv")


from tqdm import tqdm

import torch
from torch import nn
import torchvision
import torchvision.transforms as T

from lightly.models.modules import BarlowTwinsProjectionHead
from lightly.loss import BarlowTwinsLoss

from short_video_dataset import ShortVideoDataset

from augmentation import apply_transforms

class BarlowTwins(nn.Module):
    def __init__(self, backbone):
        super().__init__()
        self.backbone = backbone
        self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048)

    def forward(self, x):
        x = self.backbone(x).flatten(start_dim=1)
        z = self.projection_head(x)
        return z

def main():

    torch.manual_seed(42)

    resnet = torchvision.models.resnet34()
    backbone = nn.Sequential(*list(resnet.children())[:-1])
    backbone[0] = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
    model = BarlowTwins(backbone)

    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(device)
    model.to(device)

    dataset = ShortVideoDataset('video_short_half_res', transform=T.Compose([
        T.ToTensor(),
        T.CenterCrop(size=720)
    ]))

    dataloader = torch.utils.data.DataLoader(
        dataset,
        batch_size=64,
        shuffle=True,
        drop_last=True,
        num_workers=8,
    )

    criterion = BarlowTwinsLoss(lambda_param=1e-3)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.001, weight_decay=0.001)

    print("Starting Training")
    for epoch in range(1000):
        total_loss = 0
        for batch in tqdm(dataloader):
            x0 = apply_transforms(batch).to(device)
            x1 = apply_transforms(batch).to(device)
            z0 = model(x0)
            z1 = model(x1)
            loss = criterion(z0, z1)
            total_loss += loss.detach()
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
        avg_loss = total_loss / len(dataloader)
        print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")

        if avg_loss < 100:
            torch.save(model, 'models/model_bt.pth')
            break

if __name__ == '__main__':
    main()


from lona.html import Strong, Select, HTML, Div, H2, Br
from lona.static_files import Script
from lona._json import dumps
from lona.view import View

class TestWidget(Div):
    STATIC_FILES = [
        Script(name='TestWidget', path='widget_data.js'),
    ]

    WIDGET = 'widget_data'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.server_state = Div()

        self.nodes = [
            self.server_state,
            Div(_id='client-state'),
        ]

    def update_state(self):
        self.server_state.set_text(dumps(self.widget_data))

class WidgetDataView(View):
    def handle_request(self, request):
        widget = TestWidget()

        interval = Select(
            values=[
                (1,    '1s',    False),
                (0.5,  '0.5s',  True),
                (0.25, '0.25s', False),
                (0.01, '0.01s', False),
            ],
        )

        html = HTML(
            H2('Widget Data'),
            'This view tests the encoding and decoding of abstract widget data.',
            Br(),
            Br(),
            'The first value is the state the server has, the second is the '
            'second is the client state.',
            Br(),
            'Both values should be equal at all times.',
            Br(),
            Br(),

            Strong('Interval: '),
            interval,
            Br(),
            Br(),

            widget,
        )

        self.show(html)

        while True:
            # list
            widget.widget_data = {'list': []}

            for i in range(6):
                widget.widget_data['list'].append(i)
                widget.update_state()
                self.show(html)
                self.sleep(float(interval.value))

            widget.widget_data['list'].remove(2)
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))

            widget.widget_data['list'].insert(2, 2)
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))

            widget.widget_data['list'].clear()
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))

            widget.widget_data['list'] = [5, 4, 3, 2, 1]
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))

            # dict
            widget.widget_data = [{}]

            for i in range(6):
                widget.widget_data[0][i] = i
                widget.update_state()
                self.show(html)
                self.sleep(float(interval.value))

            widget.widget_data[0].pop(2)
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))

            widget.widget_data[0].clear()
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))

            widget.widget_data[0] = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
            widget.update_state()
            self.show(html)
            self.sleep(float(interval.value))


# python -m pip install selenium
# python -m pip install webdriver-manager
# python -m pip install beautifulsoup4
# python -m pip install Pillow

import os
from io import BytesIO
from PIL import Image
from base64 import b64decode
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

def scraper(url):
    # Set options for webdriver
    options = Options()
    options.headless = True  # hide GUI
    options.add_argument("--window-size=1920,1080")  # set window size to native GUI size
    options.add_argument("start-maximized")  # ensure window is full-screen
    options.add_argument("--log-level=3")  # suppress debug log

    # Configure Chrome browser to not load images and javascript
    options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})

    # Creating a new driver with ChromeDriverManager based in the service options
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

    driver.get(url)

    # Wait for page to load until expected conditions
    WebDriverWait(driver, timeout=5).until(
        EC.presence_of_element_located((By.ID, "XXXXXX")),
        EC.presence_of_element_located((By.CLASS_NAME, "XXXXXXXXXX"))
    )

    # Getting content
    content = driver.page_source

    # Parsing content
    soup = BeautifulSoup(content, "html.parser")

    print(" ")

    # Soup Query 1: Getting title
    header = soup.find("X", {"XXXXX": "XXXXXXXXXXX"})
    title = header.text

    # Soup Query 2: Getting pages
    slider = soup.find("XXX", {"XX": "XXXXXX"})
    pages = slider.find_all("XXX")

    # Detecting current chapter
    chap = url.split('/')[-1].split('#')[-1]

    # Detecting sources
    sources = len(pages)
    print("Detected pages: " + str(sources))

    # Making the output dir
    path = f"{os.getcwd()}\\{title}\\Cap. {chap}\\"
    os.makedirs(path)

    print("Created destination: " + path)

    print(f"\nDownloading {title} - Cap. {chap} ... \n")

    count = 1

    for page in pages:
        url = page["src"]

        # Forming the filename from last link resource
        filename = url.split('/')[-1]

        # Setting output
        out = path + "\\" + filename

        # Using the requests module gives a 1020 error code (missing headers to authentication), so as alternative:

        driver.get(url)

        # Using javascript to save a base64 img (a lite alternative to selenium-wire)
        b64img = driver.execute_script(r'''
        var img = document.getElementsByTagName("img")[0];
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
        ''')

        # Decode from base64, translate to bytes and write to PIL image
        raw = Image.open(BytesIO(b64decode(b64img)))
        img = raw.convert("RGB")
        img.save(out)

        # Progress stats
        print(filename + " was successful downloaded from:\n" + url)
        print(f"progress ({((count / sources) * 100):.1f}%): {count}/{sources} \n")
        count += 1

if __name__ == "__main__":
    import sys
    import getopt

    # Arguments
    arg_url = ""
    arg_help = "{0} -u <url>".format(sys.argv[0])

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hu:", ["help", "url="])
    except:
        # Any problem returns the helper arg.
        print(arg_help)
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print(arg_help)
            sys.exit(2)
        elif opt in ("-u", "--url"):
            arg_url = arg

    # Starting program
    scraper(arg_url)


import requests
import pickle
from bs4 import BeautifulSoup, Comment
import re
characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
              'v', 'w', 'x', 'y', 'z']
big_characters = [c.upper() for c in characters]

characters += big_characters
reg = r'[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]'
url = 'http://www.pythonchallenge.com/pc/def/banner.p'

if __name__ == '__main__':
    r = requests.get(url)
    print(r.content)
    uniq_res = []

    with open('banner.p', 'wb') as f:
        f.write(r.content)

    with open('banner.p', 'rb') as f:
        res = pickle.load(f)

    for r in res:
        print(''.join([elem[1]*elem[0] for elem in r]))


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

# In[24]:

## Loading similarity pairing
import pandas as pd

df = pd.read_excel(r'C:\Users\dinos\Desktop\Python Project\Similarity Rating.xlsx')
print(df)

# In[25]:

## Creating historgram for rating distribution
import matplotlib.pyplot as plt

n, bins, patches = plt.hist(x=df, bins='auto', color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Rating')
plt.ylabel('Frequency')
plt.title('Histogram of similarity rating')
maxfreq = n.max()

# In[27]:

## Finding quantile for buckets with 10 interval
import numpy as np

print("10th percentile of df is:",np.percentile(df, 10))
print("20th percentile of df is:",np.percentile(df, 20))
print("30th percentile of df is:",np.percentile(df, 30))
print("40th percentile of df is:",np.percentile(df, 40))
print("50th percentile of df is:",np.percentile(df, 50))
print("60th percentile of df is:",np.percentile(df, 60))
print("70th percentile of df is:",np.percentile(df, 70))
print("80th percentile of df is:",np.percentile(df, 80))
print("90th percentile of df is:",np.percentile(df, 90))

# In[34]:

## Similarity pairs list from rating 1 to 5 (1 = low similarity, 5 = high simialirty)
## See (Boles & Clifford, 1989) for more information on similarity matrix
## Bucket according to percentile
pairs_10 = [["i", "b"], ["i", "e"], ["k", "a"], ["l", "a"], ["l", "c"],
           ["l", "e"], ["m", "j"], ["m", 'l'], ["n", "k"], ["n", "l"],
           ["o", "f"], ["o", "k"], ["o", "l"], ["p", "l"], ["q", "i"],
           ["r", "l"], ["s", "h"], ["s", "k"], ["s", "l"], ["v",  "l"],
           ["w", "b"], ["w", "d"], ["w", "l"], ["w", "o"], ["x", "b"],
           ["x", "d"], ["x", "f"], ["x", "l"], ["x", "o"], ["x", "p"],
           ["y", "l"], ["z", "d"], ["z", "l"]]
pairs_20 = [["f", "c"], ["i", "c"], ["j", "a"], ["j", "b"], ["j", "e"],
           ["k", "e"], ["k", "f"], ["k", "i"], ["k", "j"], ["l", "g"],
           ["m", "b"], ["m", "k"], ["q", "k"], ["q", "m"], ["t", "a"],
           ["t", "e"], ["t", "o"], ["t", "q"], ["u", "f"], ["u", "l"],
           ["v", "a"], ["w", "e"], ["w", "f"], ["w", "g"], ["w", "h"],
           ["w", "i"], ["w", "j"], ["w", "k"], ["w", "t"], ["x", "g"],
           ["x", "h"], ["x", "i"], ["x", "j"], ["x", "n"], ["z", "b"],
           ["z", "f"], ["z", "g"], ["z", "o"], ["z", "q"]]
pairs_30 = [["f", "b"], ["h", "a"], ["i", "a"], ["i", "d"], ["i", "h"],
           ["k", "c"], ["m", "d"], ["m", "f"], ["p", "f"], ["q", "f"],
           ["q", "j"], ["q", "l"], ["v", "i"], ["v", "p"], ["w", "q"],
           ["w", "r"], ["x", "q"], ["x", "t"], ["y", "f"], ["y", "i"],
           ["z", "h"], ["z", "i"], ["z", "j"]]
pairs_40 = [["h", "g"], ["i", "f"], ["i", "g"], ["k", "g"], ["n", "f"],
            ["o", "i"], ["p", "i"], ["p", "m"], ["r", "k"], ["s", "f"],
            ["s", "i"], ["s", "j"], ["s", "q"], ["t", "m"], ["t", "n"],
            ["t", "s"], ["u", "k"], ["u", "t"], ["v", "b"], ["v", "d"],
            ["v", "e"], ["v", "f"], ["v", "g"], ["v", "m"], ["v", "q"],
            ["w", "a"], ["x", "a"], ["x", "w"], ["y", "a"], ["y", "t"],
            ["z", "k"]]
pairs_50 = [["f", "a"], ["f", "d"], ["h", "e"], ["h", "f"], ["l", "h"],
            ["m", "e"], ["m", "i"], ["n", "d"], ["n", "g"], ["n", "i"],
            ["o", "h"], ["o", "j"], ["p", "k"], ["r", "i"], ["s", "b"],
            ["s", "d"], ["s", "n"], ["t", "c"], ["t", "g"], ["t", "h"],
            ["t", "p"], ["u", "i"], ["u", "p"], ["u", "s"], ["v", "s"],
            ["w", "p"], ["x", "c"], ["x", "e"], ["y", "m"], ["y", "o"],
            ["y", "x"], ["z", "p"], ["z", "t"]]
pairs_60 = [["f", "e"], ["j", "c"], ["j", "d"], ["j", "h"], ["k", "d"],
            ["l", "b"], ["l", "d"], ["l", "k"], ["m", "c"], ["m", "g"],
            ["n", "b"], ["n", "j"], ["p", "n"], ["q", "h"], ["q", "n"],
            ["r", "g"], ["r", "q"], ["s", "m"], ["s", "o"], ["s", "r"],
            ["t", "k"], ["u", "b"], ["u", "g"], ["u", "q"], ["v", "k"],
            ["v", "t"], ["w", "c"], ["x", "m"], ["x", "s"], ["x", "u"],
            ["y", "r"], ["z", "n"], ["z", "v"], ["z", "y"]]
pairs_70 = [["d", "a"], ["d", "c"], ["e", "d"], ["g", "f"], ["l", "j"],
            ["m", "a"], ["m", "h"], ["n", "a"], ["n", "e"], ["o", "m"],
            ["p", "j"], ["q", "e"], ["r", "b"], ["r", "o"], ["s", "g"],
            ["t", "b"], ["t", "d"], ["t", "i"], ["t", "r"], ["u", "d"],
            ["u", "m"], ["v", "r"], ["x", "r"], ["y", "b"], ["y", "c"],
            ["y", "d"], ["y", "j"], ["y", "k"], ["y", "n"], ["z", "m"],
            ["z", "u"]]
pairs_80 = [["b", "a"], ["c","a"], ["h", "c"], ["k", "b"], ["l", "f"],
            ["o", "g"], ["o", "n"], ["p", "a"], ["p", "c"], ["p", "h"],
            ["q", "a"], ["q", "c"], ["q", "o"], ["r", "a"], ["r", "d"],
            ["r", "f"], ["r", "j"], ["s", "a"], ["s", "p"], ["u", "a"],
            ["u", "j"], ["v", "h"], ["v", "j"], ["v", "n"], ["w", "n"],
            ["w", "s"], ["y", "h"], ["y", "p"], ["y", "w"], ["z", "a"],
            ["z", "c"], ["z", "x"]]
pairs_90 = [["c", "b"], ["e", "b"], ["e", "c"], ["g", "a"], ["g", "b"],
            ["g", "c"], ["g", "e"], ["h", "d"], ["j", "f"], ["j", "g"],
            ["o", "a"], ["o", "b"], ["o", "d"], ["p", "e"], ["r", "c"],
            ["r", "e"], ["r", "m"], ["r", "n"], ["r", "p"], ["s", "c"],
            ["s", "e"], ["t", "j"], ["t", "l"], ["u", "e"], ["u", "h"],
            ["u", "o"], ["u", "r"], ["v", "c"], ["v", "o"], ["x", "v"],
            ["y", "q"], ["z", "e"], ["z", "w"]]
pairs_100 = [["d", "b"], ["e", "a"], ["g", "d"], ["h", "b"], ["j", "i"],
            ["k", "h"], ["l", "i"], ["n", "c"], ["n", "h"], ["n", "m"],
            ["o", "c"], ["o", "e"], ["p", "b"], ["p", "d"], ["p", "g"],
            ["p", "o"], ["q", "b"], ["q", "d"], ["q", "g"], ["q", "p"],
            ["r", "h"], ["t", "f"], ["u", "c"], ["u", "n"], ["v", "u"],
            ["w", "m"], ["w", "u"], ["w", "v"], ["x", "k"], ["y", "g"],
            ["y", "u"], ["y", "v"], ["z", "s"]]

# In[36]:

import string
import random

## Creating random generator for beginning replacement (first + second placement)
def id_generator_beginning(size = 5, pairs = pairs_10, chars = string.ascii_lowercase):
    result = []
    for pair in pairs:
        placement = random.randint(0, 1)
        if placement == 0:
            pre_generator = ''.join(random.choice(chars) for _ in range(size - 1))
            pair_list = []
            for letter in pair:
                pair_list.append(letter + pre_generator)
        if placement == 1:
            pre_generator = ''.join(random.choice(chars) for _ in range(size - 2))
            prefix = random.choice(chars)
            pair_list = []
            for letter in pair:
                pair_list.append(prefix + letter + pre_generator)
        result.append(pair_list)
    return result

## Note ##
# size = length of words
# pairs = choose list of pairs to be replaced
# num_pairs = number of pairs chosen from list to be replaced
df = id_generator_beginning(size = 9, pairs = pairs_100)

## Creating random generator for end replacement
def id_generator_end(size = 5, pairs = pairs_10, chars = string.ascii_lowercase):
    result = []
    for pair in pairs:
        placement = random.randint(0, 1)
        if placement  == 0:
            pre_generator = ''.join(random.choice(chars) for _ in range(size - 1))
            pair_list = []
            for letter in pair:
                pair_list.append(pre_generator + letter)
            result.append(pair_list)
        if placement == 1:
            pre_generator = ''.join(random.choice(chars) for _ in range(size - 2))
            pair_list = []
            postfix = random.choice(chars)
            for letter in pair:
                pair_list.append(pre_generator + letter + postfix)
            result.append(pair_list)
    return result

df = id_generator_end(size = 9, pairs = pairs_100)

## Creating random generator for middle replacement
def id_generator_middle(size = 5, pairs = pairs_10, chars = string.ascii_lowercase):
    result = []
    for pair in pairs:
        pre_generator = ''.join(random.choice(chars) for _ in range(size - 1))
        pair_list = []
        if size == 5:
            placement = 0
            for letter in pair:
              output = pre_generator[:(2+placement)] + letter + pre_generator[(2+placement):]
              pair_list.append(output)
        if size == 7:
            placement = random.randint(-1, 1)
            for letter in pair:
              output = pre_generator[:(3+placement)] + letter + pre_generator[(3+placement):]
              pair_list.append(output)
        if size == 9:
            placement = random.randint(-2, 2)
            for letter in pair:
              output = pre_generator[:(4+placement)] + letter + pre_generator[(4+placement):]
              pair_list.append(output)
        result.append(pair_list)
    return result

## Note ##
# size = length of words
# pairs = choose list of pairs to be replaced
# num_pairs = number of pairs chosen from list to be replaced
# placement = varying the level of middle; 0 = median
df = id_generator_middle(size = 9, pairs = pairs_100)

## Creating the same pair - for control group
def id_generator(size = 5, iteration = 20, chars = string.ascii_lowercase):
    result = []
    for n in range(1, iteration):
        pair = []
        pre_generator = ''.join(random.choice(chars) for _ in range(size))
        pair.append(pre_generator)
        pair.append(pre_generator)
        result.append(pair)
    return result

df = id_generator(size = 9, iteration = 200)


import logging
import functools
import os

from progressbar import (
    Bar,
    Percentage,
    ProgressBar,
)
from requests_toolbelt import (MultipartEncoder, MultipartEncoderMonitor)

logger = logging.getLogger(__name__)

def _update_progress_bar(progress_bar, maximum_value, monitor):
    if monitor.bytes_read <= maximum_value:
        progress_bar.update(monitor.bytes_read)

def upload_files(binary_filename, updown_client):
    """Upload a binary file to the Store.

    Submit a file to the Store upload service and return the
    corresponding upload_id.
    """
    result = {'success': False, 'errors': []}

    try:
        binary_file_size = os.path.getsize(binary_filename)
        binary_file = open(binary_filename, 'rb')
        encoder = MultipartEncoder(
            fields={
                'binary': ('filename', binary_file, 'application/octet-stream')
            }
        )

        # Create a progress bar that looks like: Uploading foo [==  ] 50%
        progress_bar = ProgressBar(
            widgets=['Uploading {} '.format(binary_filename),
                     Bar(marker='=', left='[', right=']'), ' ', Percentage()],
            maxval=os.path.getsize(binary_filename))
        progress_bar.start()
        # Print a newline so the progress bar has some breathing room.
        logger.info('')

        # Create a monitor for this upload, so that progress can be displayed
        monitor = MultipartEncoderMonitor(
            encoder, functools.partial(_update_progress_bar, progress_bar,
                                       binary_file_size))

        # Begin upload
        response = updown_client.upload(monitor)

        # Make sure progress bar shows 100% complete
        progress_bar.finish()

        if response.ok:
            response_data = response.json()
            result.update({
                'success': response_data.get('successful', True),
                'upload_id': response_data['upload_id'],
                'binary_filesize': os.path.getsize(binary_filename),
                'source_uploaded': False,
            })
        else:
            logger.error(
                'There was an error uploading the package.\n'
                'Reason: %s\n'
                'Text: %s',
                response.reason, response.text)
            result['errors'] = [response.text]
    except Exception as err:
        logger.exception(
            'An unexpected error was found while uploading files.')
        result['errors'] = [str(err)]
    finally:
        # Close the open file
        binary_file.close()

    return result


from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from tkinter.ttk import Progressbar
from tkinter import filedialog
from PIL import Image, ImageTk
import zad

def resizeForBlackBg(imageName):
    global pathV
    pathV = imageName
    resizedImage = Image.open(imageName)
    resizedImage = resizedImage.resize((450, 350))
    new_image= ImageTk.PhotoImage(resizedImage)
    return new_image

#tutaj wstawimy elegancko jakies funkcje co sie dzieja po kliknieciu
def clickedImageChoosing():
    global fileName
    global czarnyImage
    czarnyImage = "bgimages/czarne.png"
    fileName = filedialog.askopenfilename(filetypes = (("jpg","*.jpg"),("png","*.png"),("all files","*.*")))
    print(bool(fileName))
    if not fileName:
        fileName = czarnyImage
    fileName = resizeForBlackBg(fileName)
    wybraneZdjLabel.configure(image = fileName)
    wybraneZdjLabel.place(relx = 0.5, rely =0.3, anchor = CENTER)

def clickedSend():
    global inputPictureDefinition
    print(pathV)
    inputPictureDefinition = combo.get()
    resultString = zad.evaluate(pathV, inputPictureDefinition)
    textResultLabel.configure(text = "You specified selected image as: " + inputPictureDefinition + ". Our program calculated that it is: " + resultString ,styl = "TButton",  font=('Helvetica 13 bold'))

window = Tk()
window.attributes("-zoomed", True)
bgImage = PhotoImage(file = "bgimages/tlo2.png")
labelBg = Label(window, image=bgImage)
labelBg.place(x=0, y=0, relwidth = 1, relheight =1)
window.title("Analiza obrazow - projekt JS && BB")

#styling
style = Style()
style.configure("TButton", foreground="#FFFFFF", background="#0c2a56")
style.configure("TCombobox", fieldbackground= "#0c2a56", background= "white", foreground="#FFFFFF")

combo = Combobox(window)
combo['values']= ('sea', 'forest', 'glacier', 'street', '--choose category--')
combo.current(4) #set the selected item
combo.place(relx = 0.45, rely = 0.6, anchor = CENTER)

btnChooseImage = Button(window, text="Choose file", command=clickedImageChoosing, style="TButton")
btnChooseImage.place(relx = 0.55, rely = 0.6, anchor = CENTER)

czarneImage = "bgimages/czarne.png"
czarneImage = resizeForBlackBg(czarneImage)
wybraneZdjLabel = Label(window, image=czarneImage)
wybraneZdjLabel.place(relx = 0.5, rely = 0.3, anchor = CENTER)

btnCount = Button(window, text="Send to detect", command=clickedSend, style="TButton")
btnCount.place(relx = 0.5, rely = 0.7, anchor = CENTER)

textResultLabel = Label(window, text="")
textResultLabel.place(relx = 0.5, rely = 0.8, anchor = CENTER)

window.mainloop()


import random

def list (num):
    list_elements = []
    for i in range(num):
        list_elements.append (random.randint (i, num+1))
    print(f"Список {list_elements}")
    return list_elements;

def prod_list(x):
    new_list= []
    prod = 0
    if len(x)%2 == 1:
        for i in range(len(x)//2 + 1):
            if i == 0:
                prod = x[i] * x[-1]
            else:
                prod = x[i] * x[-i -1]
            new_list.append(prod)
    else:
        for i in range(len(x)//2 ):
            if i == 0:
                prod = x[i] * x[-1]
            else:
                prod = x[i] * x[-i -1]
            new_list.append(prod)
    return new_list

list_quantity = int(input("Длина списка = "))
new_list = list(list_quantity);
print(prod_list(new_list));


from dblur.testers.base_tester import BaseTester
from dblur.data.dataset import ImageDataset
from dblur.models.fnafnet import FNAFNet
from dblur.losses.fnafnet import FNAFNetLoss
import torch
import torch.nn as nn
import os
from torch.utils.data import DataLoader

class FNAFNetTester(BaseTester):
    """FNAFNet tester for image deblurring.

    FNAFNetTester is subclassed from BaseTester. The class contains methods to
    test a model used for deblurring, deblur multiple/single images given a
    pretrained model, get test dataloader, get model and get loss function."""

    def get_test_dataloader(self, dataset_path, transform=None, batch_size=16):
        """See base class."""

        test_dataset = ImageDataset(dataset_path, transform)
        test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True)

        return test_dataloader

    def get_model(self, projected_in_channels=32, enc_num=[1, 1, 1, 28], middle_num=1, dec_num=[1, 1, 1, 1],
                  attn_expansion_factor=2, ffn_expansion_factor=2, gate_reduction_factor=2, dropout_rate=0,
                  upscale_factor=2, attn_kernel_size=3, upscale_kernel_size=1, bias=True, upscale_bias=False,
                  fft_block_expansion_factor=2, fft_block_norm="backward", fft_block_activation=nn.ReLU(),
                  fft_block_bias=False, fft_block_a=4):
        """Returns an instance of the FNAFNet model based on the arguments below:

        Args:
            projected_in_channels: number of channels input is projected into by
                the first convolution layer.
            enc_num: list of number of NAFNet blocks in each encoder for a
                particular layer of the UNet.
            middle_num: number of NAFNet blocks in lowest layer of the UNet.
            dec_num: list of number of NAFNet blocks in each decoder for a
                particular layer of the UNet.
            attn_expansion_factor: expansion factor in the 1D Convolution in the
                attention block of each NAFNet Block.
            ffn_expansion_factor: expansion factor in the 1D Convolution in the
                Feed Forward Block of each NAFNet Block.
            gate_reduction_factor: reductor factor in the SimpleGate present in
                each Feed Forward Block of each NAFNet Block.
            dropout_rate: dropout rate in each NAFNet Block.
            upscale_factor: scaling factor across different layers in the UNet.
                E.g. With a scaling factor of 2, the image dimensions are halved
                as we go move downward across layers in the UNet.
            attn_kernel_size: kernel size of the convolutional layer in each
                attention block in each NAFNet Block.
            upscale_kernel_size: kernel size of the convolution layer in each
                UpSample and DownSample block.
            bias: if True, bias is added in every convolution layer in the model
                except for the convolutions present in the UpSample and DownSample
                blocks.
            upscale_bias: if True, bias is added in every convolution layer in the
                UpSample and Donwsample block.
            fft_block_expansion_factor: expansion factor of the 1D convolution
                present in each ResFFTBlock.
            fft_block_norm: norm of the inverse 2D Fourier Transform present in
                each ResFFTBlock.
            fft_block_activation: activation function present in each ResFFTBlock.
            fft_block_bias: if True, bias is added in the 1D convolution present
                in each ResFFTBlock.
            fft_block_a: the negative slope of the rectifier used after this layer
                for the initialization of weights using
                torch.nn.init.kaiming_uniform.
        """

        return FNAFNet(projected_in_channels=projected_in_channels, enc_num=enc_num, middle_num=middle_num,
                       dec_num=dec_num,
                       attn_expansion_factor=attn_expansion_factor, ffn_expansion_factor=ffn_expansion_factor,
                       gate_reduction_factor=gate_reduction_factor, dropout_rate=dropout_rate,
                       upscale_factor=upscale_factor,
                       attn_kernel_size=attn_kernel_size, upscale_kernel_size=upscale_kernel_size, bias=bias,
                       upscale_bias=upscale_bias,
                       fft_block_expansion_factor=fft_block_expansion_factor, fft_block_norm=fft_block_norm,
                       fft_block_activation=fft_block_activation, fft_block_bias=fft_block_bias,
                       fft_block_a=fft_block_a)

    def get_loss(self):
        """Returns FAFNet Loss used for training FNAFNet."""

        return FNAFNetLoss()


from django.urls import path, include
from django.conf.urls import url

from rest_framework.routers import DefaultRouter

from .views import *

router = DefaultRouter()
router.register('', ProductViewSet)
# router.register('', CreateComment)

urlpatterns = [
    path('categories/', CategoriesList.as_view()),
    path('', include(router.urls)),
    path('comments/create/', CreateComment.as_view()),
    path('comments/<int:pk>/', CommentViewSet.as_view({
        "get": "retrieve",
        "path": "partial_update",
        "put": "update",
        "delete": "destroy"}))
]