'''
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)


from typing import Optional, Callable, List

from constrained_decoding.dfa import DFA
from constrained_decoding.autoregressive_dfa_constraining.dfa_constrained_beam_search import dfa_constrained_beam_search
from constrained_decoding.autoregressive_dfa_constraining.dfa_constrained_generate import dfa_constrained_generate

def set_decoding_to_dfa_constrained(model,
                                    dfa: Optional[DFA] = None,
                                    dfa_factory: Optional[Callable[[List[int], ], DFA]] = None,
                                    dfas: Optional[List[DFA]] = None,
                                    dfa_factories: Optional[List[Callable[[List[int], ], DFA]]] = None,
                                    tokenizer=None):
    """ Set the beam search method of the model to be constrained to decoding according to a Deterministic Finite Automaton.
        Either `dfa` or `dfa_factory` must be specified.
    Args:
        model ([type]): A Huggingface model supporting text generation. The function will modify `model.beam_search`.
        dfa (Optional[DFA]): When specified, the same DFA is used for all batch instances and beams, regardless of input sequence. Defaults to None.
        dfa_factory (Optional[Callable[[List[int]], DFA]]): When specified, used for instanciating a `DFA` for each batch item.
            Assumed to be a functions which gets `input_ids` (token ids of input sequence) and returns a `DFA`. Defaults to None.
        tokenizer ([type], optional): The instanciated DFAs or provided `dfa` would be adjusted to this tokenizer.
            if `dfa` is provided and `dfa.tokenizer` is not None, `tokenizer` would not be used.

    """
    # Validate arguments
    if not (dfa or dfa_factory or dfas or dfa_factories):
        raise ValueError("Either `dfa`, `dfas`, `dfa_factory` or `dfa_factories` must be provided.")
    from transformers.generation_utils import GenerationMixin
    assert isinstance(model, GenerationMixin), "Model must be an instance of `transformers.generation_utils.GenerationMixin` to be applied the dfa-constrained `beam_search` method."

    # Replace model's beam_search method with our custom function as a bound method
    import types
    model.beam_search = types.MethodType(dfa_constrained_beam_search, model)
    # Provide our custom beam_search method with dfa or dfa_factory (as function-object attributes)
    if dfa or dfas:
        dfas = dfas or [dfa]
        for dfa in dfas:
            # make sure DFA is adjusted to tokenizer
            if dfa.tokenizer is None and tokenizer is not None:
                dfa = dfa.adjust_for_tokenizer(tokenizer, convert_to_word_ids=True)
            elif dfa.tokenizer is None and tokenizer is None:
                raise ValueError("Either `dfa` should be adjusted to model's tokenizer, or `tokenizer` should be provided for adjusting the `dfa` to it.")
        # provide the beam_search method with dfa
        dfa_constrained_beam_search.multiple_dfas = dfas
    elif dfa_factory or dfa_factories:
        dfa_factories = dfa_factories or [dfa_factory]
        dfa_constrained_beam_search.multiple_dfa_factories = dfa_factories
        dfa_constrained_beam_search.tokenizer = tokenizer
    # needs also to replace `model.generate` to our custom generate function that sends `encoder_input_ids` to model.beam_search
    model.generate = types.MethodType(dfa_constrained_generate, model)


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]))


from __future__ import print_function
import sys

from optparse import OptionParser

from androguard.cli import androdis_main

option_0 = {
    'name': ('-i', '--input'),
    'help': 'file : use this filename (DEX/ODEX)',
    'nargs': 1
}
option_1 = {
    'name': ('-o', '--offset'),
    'help': 'offset to disassemble',
    'nargs': 1
}
option_2 = {'name': ('-s', '--size'), 'help': 'size', 'nargs': 1}

options = [option_0, option_1, option_2]

def main(options, arguments):
    if options.input and options.offset and options.size:
        offset = int(options.offset, 0)
        size = int(options.size, 0)
        androdis_main(offset, size, options.input)

if __name__ == "__main__":
    parser = OptionParser()
    for option in options:
        param = option['name']
        del option['name']
        parser.add_option(*param, **option)

    options, arguments = parser.parse_args()
    sys.argv[:] = arguments
    main(options, arguments)


from dataclasses import dataclass, field
from typing import List
from .blacklist import Blacklist
from .blacklist_ref import BlacklistRef
from .containment_aggregation_structure import ContainmentAggregationStructure

__NAMESPACE__ = "http://www.netex.org.uk/netex"

@dataclass
class BlacklistsRelStructure(ContainmentAggregationStructure):
    class Meta:
        name = "blacklists_RelStructure"

    blacklist_ref_or_blacklist: List[object] = field(
        default_factory=list,
        metadata={
            "type": "Elements",
            "choices": (
                {
                    "name": "BlacklistRef",
                    "type": BlacklistRef,
                    "namespace": "http://www.netex.org.uk/netex",
                },
                {
                    "name": "Blacklist",
                    "type": Blacklist,
                    "namespace": "http://www.netex.org.uk/netex",
                },
            ),
        }
    )


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 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()


# 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)


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 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()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('flad', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='allele',
            name='locus',
            field=models.ForeignKey(null=True, to='flad.Locus'),
            preserve_default=True,
        ),
    ]


from flask import Flask, render_template, request
import mlab

mlab.connect()

app = Flask(__name__)

@app.route("/search", methods=['GET', 'POST'])
def home():
    if request.method == 'GET':
        return render_template("project.html")
    elif render_template == 'POST':
        form = request.form
        food_name = form['food_name']
        location = form['location']
        rate = form['rate']
        new_food = Food(food_name=food_name, location=location, rate=rate)
        new_food.save()
        return "Done"

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


from Positioning import positioning_MTP, homing_MTP
from Siemens_PLC import fire_signal, sensor1, sensor2, switch, IP, RACK, SLOT
from Snapshot import snapshot
import snap7

horizontal = 95
vertical = 0
sample_distance = 42
nikon_distance = 457

for i in range(10000):  # for test measurement runs, we chose to try 10000 subsequent runs.
    plc = snap7.client.Client()  # create client to communicate with PLC
    plc.connect(IP, RACK, SLOT)  # connect client to PLC
    homing_MTP()  # home vertical and horizontal Zaber stages
    positioning_MTP(vertical, horizontal)  # moving stages to 1st measurement position (1st sample)
    sensor1()  # check 1st measurement position with sensor switch
    fire_signal()  # fire data results from InProcess sample measurement
    positioning_MTP(vertical, horizontal + sample_distance)  # moving stages to 2nd measurement position (2nd sample in
    # in distance 42mm to  1st sample position)
    # sensor2() change switch to sensor2 as soon as 2nd sensor is wired up
    switch()  # for now, we used switch, because 2nd sensor wasn't build in
    fire_signal()  # fire data results from InProcess sample measurement
    positioning_MTP(vertical, nikon_distance)  # move stages to 1st photography position
    snapshot()  # 1st sample will be photographed
    positioning_MTP(vertical, nikon_distance + sample_distance)  # move stages to 2nd photography position
    snapshot()  # 2nd sample will be photographed
    plc.disconnect()  # disconnect the client from PLC
    plc.destroy()  # destroy the client communication to the PLC


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 unittest
from pathlib import Path

from gute.source import SourceNode
from gute.template import Template

class TemplateTest(unittest.TestCase):
    def test_bulk_constructor(self):
        nodes = ["
Hello
", "
World
"]
        templates = Template.from_nodes(nodes, None)
        self.assertEqual("
Hello
", templates[0].source_node)

    def test_target_filename(self):
        source_node = SourceNode(Path("./tests/data/post1.md"))
        template = Template(source_node, None)
        self.assertEqual("post1.html", template.target_filename())

    def test_hydrate_with_default_template(self):
        source_node = SourceNode(Path("./tests/data/post1.md"))
        template = Template(source_node, None)
        self.assertEqual(
            "

Hello, world
\n\n
This is really great content. Let's make it static.
\n
",
            template.hydrate(),
        )

    def test_hydrate_with_provided_template(self):
        source_node = SourceNode(Path("./tests/data/post1.md"))
        template_path = Path("./tests/data/template.html")
        template = Template(source_node, template_path)
        self.assertEqual(
            "\n<title>Great Website</title>\n\n
Hello, world
\n\n
This is really great content. Let's make it static.
\n\n\n",
            template.hydrate(),
        )