import pygame
import os

pygame.init()

screen_width = 1200
screen_height = 750
animation = 4

class Character(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        all_images = os.listdir(self.path)
        self.images = {image: pygame.transform.scale(pygame.image.load(self.path + image).convert_alpha(), (50, 50)) for image in all_images}
        self.image = self.images['Idle (1).png']
        self.rect = self.image.get_rect()
        self.mode_num = 1

    def move(self, surface, location):
        x, y = location
        self.rect.x = x
        self.rect.y = y

    def walk(self, velocity, frame):
        if frame == animation:
            if self.mode_num == self.max_walk:
                self.mode_num = 0
            self.mode_num += 1
        current_img = "Walk (" + str(self.mode_num) + ").png"

        if velocity < 0:
            self.image = pygame.transform.flip(self.images[current_img], True, False)
        else:
            self.image = self.images[current_img]

        if self.rect.x + velocity >=0 and self.rect.x + 50 + velocity <= screen_width:
            self.rect.x += velocity

class Girl(Character):

    def __init__(self):
        self.path = "png/Girl/"
        Character.__init__(self)
        self.rect.x = 0
        self.rect.y = 0

class Zombie(Character):

    def __init__(self):
        self.path = "png/Zombie/female/"
        Character.__init__(self)
        self.rect.x = 100
        self.rect.y = 100
        self.max_walk = 10
        self.jump_velocity = 15

    def jump(self, level_rects):
        mass = 3
        force = (int)(0.5 * mass) * self.jump_velocity^2
        self.rect.y -= force
        self.jump_velocity -= 1

        # if jump velocity is less than 0, we've reached the top of the jump, so
        # need to negate the mass so negative velocity doesn't affect movement
        if self.jump_velocity < 0:
            mass = -1
        # check to see if velocity has returned exceeded original upward velocity so acceleration doesn't continue
        if self.jump_velocity == -16:
            self.jump_velocity == -15

        # check for a collision with a platform
        collision = self.rect.collidelist(level_rects)
        if collision == -1 and self.rect.y < screen_height:
            if (self.rect.x + 54 <= screen_width):
                self.rect.x += 4
            return True  #still jumping
        if collision >= 0:
            mass = 3
            self.jump_velocity = 15
            self.rect.y = level_rects[collision][1] - 50 # subtracting the height of the image
            return False

class Level(object):
    coordinates = [[["Tile1.png", screen_width - 1200, screen_height - 50], ["Tile2.png", screen_width - 1150, screen_height - 50], ["Tile2.png", screen_width - 1100, screen_height - 50], ["Tile2.png", screen_width - 1050, screen_height - 50], ["Tile3.png", screen_width - 1000, screen_height - 50], \
        ["Tile14.png", screen_width - 900, screen_height - 150], ["Tile15.png", screen_width - 850, screen_height - 150], ["Tile15.png", screen_width - 800, screen_height - 150], ["Tile15.png", screen_width - 750, screen_height - 150], ["Tile16.png", screen_width - 700, screen_height - 150], \
            ["Tile14.png", screen_width - 700, screen_height - 250], ["Tile15.png", screen_width - 650, screen_height - 250], ["Tile15.png", screen_width - 600, screen_height - 250], ["Tile15.png", screen_width - 550, screen_height - 250], ["Tile15.png", screen_width - 500, screen_height - 250], ["Tile16.png", screen_width - 450, screen_height - 250], \
                ["Tile14.png", screen_width - 350, screen_height - 300], ["Tile15.png", screen_width - 300, screen_height - 300], ["Tile15.png", screen_width - 250, screen_height - 300], ["Tile15.png", screen_width - 200, screen_height - 300], ["Tile15.png", screen_width - 150, screen_height - 300], ["Tile15.png", screen_width - 100, screen_height - 300], ["Tile16.png", screen_width - 50, screen_height - 300] \
            ]]

    limits = {screen_height - 50: (screen_width - 1200, screen_width - 1000), \
        screen_height - 150: (screen_width - 900, screen_width - 700), \
            screen_height - 250: (screen_width - 700, screen_width - 450), \
                screen_height - 300: (screen_width - 350, screen_width - 50)}

    def __init__(self,id):
        self.id = id
        path = "png/Tiles/"
        all_images = os.listdir(path)
        self.img = {image: pygame.transform.scale(pygame.image.load(path + image).convert_alpha(), (50, 50)) for image in all_images}

    def build_level(self, surface):
        for tile in self.coordinates[self.id]:
            surface.blit(self.img[tile[0]], (tile[1], tile[2]))

    def get_pc_starting_points(self):
        player_character = (self.coordinates[self.id][0][1], self.coordinates[self.id][0][2] - 50)
        return player_character

    def get_npc_starting_points(self):
        npc = (self.coordinates[self.id][5][1] + 50, self.coordinates[self.id][5][2] - 50)
        return npc

    def platform_check(self, x, y):
        y += 50
        if y in self.limits:
            min, max = self.limits[y]
            if x >= min - 25 and x <= max + 25:
                return True
        return False

    def get_rects(self):
        level_rects = []
        for item in self.limits.items():
            x1, x2 = item[1]
            length = x2 - x1 + 50
            level_rects.append(pygame.Rect(x1, item[0], length, 50))
        return level_rects

def main():
    walking = 1
    velocity = 0
    game_clock= pygame.time.Clock()
    screen_size = (screen_width, screen_height)
    screen = pygame.display.set_mode(screen_size, 0, 32)
    background = pygame.image.load('png/BG.png').convert()
    is_jumping = False

    level = Level(0)
    zombie = Zombie()
    girl = Girl()
    char_list = pygame.sprite.Group()
    char_list.add(girl, zombie)

    glocation = level.get_npc_starting_points()
    zlocation = level.get_pc_starting_points()
    girl.move(screen, glocation)
    zombie.move(screen, zlocation)

    #pick up the platform rects
    level_rects = level.get_rects()

    while True:
        game_clock.tick(45)

        pressed_key = pygame.key.get_pressed()
        right_action = pressed_key[pygame.K_RIGHT] or pressed_key[pygame.K_d]
        left_action = pressed_key[pygame.K_LEFT] or pressed_key[pygame.K_a]
        jump_action = pressed_key[pygame.K_SPACE]

        if right_action:
            if not is_jumping:
                velocity = 2
                zombie.walk(velocity, walking)
                walking += 1

        if left_action:
            if not is_jumping:
                velocity = -2
                zombie.walk(velocity, walking)
                walking += 1

        if jump_action:
            is_jumping = True

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

        if not level.platform_check(zombie.rect.x, zombie.rect.y) and not is_jumping:
            zombie.rect.x += 25
            while zombie.rect.y < screen_height - 75:
                zombie.image = pygame.transform.rotate(zombie.image, velocity * -90)
                screen.blit(pygame.transform.scale(background, screen_size), (0, 0))
                level.build_level(screen)
                char_list.draw(screen)
                pygame.display.flip()
                zombie.rect.x += velocity
                zombie.rect.y += 5
                pygame.time.delay(250)
            pygame.quit()
        elif is_jumping:
            is_jumping = zombie.jump(level_rects)

        screen.blit(pygame.transform.scale(background, screen_size), (0, 0))
        level.build_level(screen)
        char_list.draw(screen)
        pygame.display.flip()
        if walking == animation + 1:
            walking = 1

if __name__ == "__main__":
    main()


# ------------单链表--------------
class Note:
    '''线性节点类'''
    def __init__(self,value=None):
        self.value = value
        self.next = None

class LinearLinked:
    '''线性链表'''
    def __init__(self,iter=None):
        '''
        将可迭代对象转成线性链表
        :param ite:可迭代对象
        '''
        self.header = q = Note()
        self.length = 0
        if not iter:
            return
        for value in iter:
            q.next = Note(value)
            self.length += 1
            q = q.next

    def insert(self,value,index=0):
        '''
        将数据插入指定位置
        :param value: 数据
        :param index: 位置
        '''
        if index>=self.length:
            raise IndexError('linear index out of range')
        note = Note(value)
        q = self.header
        for i in range(index):
            q = q.next
        note.next,q.next = q.next,note
        self.length += 1

    def delete(self,index=0):
        '''
        删除指定节点,默认删除
        :param index: 位置
        :return: 被删除节点的值
        '''
        if not self.header.next:
            raise ValueError('linear is empty')
        if index>=self.length:
            raise IndexError('linear index out of range')
        q = self.header
        for i in range(index):
            q = q.next
        q.next = q.next.next
        self.length -= 1

    def clear(self):
        '''
        重置为空表
        :return:
        '''
        self.header.next = None
        self.length = 0

    def getValue(self,index):
        '''
        获取指定节点的值
        :param index: int 索引
        :return: 值
        '''
        if index>=self.length:
            raise IndexError('linear index out of range')
        q = self.header
        for i in range(index):
            q = q.next
        return q.value

    def setValue(self,index,value):
        '''
        修改指定节点的值
        :param index: int 索引
        :param value: 新值
        '''
        if index>=self.length:
            raise IndexError('linear index out of range')
        q = self.header
        for i in range(index):
            q = q.next
        q.value = value

    def __iter__(self):
        return LinearLinkedIterator(self.header)

class LinearLinkedIterator:
    '''线性链表迭代器'''
    def __init__(self,note):
        self.note = note
    def __next__(self):
        if not self.note.next:
            raise StopIteration
        self.note = self.note.next
        return self.note.value
# ------------栈--------------
class Stack:
    def __init__(self,iter=None):
        '''
        初始化栈
        :param iter:可迭代对象 初始化数据
        '''
        self.header = Note()
        self.length = 0
        if not iter:
            return
        for i in iter:
            note = Note(i)
            note.next,self.header.next = self.header.next,note
            self.length += 1

    def is_empty(self):
        '''
        判断栈是否为空
        :return: 布尔值
        '''
        return self.header.next == None

    def peek(self):
        '''
        返回栈顶元素
        :return: 栈顶元素
        '''
        if self.is_empty():
            raise IndexError('栈为空')
        return self.header.next.value

    def size(self):
        '''
        返回栈的大小
        :return: 栈的大小
        '''
        return self.length

    # 把新的元素堆进栈里面（程序员喜欢把这个过程叫做压栈，入栈，进栈……）
    def push(self, val):
        '''
        入栈
        :param val: 元素
        :return: None
        '''
        if not val:
            raise ValueError('val的值为空')
        note = Note(val)
        self.header.next, note.next = note, self.header.next
        self.length += 1

    def pop(self):
        '''
        出栈
        :return: 栈顶元素
        '''
        if self.is_empty():
            raise IndexError('栈为空')
        res = self.header.next.value
        self.header.next = self.header.next.next
        self.length -= 1
        return res

def conversion(n:int, x:int)->str:
    '''
    十进制转其他进制
    :param n: 需要转换进制的十进制数
    :param x: 进制
    :return: 转换后的数
    '''
    s = Stack()
    res = ''
    while n>0:
        s.push(n%x)
        n //= x
    while not s.is_empty():
        res += str(s.pop())
    return res

def pareMacthing(string:str)->bool:
    '''
    验证字符串中的括号是否匹配
    :param s: 字符串
    :return: bool
    '''
    if not string:
        return True
    s = Stack()
    for i in string:
        if i in ['(','[','{']:
            s.push(i)
        if i == ')':
            if s.peek() == '(':
                s.pop()
            else:
                return False
        elif i == ']':
            if s.peek() == '[':
                s.pop()
            else:
                return False
        elif i == '}':
            if s.peek() == '{':
                s.pop()
            else:
                return False
    return True if s.is_empty() else False
# --------------队列-----------------
class Queue:
    def __init__(self,iter=None):
        '''
        初始化队列
        :param iter: 可迭代对象
        '''
        self.rear=self.header = Note()
        self.length = 0
        if not iter:
            return
        for i in iter:
            note = Note(i)
            self.rear.next = note
            self.rear = self.rear.next
            self.length += 1

    def put(self,value):
        '''
        入队
        :param value: 入队的数据
        :return: None
        '''
        self.rear.next = Note(value)
        self.rear = self.rear.next
        self.length += 1

    def pop(self):
        '''
        出队
        :return: 出队的数据
        '''
        if not self.length:
            raise ValueError('队列为空')
        res = self.header.next
        self.header.next = self.header.next.next
        return res

if __name__ == '__main__':
    from queue import deque
    dq = deque(['a','b'])
    print(dq)


#!/usr/bin/python3

#
# eevee.py
#
# Interface for the register controller of the eevee
#
# You can include this, and then write python that uses it
#
import os
import sys
import socket
import select
import random
import struct

# Struct incantations for
eevee_packet_format = "!I I I"
eevee_transaction_format = "!H H"
eevee_register_format = "!I I"

eevee_packet = struct.Struct(eevee_packet_format)
eevee_transaction = struct.Struct(eevee_transaction_format)
eevee_register = struct.Struct(eevee_register_format)

#
# This imports the registers, control directives, magic, and port from the header files
# into the python global namespace.
# You can then refer to these just as you would in C
#
headersLoaded = False

def loadHeaders():
    global headersLoaded

    # Search an environment variable for EEVEE_SRC_PATH
    mungypath = os.environ.get('EEVEE_SRC_PATH')
    if mungypath is None:
        mungypath = "./"

    path = os.path.abspath(mungypath)

    if not os.path.exists(path):
        print("Error: Could not find %s." % path)
        exit(2)

    # I don't feel like learning a language (pyparsing grammars) to parse one language (C preprocessor) into a different language (python)
    # So lets just do it manually
    evaluations = []

    # Load the register map
    try:
        registers = open(path + "/eevee_regmap.h")
    except Exception as e:
        print("Could not open eevee_regmap.h", e, file=sys.stderr)
        raise

    for n,line in enumerate(registers):
        words = line.strip().split()

        try:
            # Note that 0 given as parameter to int() turns on C-like base intuiting
            if words and words[0] == "#define" and str.isidentifier(words[1]):
                globals()[words[1]] = int(words[2], 0)
        except IndexError as e:
            # Silently skip bad lines
            pass
            # print("eevee_regmap.h:%d does not appear to be a simple assignment.  Skipping.\n \t%s" % (n, line), e, file=sys.stderr)

    registers.close()

    # Load the control map and protocol definition
    try:
        commands = open(path + "/eevee_control.h")
    except Exception as e:
        print("Could not open eevee_control.h", e, file=sys.stderr)
        raise

    for n,line in enumerate(commands):
        words = line.strip().split()

        try:
            if words and words[0] == "#define" and str.isidentifier(words[1]):
                globals()[words[1]] = int(words[2], 0)
        except Exception as e:
            print("eevee_control.h:%d does not appear to be a simple assignment.  Skipping. \n \t%s" % (n, line), e, file=sys.stderr)

    commands.close()

    headersLoaded = True

# Subclass Exception, because we are exceptional. Heh.
class EEVEEException(Exception):
    pass

# Discover the EEVEE boards on a subnet
def discover(broadcast, version="cafe0003", timeout=0.2):

    if not headersLoaded:
        loadHeaders()

    # Broadcast a null version string, so that everyone complains with their own
    # version string
    #
    # Note that SO_REUSEADDR is not needed
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    # Set a timeout, so we don't recvfrom() indefinitely
    s.settimeout(timeout)

    # Broadcast the request
    # Maximally transparent request
    #
    # We should technically use the ports and magic from the header files
    s.sendto(eevee_packet.pack(EEVEE_MAGIC_COOKIE, 0, ~0),
             (broadcast, int(EEVEE_SERVER_PORT)))

    # Handle responses
    print("Discovery sent.  Collecting responses...")
    responses = []
    try:
        while True:
            resp = s.recvfrom(11)
            what,where = resp
            print(where)
            responses.append(resp)
    except socket.timeout as e:
        print("Done.")

    print("Filtering for version %s and registering boards..." % version)
    boards = []
    for what,where in responses:
        bver = what[4:8]
        if not bver == bytes.fromhex(version):
            print("Dropping %s with version %s" % (where[0], bver))

        try:
            boards.append(board(where[0]))
        except EEVEEException as e:
            print("A board at %s with version %s exists, but subsequent communication seems broken?" % (where[0], bver), e, file=sys.stderr)

    print("Final board list:")
    for b in boards:
        print(b.dna)

    return boards

#
# A protocol v2 payload
#
# The user doesn't usually interact at this level, unless
# they are writing a new type of payload (i.e. not a register
# transaction)
#
class payload(object):

    ##
    ## Factory methods
    ##

    # The natural way to do register maps is with dictionaries.
    #
    # For example:
    #  { INTERNAL_OFFSET | x : 0x0 for x in ( REG_INTERNAL_VERSION, REG_INTERNAL_EFUSE, REG_INTERNAL_SCRATCH) }
    #
    #

    # Create a register payload
    def makeRegisterWrite(regDict=None, silent=False):
        tmp = payload(EEVEE_OP_MASK_REG & (EEVEE_WRITE | (EEVEE_OP_MASK_SILENT if silent else 0x0)))
        if not regDict is None:
            if not isinstance(regDict, dict):
                raise TypeError("The register pairs must be a dictionary...")
            else:
                registerPopulate(tmp, regDict)

        return tmp

    def makeRegisterRead(regDict=None, silent=False):
        tmp = payload(EEVEE_OP_MASK_REG & (EEVEE_READ | (EEVEE_OP_MASK_SILENT if silent else 0x0)))
        if not regDict is None:
            if not isinstance(regDict, list):
                raise TypeError("The list of register pairs must be a list...")
            else:
                registerPopulate(tmp, regDict)

        return tmp

    ##
    ## Static methods
    ##
    def registerPopulate(load, regdict):

        registerbytes = bytearray()

        # If the registers are not in pairs, then just fail out
        for key,value in regdict.items():
            # Perform the explicit cast
            registerbytes.extend(eevee_register.pack(key, value + (1<<32) if value < 0 else value))

        load.payload = registerbytes

    #
    # Return a dictionary based on a transaction payload, assuming it is
    # a register transaction
    #
    def bigBytesToReglist(pairsinbytes):
        tmp = {}

        for k in range(0, int(len(pairsinbytes) / (2*EEVEE_WIDTH_REGISTER))):
            offset = k*2*EEVEE_WIDTH_REGISTER
            addr, word = eevee_register.unpack(pairsinbytes[offset:offset+8])
            tmp[addr] = word

        return tmp

    ##
    ## Object methods
    ##
    def toggleSilent(self):
        self.op ^= EEVEE_OP_MASK_SILENT

    def toggleReadback(self):
        self.op ^= EEVEE_OP_MASK_NOREADBACK

    def __init__(self, op, payload=None):

        # Sanity check the parameters
        if not isinstance(op, int):
            raise TypeError("Operation must be a %d-byte wide integer" % EEVEE_WIDTH_OP)

        # Define the operation
        self.op = op

        # Make a new bytearray()
        self.payload = bytearray()

        if isinstance(payload, bytes) or isinstance(payload, bytearray):
            self.payload.extend(payload)

            if (op & EEVEE_OP_MASK_REG > 0) and not (op & EEVEE_OP_MASK_OTHER):
                # Its a register operation, sanity check the width
                if (len(self.payload) % EEVEE_WIDTH_REGISTER*2) > 0:
                    raise ValueError("Register operation payloads must come in integer numbers of addr:word pairs")
                elif not (op & EEVEE_OP_MASK_REG > 0) and (op & EEVEE_OP_MASK_OTHER):
                    # Its some other operation
                    pass
            else:
                # Its either a double specification, or its empty!
                raise EEVEEException("Invalid operator specifier")
        elif not payload is None:
            raise TypeError("Payloads, if given, must be type bytes or bytearray")

class board(object):

    def __init__(self, machine, port=None, udpsport=None, anonymous=False):

        # Try to load the headers
        if not headersLoaded:
            loadHeaders()

        # Set the machine
        self.dest = None

        # We now have a list of payloads that are supposed to be shipped
        self.transactions = list()

        # Try to resolve the name
        try:
            self.dest = socket.gethostbyname(machine)
        except Exception as e:
            print("TROUBLE: could not resolve %s" % machine, e)
            raise

        # Try to set up a socket
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            # If we want to use a persistent source port (e.g. for netcat tunnels)
            # do it here.
            if isinstance(udpsport, int):
                self.s.bind(('0.0.0.0', udpsport))

            if port is None:
                port = EEVEE_SERVER_PORT
            elif not isinstance(port, int):
                raise Exception("Given port is not an integer")

            self.s.connect((self.dest, port))
        except Exception as e:
            print("TROUBLE: could not grab a datagram socket", e)
            raise

        #pdb.set_trace()

        # Give a delay
        self.delay = 0.0

        # Retrieve the device DNA so we know what board we are looking at
        if not anonymous:
            self.dna = bytearray()
            self.dna.extend( (self.peeknow(INTERNAL_OFFSET | REG_INTERNAL_DNA_HIGH)).to_bytes(4, 'big'))
            self.dna.extend( (self.peeknow(INTERNAL_OFFSET | REG_INTERNAL_DNA_LOW)).to_bytes(4, 'big'))

    #
    # peek() push register reads into the pending transaction
    #
    def peek(self, arg1):

        # So there are two ways we can use this:
        #   peek( { reg1:arbitrary, reg2:arbitrary, ... } )   [ordered or unordered dictionary type]
        #   peek( reg )

        load = payload.makeRegisterRead()

        # Add the outgoing bytes
        if isinstance(arg1, dict):
            payload.registerPopulate(load, arg1)
        elif isinstance(arg1, int):
            payload.registerPopulate(load, { arg1 : 0x0 })
        else:
            raise EEVEEException("Could not interpret %s in any sensible way" % (arg1))

        # Append this action to the transactions
        # I gotta fix my nomenclature here...
        self.transactions.append(load)
    #
    # poke() push register writes into the pending transaction
    #
    def poke(self, arg1, arg2=None, silent=False, readback=True):

        # So there are two ways we can use this:
        #   poke( { reg1:word1, reg2:word2, ... } )   [ordered or unordered dictionary type]
        #   poke( reg, word )

        load = payload.makeRegisterWrite()

        # Did we request the silent treatment?
        if silent:
            load.toggleSilent()
        if not readback:
            load.toggleReadback()

        # Add the outgoing bytes
        if isinstance(arg1, dict) and arg2 is None:
            payload.registerPopulate(load, arg1)
        elif isinstance(arg1, int) and isinstance(arg2, int):
            payload.registerPopulate(load, { arg1 : arg2 })
        else:
            raise EEVEEException("Could not interpret %s and %s in any sensible way" % (arg1, arg2))

        self.transactions.append(load)

    #
    # pokenow() do a one off register write
    #
    def pokenow(self, addr, word, silent=False, readback=True):

        # pdb.set_trace()

        # Save the current transaction pile
        tmp = self.transactions

        # Make a new one
        self.transactions = []
        self.poke(addr, word, silent, readback)
        self.transact()

        # Restore the previous transaction pile
        result = self.transactions
        self.transactions = tmp

        # Return what came back
        if silent:
            return
        else:
            return result[0].payload[addr]

    #
    # peeknow() do a one off register read
    #
    def peeknow(self, addr):

        # Save the current transaction pile
        tmp = self.transactions

        # Make a new one
        self.transactions = []
        self.peek(addr)
        self.transact()

        # Restore the previous transaction pile
        result = self.transactions
        self.transactions = tmp

        # pdb.set_trace()

        # Return what came back
        return result[0].payload[addr]

    #
    # transact() tries to flush the request queue and return a tuple
    #
    def transact(self):

        # Are we associated to a card yet?
        if self.dest is None:
            error = EEVEEException("Not yet pointed to a target board")
            error.board = self
            raise error

        # Are there any pending transactions?
        if len(self.transactions) == 0:
            raise EEVEEException("There are no pending transactions.")

        # Note that we cannot use the "with" construct here, as it always garbage
        # collects theconnection, and we want a persistent one
        frame = bytearray()

        # Make the header
        random.seed()
        msgid = random.randrange(0, 1 << 8*EEVEE_WIDTH_SEQNUM)
        version = (EEVEE_VERSION_HARD << 16) | EEVEE_VERSION_SOFT
        frame.extend(eevee_packet.pack(EEVEE_MAGIC_COOKIE,
                                       version,
                                       msgid))

        # Data.  Load it all up
        response = 0

        for action in self.transactions:
            frame.extend(eevee_transaction.pack(action.op, len(action.payload)))
            frame.extend(action.payload)

            # Keep track if we expect a response...
            if (action.op & EEVEE_OP_MASK_SILENT) == 0:
                response += 1

        # If we exceed maximum length, clear the request and except
        if len(frame) > EEVEE_MAX_PAYLOAD:
            error = EEVEEException("Length (%d) of assembled outgoing EEVEE frame exceeds header-defined maximum (%d).  Discarded." % (len(frame), EEVEE_MAX_PAYLOAD))
            error.board = self
            raise error

        # First, we've not sent anything yet.
        # Make sure to pull off anything stale sitting in the UDP port buffer
        # This can occur if a previous command was timing out, but finally returned
        # right before *we* timed out.
        garbage = True
        while garbage:
            # See if we have an entire packet immediately on the buffer
            # (zero timeout is a poll in python, see the docs)
            ready = select.select([self.s], [], [], 0)
            if not ready[0]:
                garbage = False
            else:
                # Pop a packet off
                data, addr = self.s.recvfrom(1 << 16)

        # Port buffer should be empty now

        # Attempt to push this through
        attempts = 3
        while attempts > 0:

            # Transmit
            self.s.sendall(frame)

            # If we're not expecting any responses, don't wait for them
            # but still return an iterable type
            if response == 0:
                return list()

            # Otherwise wait for the response
            # This is UDP, so we are actually waiting for an entire
            # response datagram.  So once we can read, we read the maxiumum
            # IP datagram: 1 << 16, even though the eevee boards will never
            # send more than max ethernet frame.
            ready = select.select([self.s], [], [], self.delay + 0.2)

            if ready[0]:
                # We attempt to read magic, version, and message id
                data, addr = self.s.recvfrom(1 << 16)

                # Verify that addr came from what we expected...
                if not addr[0] == self.dest:
                    raise EEVEEException("Expected response from %s, but received response from %s" % (self.dest, addr))

                # Verify that the message has the correct magic
                cookie, echover, echoid = eevee_packet.unpack(data[0:12])

                # (note that we undo network byte ordering by just reading it backwards)
                if not cookie == EEVEE_MAGIC_COOKIE:
                    raise EEVEEException("Received magic %s that was not in eevee protocol" % cookie.hex())

                # Verify that the message has the correct version
                if not echover == version:
                    raise EEVEEException("Expecting version %s, received %s" % (version.hex(), echover.hex()))

                # If the message has the incorrect ID, but looks like valid everything else
                # it can't be stale stuff, since we cleared the OS buffer before
                # sending our request....
                if not echoid == msgid + 1:
                    raise EEVEEException("Received msgid %d, expecting msgid %d.  Corrupt?" % (echoid, msgid+1))

                # Leave the while loop
                break
            else:
                # Didn't get a response.  Try again.
                attempts -= 1
                print("Response timed out... Trying %d more times." % attempts, file=sys.stderr)
                continue

        # If we timed out, raise an exception
        if attempts == 0:
            raise EEVEEException("Responsed timed out repeatedly, giving up")

        # Throw away the header, so we can relative index
        data = data[12:]

        # We know the number of payloads to expect, since this is a response to
        # something we did.
        for n in range(0, len(self.transactions)):

            # If this payload was supposed to be silent, continue
            if self.transactions[n].op & EEVEE_OP_MASK_SILENT > 0:
                continue

            op, width = eevee_transaction.unpack(data[:4])

            # Verify message operation integrity
            if not self.transactions[n].op == op:
                raise EEVEEException("Received unexpected operation %s instead of %s" % (op.hex(), transaction[n].op.hex()))

            # Verify message width integrtiy
            if not len(self.transactions[n].payload) == width:
                raise EEVEEException("Received a payload width %d not in agreement with expectation %d" % (width, len(transaction[n].payload)))

            # Did this operation fail?  If so, append its index to the failures list
            if op & EEVEE_OP_MASK_FAILURE > 0:
                self.failures.append(n)

            # Index to the payload
            data = data[4:]

            # If its a register operation, process it as such
            if op & EEVEE_OP_MASK_REG > 0:

                # Make sure the width makes sense
                if width % (EEVEE_WIDTH_REGISTER*2) > 0:
                    raise EEVEEException("Width of register operation list %d did not divide correctly" % width)

                # Get the number of registers here
                nreg = int(width / (EEVEE_WIDTH_REGISTER*2))

                # Loop over the registers.
                # If it was a write, check the readback

                # Overwrite the transaction list with dictionaries, instead of bytes
                for reg in range(0, nreg):
                    self.transactions[n].payload = payload.bigBytesToReglist(data[:width])

                # Reindex
                data = data[width:]

            else:
                # Not yet implemented
                pass

        return self.transactions

    #
    # Clear pending transactions or the response
    #
    def clearTransactions(self):
        self.transactions = []

    #############################
    #
    # Useful userspace functions
    #
    #############################

    #
    # aimNBIC(): aim the NBIC
    #   Takes a (hostname, port) tuple (consistent with the other python socket stuff)
    #
    def aimNBIC(self, host=None, port=None):

        # See if we should act reflexively
        if host is None:
            ipaddr = self.s.getsockname()
            ipaddr = socket.inet_aton(ipaddr[0])
        else:
            ipaddr = socket.inet_aton(socket.gethostbyname(host))

        # Can't define this in the declaration because these
        # variables aren't in the namespace until loadHeaders() is called
        if port is None:
            port = EEVEE_NBIC_PORT

        #
        ## ENDIANNESS AHEAD
        #
        # To make it faster for hardware to build frames
        # we store these things in network order, so they can just be
        # repeatedly blasted, without twiddling.
        #
        # XXX wtf was that +1 doing there?
        nbicports = (socket.htons(port) << 16) | socket.htons(port)
        self.pokenow(NBIC_OFFSET | REG_NBIC_PORTS, nbicports)

        # Even though ipaddr is a bigendian byte string
        # It needs to be written to the register as a big endian byte string
        # So its network order is actually little endian.  endianness sucks.
        self.pokenow(NBIC_OFFSET | REG_NBIC_DESTIP, int.from_bytes(ipaddr, byteorder='little'))


N = int(input())
A = list(map(int, input().split()))

ans = 30
for i in range(30, -1, -1):
    flag = True
    for a in A:
        if a%(2**i) != 0:
            flag = False
            break
    if flag:
        ans = i
        break

print(ans)


#Josh Natis
#October 31st
#Assignment 42

import folium
import pandas as pd

filename = input("Enter CSV file name: ")
outName = input("Enter output name: ")
collisions = pd.read_csv(filename)

nycMap = folium.Map(location=[40.75, -74.125], zoom_start=10)

latList = collisions["LATITUDE"]
longList = collisions["LONGITUDE"]
locDict = dict(zip(latList,longList))

count = 0
for key in locDict:
    folium.Marker(location = [key, locDict[key]], popup = collisions["TIME"][count]).add_to(nycMap)
    count += 1

nycMap.save(outfile=outName)


import base64
import ConfigParser
import fcntl
import hashlib
import hmac
import os
import random
import sys

def clear_screen():
    sys.stdout.write('\033[2J\033[1;1H')
    sys.stdout.flush()

def read_prompt():
    sys.stdout.write('\033[35;1m')
    sys.stdout.write('> ')
    sys.stdout.flush()
    line = sys.stdin.readline()
    sys.stdout.write('\033[0m')
    if not line:
        sys.exit(1)
    if len(line) > 1024:
        sys.exit(1)
    return line.strip()

def hit_enter():
    sys.stdout.write('\033[35;1m')
    sys.stdout.write('\n[hit enter to continue]\n> ')
    sys.stdout.flush()
    sys.stdin.readline()
    sys.stdout.write('\033[0m')

def hashify(secret_key, message):
    return hmac.new(secret_key, message, hashlib.sha256).hexdigest()

def base32(x):
    x = base64.b32encode(x)
    num_pad = x.count('=')
    if num_pad == 0:
        return x
    extra = ''.join(random.choice(('0', '1')) for _i in xrange(num_pad))
    return x[:-num_pad] + extra

def unbase32(x):
    try:
        return base64.b32decode(x.replace('0', '=').replace('1', '='))
    except TypeError:
        raise ValueError('unbase32 error')

def read_secret(filename):
    p = ConfigParser.ConfigParser()
    p.read([filename])
    return p.get('secrets', 'secret_key').strip()

ramstein_config = """
[general]
required_deaths_per_day = 17
enable_firmware_upload = yes

[secrets]
; Must match with all other U.S. military institutions
; If you have to change it, change it on every institution
secret_key = {key}
""".lstrip()

creech_config = """
[general]
permit_kill_order = yes
take_responsibility = no

[secrets]
; Must match with all other U.S. military institutions
; If you have to change it, change it on every institution
secret_key = {key}
""".lstrip()

def generate_keys(config_dir):
    """Generate new cryptographic keys.

    Is executed on the first run of the service.
    """
    ramstein_ini = os.path.join(config_dir, 'ramstein.ini')
    creech_ini = os.path.join(config_dir, 'creech.ini')
    lock_file = os.path.join(config_dir, '.lock')
    if not os.path.exists(ramstein_ini) or not os.path.exists(creech_ini):
        with open(lock_file, 'w') as f_lock:
            try:
                fcntl.lockf(f_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except OSError:
                return
            try:
                key = base64.b32encode(os.urandom(15))
                with open(ramstein_ini, 'w') as f:
                    f.write(ramstein_config.format(key=key))
                with open(creech_ini, 'w') as f:
                    f.write(creech_config.format(key=key))
            finally:
                fcntl.lockf(f_lock.fileno(), fcntl.LOCK_UN)


from json import load
from snakemake import shell
from sys import exit

json_file	= snakemake.input[0]
sra_file	= snakemake.input[1]
cmd			= snakemake.params[0]
fastq_dir	= snakemake.params[1]
fastq_2 	= snakemake.output[1]

json 	= load(open(json_file))
layout	= json["LAYOUT"]

fastq_dump_str = " --split-e --outdir %s %s "

fastq_dump = cmd + fastq_dump_str %(fastq_dir, sra_file)
if layout == "SINGLE":
	dummy_com = " ; touch %s" %fastq_2
	fastq_dump += dummy_com
elif layout != "PAIRED":
	exit("fastq_dump: Layout type could not be interpreted; %s" %layout)

print(fastq_dump)
shell(fastq_dump)


import math
x = int(input())
a , f = math.modf(x / 11)
ans = f * 2
#print(f , a)
if a > 0.6:
    ans += 2
elif a > 0:
    ans += 1
print(int(ans))


# or nahshon agash
# ID- 311330500

import pandas as pd

# class represents a graph
class Graph:

    # initialize
    def __init__(self, path):
        self.data = pd.read_csv(path)
        self.graph = self.build_graph()
        self.size = len(self.graph)

    # build a graph
    def build_graph(self):
        graph = {}
        print("start build graph")
        for i in range(0, len(self.data)):
            if self.data.loc[i][0] == self.data.loc[i][1]:
                # location to itself
                distance = 0
            else:
                # location to neighbor
                distance = 1
            graph.setdefault(self.data.loc[i][0], {})[self.data.loc[i][1]] = distance
            # if the graph isnt directed so we need to add this line to add neigbhor for the other side
            #graph.setdefault(self.data.loc[i][1], {})[self.data.loc[i][0]] = distance

        print("finish build graph")
        return graph

    # get a neighbors.
    # if b - get distance from a to b
    def get(self, a, b=None):
        links = self.graph.setdefault(a, {})
        if b is None:
            return links
        else:
            return links.get(b)

# class represents a node
class Node:

    # initialize
    def __init__(self, name: str, parent):
        self.name = name
        self.parent = parent
        self.country = name.split(', ')[1]
        self.g = 0  # Distance from start node
        self.h = 0  # Distance to goal node
        self.f = 0  # Total cost

    # compare nodes
    def __eq__(self, other):
        return self.name == other.name

    # sort nodes by f
    def __lt__(self, other):
        return self.f > other.f

# there is path. now need to organized the path
def print_answer(ls, details):
    # all paths should be in same length
    lmax = 0
    sum = 0
    for key in ls.keys():
        lmax = max( lmax, len(ls[key]))
    for key in ls.keys():
        while len(ls[key]) < lmax:
            # add last location until length = lmax
            ls[key].append(ls[key][-1])
    df = pd.DataFrame(data=ls)
    # print heuristic value
    if details:
        print("the heuristic value after the first transformation is:", [df.loc[0][i] for i in range(len(ls.keys()))])
        for i in range(len(ls.keys())):
            sum += df.loc[0][i]
        print("In total:",sum)
        # remove auxiliary row
        df = df.drop(0)

    return df.values.tolist()

# find path
def find_path(starting_locations, goal_locations, search_method, detail_output):
    # create a graph based on data
    graph = Graph(path ="adjacency.csv")

    ans_final = {}

    # intertor to one selcted: start-goal
    for i in range(0, len(starting_locations)):
        start = starting_locations[i]
        goal = goal_locations[i]

        switcher = {
            1: A_star_search(graph, start, goal, detail_output),
            2: None,
            3: None}

        # run selected algorithm
        ans = switcher.get(search_method)

        if ans == False:
            # there isnt path
            return print("No path found")
        else:
            # there is path
            ans_final[i]= ans

    return print(starting_locations,*print_answer(ans_final, detail_output), sep="\n")

# A* search
def A_star_search(graph, start, end, detail_output ):

    open, closed = [], []

    # Create a start node and an goal node
    start_node = Node(start, None)
    goal_node = Node(end, None)
    # find heuristics values to goal
    heuristic = bfs(goal_node.country)

    # Add the start node to open list
    open.append(start_node)

    #loop until opn list is empty
    while len(open) > 0:
        # sort to get the node with the lowest cost first
        open.sort()
        current_node = open.pop()
        # add current node to closed list
        closed.append(current_node)

        # if we have reached the goal, recreate path
        if current_node == goal_node:
            return recreate_path(current_node, start_node, detail_output)

        neighbors = graph.get(current_node.name)
        for key, value in neighbors.items():
            neighbor = Node(key, current_node)

            # if we check the neighbor, pass
            if neighbor in closed:
                continue
            # calculate full path cost
            neighbor.g = current_node.g + value
            neighbor.h = heuristic.get(neighbor.country)
            try:
                neighbor.f = neighbor.g + neighbor.h
            except:
                # if there is not heuristic value
                neighbor.f = neighbor.g + 100000

            # Check if neighbor is in open list and if it has a lower value
            open = add_to_open(open, neighbor)

    return False

# follow nodes and recreate path
def recreate_path(current_node, start_node, detail_output):

    path = []
    # loop until reach to start-node
    while current_node != start_node:
        path.append(current_node.name)
        details_h = current_node.h
        current_node = current_node.parent
    if detail_output:
        path.append(details_h)
    # reverse path
    return path[::-1]

# Check if neighbor is in open list and if it has a lower value
def add_to_open(open, neighbor):

    for node in open:
        if neighbor == node:
            if neighbor.g < node.g:
                # replace node
                open.remove(node)
                open.append(neighbor)
            return open

    # neighbor is not in open list
    open.append(neighbor)

    return open

# Neighborhood relations between countries
def Neighbors():
    return {      'OH': ['WV', 'IN', 'MI', 'PA', 'KY'],
                  'OK': ['NM', 'CO', 'KS', 'TX', 'AR', 'MO'],
                  'OR': ['WA', 'ID', 'CA', 'NV'],
                  'IA': ['SD', 'NE', 'MO', 'IL', 'WI', 'MN'],
                  'ID': ['WA', 'OR', 'NV', 'UT', 'MT', 'WY'],
                  'IL': ['KY', 'IN', 'MO', 'IA', 'WI'],
                  'IN': ['OH', 'MI', 'KY', 'IL'],
                  'AL': ['FL', 'GA', 'TN', 'MS'],
                  'AK': [],
                  'AZ': ['CA', 'NM', 'NV', 'UT', 'CO'],
                  'AR': ['OK', 'TX', 'LA', 'MS', 'TN', 'MO'],
                  'GA': ['NC', 'SC', 'FL', 'AL', 'TN'],
                  'DE': ['PA', 'MD', 'NJ'],
                  'SD': ['WY', 'MT', 'ND', 'MS', 'LA', 'NE'],
                  'ND': ['MT', 'SD', 'MS'],
                  'HI': [],
                  'WY': ['UT', 'CO', 'ID', 'NE', 'SD', 'MT'],
                  'WA': ['OR', 'ID'],
                  'WI': ['IL', 'IA', 'MN', 'MI'],
                  'VA': ['MD', 'WV', 'KY', 'NC', 'TN','DC'],
                  'WV': ['OH', 'PA', 'MD', 'VA', 'KY'],
                  'VT': ['NH', 'NY', 'MA'],
                  'TN': ['VA', 'NC', 'GA', 'AL', 'MS', 'AR', 'KY', 'MO'],
                  'TX': ['NM', 'OK', 'AR', 'LA'],
                  'UT': ['AZ', 'NV', 'CO', 'ID', 'WY', 'NM'],
                  'LA': ['TX', 'AR', 'MA'],
                  'MT': ['ID', 'WY', 'SD', 'ND'],
                  'MO': ['NE', 'KS', 'OK', 'TN', 'KY', 'AR', 'IL', 'IA'],
                  'ME': ['NH'],
                  'MN': ['ND', 'SD', 'IA', 'WI'],
                  'MS': ['LA', 'AL', 'TN', 'AR'],
                  'MI': ['OH', 'IN', 'WI'],
                  'MA': ['NH', 'VA', 'CT', 'NY', 'RI'],
                  'MD': ['PA', 'DE', 'VA', 'WV', 'DC'],
                  'NV': ['OR', 'CA', 'AZ', 'ID', 'UT'],
                  'NE': ['WY', 'SD', 'KS', 'MO', 'CO', 'IA'],
                  'NJ': ['NY', 'PA', 'DE'],
                  'NH': ['ME', 'VT', 'MA'],
                  'NY': ['VT', 'MA', 'CT', 'NJ', 'PA'],
                  'NM': ['AZ', 'CO', 'TX', 'OK', 'UT'],
                  'FL': ['GA', 'AL'],
                  'PA': ['OH', 'NY', 'WV', 'MD', 'DE', 'NJ'],
                  'CO': ['NM', 'UT', 'WY', 'KS', 'OK', 'NE', 'AZ'],
                  'CT': ['MA', 'NY', 'RI'],
                  'CA': ['OR', 'AZ', 'NV'],
                  'KS': ['CO', 'NE', 'MO', 'OK'],
                  'KY': ['OH', 'WV', 'VA', 'TN', 'IN', 'IL', 'MO'],
                  'SC': ['NC', 'GA'],
                  'NC': ['VA', 'TN', 'SC', 'GA'],
                  'RI': ['MA', 'CT'],
                  'VI': [],
                  'PR': [],
                  'MP': [],
                  'GU': [],
                  'AS': [],
                  'DC': ['MD', 'VA']   }

# bfs-search to find heuristics value
def bfs (root, graph_search=Neighbors()):

    ans, visited, queue, queue2 = {}, set(), [root], []
    visited.add(root)
    i = 0

    # i used two queues to know when layer ending and new layer begining
    while queue or queue2:
        while queue:
            var = queue.pop(0)
            ans[var] = i

            for neighbour in graph_search[var]:
                if neighbour not in visited:
                    visited.add(neighbour)
                    queue2.append(neighbour)
        i += 1
        while queue2:
            var = queue2.pop(0)
            ans[var] = i

            for neighbour in graph_search[var]:
                if neighbour not in visited:
                    visited.add(neighbour)
                    queue.append(neighbour)

        i += 1

    return ans

if __name__ == "__main__":

    starting_locations = ["Chicot County, AR", "Chittenden County, VT", "Rensselaer County, NY"]
    goal_locations = ["Grant County, AR", "Rensselaer County, NY", "Grant County, AR"]

    search_method = 1
    detail_output = True

    find_path(starting_locations, goal_locations, search_method, detail_output)


"""
Helpers for evaluating models.
"""

from .reptile import ReptileForFederatedData
from mlmi.reptile.reptile_original.variables import weight_decay

# pylint: disable=R0913,R0914
def evaluate(sess,
             model,
             train_dataloaders,
             test_dataloaders,
             num_classes=5,
             eval_inner_iters=50,
             transductive=False,
             weight_decay_rate=1,
             reptile_fn=ReptileForFederatedData):
    """
    Evaluate a model on a dataset.
    """
    reptile = reptile_fn(
        session=sess,
        transductive=transductive,
        pre_step_op=weight_decay(weight_decay_rate)
    )
    total_correct = 0
    for train_dl, test_dl in zip(
            train_dataloaders.values(), test_dataloaders.values()
    ):
        total_correct += reptile.evaluate(
            train_data_loader=train_dl,
            test_data_loader=test_dl,
            input_ph=model.input_ph,
            label_ph=model.label_ph,
            minimize_op=model.minimize_op,
            predictions=model.predictions,
            inner_iters=eval_inner_iters
        )
    return total_correct / (len(train_dataloaders) * num_classes)


from .container_utilities_py3 import Start_Container
from .container_utilities_py3 import End_Container

class PLC_IO_CONTAINER(object):

     def __init__(self,bc,cd,name):
          command_list = [  { "file":"plc_io_cntrl_py3.py","restart":True } ]
          starting_command = "docker run -d  --network host   --name plc_io   --mount type=bind,source=/mnt/ssd/site_config,target=/data/ nanodatacenter/plc_io  /bin/bash ./process_control.bsh"
          Start_Container(bc,cd,name,starting_command,command_list,"nanodatacenter/plc_io")
          End_Container(bc,cd)


# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

# Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com)

from odoo import api, fields, models

class HolidaysRequest(models.Model):
    _inherit = "hr.leave"

    @api.multi
    def _create_resource_leave(self):
        """ This method will create entry in resource calendar leave object at the time of holidays validated """
        contract = self.env['hr.contract']
        for leave in self:
            date_from = fields.Datetime.from_string(leave.date_from)
            date_to = fields.Datetime.from_string(leave.date_to)

            contract_id = contract.search([('employee_id', '=', leave.employee_id.id), ('state', '=', 'open')], limit=1)

            vals = {
                    'name': leave.name,
                    'date_from': fields.Datetime.to_string(date_from),
                    'holiday_id': leave.id,
                    'date_to': fields.Datetime.to_string(date_to),
                    'resource_id': leave.employee_id.resource_id.id,
                    'time_type': leave.holiday_status_id.time_type,
                }
            if contract_id:
                vals.update({'calendar_id': contract_id.resource_calendar_id.id,})
            else:
                vals.update({'calendar_id': leave.employee_id.resource_calendar_id.id,})

            self.env['resource.calendar.leaves'].create(vals)
        return True


# -*- coding: utf-8 -*-
"""
    :author: Wang Zelin (王泽霖)
    :url:
    :copyright: © 2018 Wang Zelin <1064534588@qq.com>
    :license: MIT, see LICENSE for more details.
"""
# 请设计一个函数，用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始，每一步可以在矩阵中向左、右、上、下移动一格。
# 如果一条路径经过了矩阵的某一格，那么该路径不能再次进入该格子。例如，在下面的3×4的矩阵中包含一条字符串“bfce”的路径（路径中的字母用加粗标出）。

# [["a","b","c","e"],
#  ["s","f","c","s"],
#  ["a","d","e","e"]]
# 但矩阵中不包含字符串“abfb”的路径，因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后，路径不能再次进入这个格子。
#
# 示例 1：
# 输入：board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
# 输出：true
#
# 示例 2：
# 输入：board = [["a","b"],["c","d"]], word = "abcd"
# 输出：false

# DFS 解析：
# 递归参数： 当前元素在矩阵 board 中的行列索引 i 和 j ，当前目标字符在 word 中的索引 k 。
# 终止条件：
# 返回 false ： (1) 行或列索引越界 或 (2) 当前矩阵元素与目标字符不同 或 (3) 当前矩阵元素已访问过 （ (3) 可合并至 (2) ） 。
# 返回 true ： k = len(word) - 1 ，即字符串 word 已全部匹配。
# 递推工作：
# 标记当前矩阵元素： 将 board[i][j] 修改为 空字符 '' ，代表此元素已访问过，防止之后搜索时重复访问。
# 搜索下一单元格： 朝当前元素的 上、下、左、右 四个方向开启下层递归，使用 或 连接 （代表只需找到一条可行路径就直接返回，不再做后续 DFS ），并记录结果至 res 。
# 还原当前矩阵元素： 将 board[i][j] 元素还原至初始值，即 word[k] 。
# 返回值： 返回布尔量 res ，代表是否搜索到目标字符串。
# 时间复杂度 O(3^K MN)： 最差情况下，需要遍历矩阵中长度为 KK 字符串的所有方案，时间复杂度为 O(3^K)；矩阵中共有 M*N 个起点，时间复杂度为 O(MN)。
# 方案数计算： 设字符串长度为 K ，搜索中每个字符有上、下、左、右四个方向可以选择，舍弃回头（上个字符）的方向，剩下 3 种选择，因此方案数的复杂度为 O(3^K)。
# 空间复杂度 O(K)： 搜索过程中的递归深度不超过 K ，因此系统因函数调用累计使用的栈空间占用 O(K) (因为函数返回后，系统调用的栈空间会释放）。
# 最坏情况下 K = MN，递归深度为 MN ，此时系统栈使用 O(MN)的额外空间。
# https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/
class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        def dfs(i,j,k):
            if not 0<=i<len(board) or not 0<=j<len(board[0]) or board[i][j]!=word[k]: return False
            if k == len(word)-1: return True
            board[i][j] = ''
            res = dfs(i+1,j,k+1) or dfs(i-1,j,k+1) or dfs(i,j+1,k+1) or dfs(i,j-1,k+1)
            board[i][j] = word[k]
            return res

        for i in range(board):
            for j in range(board[0]):
                if dfs(i,j,0): return True
        return False


#coding: utf-8
from astropy.io import fits
import json
from datetime import datetime
import os

def prendi_json(path):
	dati=json.load(open(path,"r"))
	return dati

def salva_json(dati,path):
	with open(path,"w") as outfile:
		json.dump(dati,outfile,indent=8)
	return

def calcola_luminosita_stella(dati,colonna,riga,raggio):#riga e colonna del centro della stella

	dati_tot={"tempo_tot":[],"luminosita_tot":[]}

	riga_partenza=riga-raggio
	colonna_partenza=colonna-raggio

	riga_arrivo=riga+raggio
	colonna_arrivo=colonna+raggio

	if (riga_partenza<0 or riga_arrivo>128 or colonna_partenza<0 or colonna_arrivo>128):
		dati_tot["tempo_tot"].append(0)
		dati_tot["luminosita_tot"].append(0)
		return dati_tot#se le coordinate vanno fuori dalla matrice di dati, ritornerà un valore di 0 che non verrà visualizzato nel grafico

	luminosita=0

	tempo=0

	for k in range(1000):#for per ogni foglio di dati
		for i in range(raggio*2+1):#for per le righe
			for j in range(raggio*2+1):#for per le colonne

				luminosita+=dati[k][riga_partenza+i][colonna_partenza+j]#somma tutte le luminosità

		dati_tot["luminosita_tot"].append(luminosita)#salva la luminosità totale di 1 foglio in un array
		dati_tot["tempo_tot"].append(tempo)
		tempo+=50
		luminosita=0#si azzera per ricominciare un nuovo foglio

	return dati_tot

indirizzo='level_1.fits'
hdu=fits.open(indirizzo)
data=hdu[0].data
stelle_tot={}

video=str(input("Nome Video -> "))
os.system("vlc Video/" + video + ".mpg &")
os.system("vlc Video/" + video + "diff.mpg &")

for i in range(int(input("Quante stelle? "))):
	stelle_tot["stella_"+str(i+1)]=calcola_luminosita_stella(data,int(input("X stella ")),int(input("Y stella ")),int(input("raggio ")))
	print("Fatto!\nProssima stella\n")

contatore=prendi_json("Contatore/Contatore.json")

salva_json(stelle_tot,"Dati/File"+str(contatore["contatore"])+".json")

contatore["contatore"]+=1
contatore["da_solo"]="True"

salva_json(contatore,"Contatore/Contatore.json")

os.system("python Grafico.py &")


#!/bin/python

from random import getrandbits as grb
from time import sleep
import os
from sys import argv

rep = ['  ','░░','▒▒','▓▓','██']
hist = len(rep)-1
rows, columns = os.popen('stty size', 'r').read().split()
gw,gh = int(int(columns)/2)-1, int(rows) -1
adj = [(-1,-1),(-1,0),(0,-1),(0,1),(1,0),(1,1),(-1,1),(1,-1)]
grid = [[grb(1)*hist for i in range(gw)] for j in range(gh)]
adjm = [[0 for i in range(gw)] for j in range(gh)]

try:
    gw,gh = [int(n) for n in argv[1:3]]
except:
    pass

while True:
    gs = ''
    for y in range(gh):
        for x in range(gw):
            gs += rep[grid[y][x]]
            if grid[y][x] > 0 and grid[y][x] < hist:
                grid[y][x] -= 1
            if grid[y][x] == hist:
                for dy,dx in adj:
                    adjm[(y+dy)%gh][(x+dx)%gw] += 1
        gs += '\n'
    print(gs,end='')

    for y in range(gh):
        for x in range(gw):
            if adjm[y][x] == 3:
                grid[y][x] = hist
            elif adjm[y][x] in [0,1,4,5,6,7,8] and grid[y][x] == hist:
                grid[y][x] = hist-1
            adjm[y][x] = 0
    sleep(0.2)


import responses

from selvpcclient.resources.tokens import TokensManager
from tests.rest import client
from tests.util import answers

@responses.activate
def test_add():
    responses.add(responses.POST, 'http://api/v2/tokens',
                  json=answers.TOKENS_CREATE)

    manager = TokensManager(client)

    token = manager.create(project_id=322)

    assert token is not None

@responses.activate
def test_add_raw():
    responses.add(responses.POST, 'http://api/v2/tokens',
                  json=answers.TOKENS_CREATE)

    manager = TokensManager(client)

    token = manager.create(project_id=322, return_raw=True)

    assert token == answers.TOKENS_CREATE["token"]

@responses.activate
def test_remove():
    responses.add(responses.DELETE, 'http://api/v2/tokens/666', status=204)

    manager = TokensManager(client)

    result = manager.delete(token_id=666)

    assert result is None


import struct

class hclBoneSpaceDeformerThreeBlendEntryBlock(object):
    vertexIndices: int
    boneIndices: int
    padding: int

    def __init__(self, infile):
        self.vertexIndices = struct.unpack('>H', infile.read(2))  # TYPE_UINT16:TYPE_VOID
        self.boneIndices = struct.unpack('>H', infile.read(2))  # TYPE_UINT16:TYPE_VOID
        self.padding = struct.unpack('>B', infile.read(1))  # TYPE_UINT8:TYPE_VOID

    def __repr__(self):
        return "<{class_name} vertexIndices={vertexIndices}, boneIndices={boneIndices}, padding={padding}>".format(**{
            "class_name": self.__class__.__name__,
            "vertexIndices": self.vertexIndices,
            "boneIndices": self.boneIndices,
            "padding": self.padding,
        })


' comment '

__author__ = 'lizhipei'

from typing import List
import math

# 冒泡排序
def get_short_nums(nums: List[int]) -> List[int]:
    num_len = len(nums)
    for index in range(num_len - 1):
        for mov in range(index, num_len):
            if nums[mov] < nums[index]:
                tmp = nums[mov]
                nums[mov] = nums[index]
                nums[index] = tmp
    return nums

# 归并排序
def merge_sort(nums: List[int]) -> List[int]:
    if len(nums) < 2:
        return nums
    middle = math.floor(len(nums) / 2)
    left = nums[0:middle]
    right = nums[middle:]
    return merge(merge_sort(left), merge_sort(right))

# 合并数组
def merge(left: List[int], right: List[int]) -> List[int]:
    result = []
    while left and right:
        if left[0] < right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    while left:
        result.append(left.pop(0))
    while right:
        result.append(right.pop(0))
    return result

# 快速排序
def fast_sort(nums: List[int], start: int, end: int) -> List[int]:
    if start >= end:
        return
    left = start
    right = end
    anchor = nums[start]
    while left < right:
        while left < right and nums[right] >= anchor:
            right -= 1
        while left < right and nums[left] <= anchor:
            left += 1
        swap(nums, left, right)
    nums[start] = nums[left]
    nums[left] = anchor
    fast_sort(nums, start, right - 1)
    fast_sort(nums, right + 1, end)
    return nums

# 交换元素
def swap(nums: List[int], i: int, j: int):
    nums[i], nums[j] = nums[j], nums[i]


from selenium import webdriver
import requests
from browsermobproxy import Server
import re
import textract

# from mitmproxy import ctx
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

# server = Server(r'd:\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat')
# server.start()
# proxy = server.create_proxy()

# chrome_options = Options()
# chrome_options.add_argument('--proxy-server={0}'.format(proxy.proxy))
# driver = webdriver.Chrome(ChromeDriverManager().install())
root_url = "http://ien.shou.edu.cn"
base_url = "http://ien.shou.edu.cn/2219/list.htm"
soup = {}

def init ():
    global soup
    r = requests.get(base_url)
    r.encoding = 'UTF-8'
    soup = BeautifulSoup(r.text, 'lxml')
    getlist()

def gotonextpage ():
    global soup
    link = soup.find_all('a', 'next', limit=1)[0].get("href")
    if(re.search('htm', link) == None):
        return
    nextpagelink = root_url + link
    r = requests.get(nextpagelink)
    soup = BeautifulSoup(r.text, 'lxml')
    getlist()

def getlistdetail (link):
    r = requests.get(link)
    r.encoding = 'UTF-8'
    soup = BeautifulSoup(r.text, 'lxml')
    pubdate = soup('span', 'Article_PublishDate')[0].get_text()
    viewcount = soup('span', 'WP_VisitCount')[0].get_text()
    title = soup('span', 'Article_Title')[0].get_text()
    content = soup('div', 'Article_Content', limit=1)[0]
    attach_file = soup.find_all(href=re.compile("_upload/article"))
    img = soup.find_all(src=re.compile("_upload/article"))
    gotonextpage()

def getlist ():
    global soup
    items = soup.find_all('a',href = re.compile("page"), limit=14)
    for n in items:
        title = n.get_text()
        herf = n.get("href")
        data = {
            '标题':title,
            '链接':herf
        }
        link = root_url + herf
        getlistdetail(link)
init()
# text = textract.process("C:/Users/zhongbiao/Downloads/1.doc")
# text = text.decode("utf-8")
# print(text)

# server.stop()
# driver.quit()


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

def numero():
    for i in range(11, 0, -1):
        print('Número: %d' % i)
        divisores(i)

def divisores(valor):
    numero = valor
    for item in range(1,11):
        if numero % item == 0:
            print('Dividores: %d' % item)

if __name__ == '__main__':
    numero()


from flask import *
from flask import request
# Generalised Imports
import os
import json
import datetime
import threading
import time

class BusTracker(object):
    def __init__(self, interval=30):
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()
    def run(self):
        while True:
            for a in customBus:
                with open(os.getcwd() + "/trackBus/" + a["vehicle"] + ".json", "w") as f:
                    b = RequestBusPosition( a["vehicle"][2] )
                    jsonTime = json.load(f)
                    jsonData = {}
                    jsonData["T"] = a
                    if b:
                        jsonData["N"] = b

                    jsonTime[datetime.datetime.now()] = jsonData

                    f.write(json.dumps(jsonTime))
            time.sleep(self.interval)

# Our custom Module imports
import readingbusesapi as bus_Wrapper
import busupdater as busUpdater
import cords

busWrapper = bus_Wrapper.ReadingBusesAPI("OHYrhd9WoJ")

readingDepot = {
    "longitude": -0.981368,
    "latitude":  51.459180,
}
customBus = {}

# We create the BusUpdate class which we will run on another thread so
#that it does not interacts with the flask server

example = busUpdater.BusUpdater()
busTracker = BusTracker()

app = Flask(__name__)

@app.route("/init", methods=["GET"])
def init():
    dict  = bus_Wrapper.GetBusJson()
    response = jsonify(dict)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
@app.route("/track/<vehicleID>", methods=["GET"])
def track(vehicleID):
    dict = busWrapper.RequestBusPosition(vehicleID)
    response = jsonify(dict)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

@app.route("/")
def serve_index():
    return redirect("/static/index.html")

@app.route("/<html_file>", methods=["GET"])
def serve_html(html_file):
    return render_template(html_file)

@app.route("/<css_file>")
def serve_css(css_file):
    return render_template(css_file)

@app.route("/<image>")
def serve_image(image):
    return send_from_directory(image)

@app.route("/<js_file>")
def serve_javascript(js_file):
    return send_from_directory(js_file)

@app.route("/favicon.ico")
def return_favicon():
  return send_from_directory(os.path.join(app.root_path, "static"), "favicon.ico", mimetype='image/vnd.microsoft.com')

@app.route("/getAllBus")
def getAllBus():
    Dict = []
    for files in os.listdir( os.getcwd() + "/buses"):
        if files.endswith(".json"):
            jsonFile = open(os.getcwd() + "/buses/" + files)
            jsonData = json.load(jsonFile)
            Dict.Append(jsonData["vehicle"])
    with open() as f:
        for a in Dict:
            f.write(a + ",\n")

@app.route('/addBus', methods=["POST"])
def addBus():
    form = request.get_json()
    dict = {}
    dict["service"] = form["service"]
    dict["vehicle"] = form["vehicle"]
    dict["isRunning"] = form["isRunning"]
    dict["latitude"] = form["latitude"]
    dict["longitude"] = form["longitude"]
    dict["bearing"] = form["bearing"]
    dict["customBus"] = "1"
    x = datetime.datetime.now()
    dict["observed"] = str(x.year) + "-" + str(x.month) + "-" + str(x.day) + " " + str(x.hour) + ":" + str(x.minute) + ":" + str(x.second)

    customBus[form["vehicle"]] = dict
    return ""

@app.route("/fetchCBus/<busID>")
def fetchBus(busID):
    if (busID in customBus):
        response = jsonify(customBus[busID])
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    else:
        dict = busWrapper.RequestBusPosition(busID)
        response = jsonify(dict)
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    return jsonify({})

@app.route("/fetchC/<busID>")
def fetchC(busID):
    if ("T" + busID) in customBus:
        a = customBus["T" + busID]
        b = busWrapper.RequestBusPosition( busID )
        jsonData = {}
        jsonData["T"] = a
        if b:
            jsonData["N"] = b
        response = jsonify(jsonData)
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    return jsonify({})

if __name__ == "__main__":
    app.debug = True
    app.run(host= "0.0.0.0", port=os.environ["PORT"])


import numpy as np
import datetime

def proxify(obj):
    from descarteslabs import scenes
    from ..geospatial import GeoContext
    from ..core import Proxytype, ProxyTypeError
    from ..function import Function
    from ..containers import Tuple, List
    from ..primitives import Int, Float, Bool, Str, NoneType, Any
    from ..datetimes import Datetime, Timedelta
    from ..array import Array, MaskedArray, DType

    if isinstance(obj, Proxytype):
        return obj
    elif callable(obj):
        return Function.from_callable(obj)
    elif isinstance(obj, (tuple, list)):
        contents = [proxify(x) for x in obj]
        types = tuple(type(x) for x in contents)
        if (
            isinstance(obj, list)
            and len(types) > 0
            and all(t is types[0] for t in types[1:])
        ):
            return List[types[0]](contents)
        else:
            return Tuple[types](contents)
    elif isinstance(obj, (bool, np.bool_)):
        return Bool(obj)
    elif isinstance(obj, (int, np.integer)):
        return Int(obj)
    elif isinstance(obj, (float, np.float)):
        return Float(obj)
    elif isinstance(obj, str):
        return Str(obj)
    elif obj is None:
        return NoneType(obj)
    elif isinstance(obj, np.ma.MaskedArray):
        return MaskedArray.from_numpy(obj)
    elif isinstance(obj, np.ndarray):
        return Array(obj)
    elif isinstance(obj, np.dtype):
        return DType(obj)
    elif isinstance(obj, (datetime.datetime, datetime.date)):
        return Datetime._promote(obj)
    elif isinstance(obj, datetime.timedelta):
        return Timedelta._promote(obj)
    elif isinstance(obj, scenes.GeoContext):
        return GeoContext.from_scenes(obj)
    else:
        try:
            return Any._promote(obj)
        except ProxyTypeError:
            raise NotImplementedError(
                "Cannot automatically convert to a Proxytype. "
                "Please manually construct the appropriate container type "
                "and initialize it with your object. Value: {!r}".format(obj)
            )


# hw 1 problem 12

'''
An anagram is a type of word play, the result of rearranging the
letters of a word or phrase to produce a new word or phrase, using
all the original letters exactly once; e.g., orchestra = carthorse.
Using the word unixdict.txt, write a program
that finds the sets of words that share the same characters that
contain the most words in them.
'''

def  anagram(filepath):
     filepath = open ('unixdict.txt').read()
     words = filepath.split()
     for word_similar in words:
         for word in words:
             if set(word) == set(word_similar):
                 if len(word) == len(word_similar):
                     print (word, word_similar)

print(anagram('unixdict.txt'))


#! coding: utf-8
from collections import defaultdict
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q

from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt

from field_definitions import FIELDS_BY_DOCUMENT_TYPE

from utils.views import ACTIONS
from cross_validation import check_for_publication
from utils.context_processors import additional_user_info
from attachments.models import Attachment
from main.models import Descriptor
from title.models import Title
from database.models import Database
from help.models import get_help_fields
from utils.views import LoginRequiredView
from forms import *

import json

class BiblioRefGenericListView(LoginRequiredView, ListView):
    """
    Handle list view for bibliographic records objects
    """
    paginate_by = settings.ITEMS_PER_PAGE
    context_object_name = "references"
    search_field = "reference_title"

    def dispatch(self, *args, **kwargs):
        return super(BiblioRefGenericListView, self).dispatch(*args, **kwargs)

    def get_queryset(self):

        source_id = self.request.GET.get('source', None)
        document_type = self.request.GET.get('document_type', None)

        user_data = additional_user_info(self.request)
        user_role = user_data['service_role'].get('LILDBI')

        # getting action parameter
        self.actions = {}
        for key in ACTIONS.keys():
            self.actions[key] = self.request.GET.get(key, ACTIONS[key])

        search_field = self.search_field + '__icontains'

        # search by field
        search = self.actions['s']
        if ':' in search:
            search_parts = search.split(':')
            search_field = search_parts[0] + '__icontains'
            search = search_parts[1]

        if search:
            object_list = self.model.objects.filter(**{search_field: search})
        else:
            object_list = self.model.objects.all()

        if source_id:
            object_list = object_list.filter(source_id=source_id)

        if self.actions['filter_status'] != '':
            object_list = object_list.filter(status=self.actions['filter_status'])

        if self.actions['filter_indexed_database'] != '':
            object_list = object_list.filter(indexed_database=self.actions['filter_indexed_database'])

        # filter by specific document type and remove filter by user (filter_owner)
        if document_type:
            literature_type = re.sub('[^A-Z]|[CP]', '', document_type)  # get only uppercase chars excepct CP (congress/project)
            treatment_level = re.sub('[A-Z]', '', document_type)  # get only lowercase chars
            object_list = object_list.filter(literature_type__startswith=literature_type,
                                             treatment_level=treatment_level)

        if self.actions['order'] == "-":
            object_list = object_list.order_by("%s%s" % (self.actions["order"], self.actions["orderby"]))

        # if not at main reference list and source or document_type remove filter by user
        if self.model.__name__ != 'Reference' and (source_id or document_type):
            self.actions['filter_owner'] = '*'

        # profile lilacs express editor - restrict by CC code when list sources
        if document_type and user_role == 'editor_llxp':
            self.actions['filter_owner'] = 'center'

        # filter by user
        if not self.actions['filter_owner'] or self.actions['filter_owner'] == 'user':
            object_list = object_list.filter(created_by=self.request.user)
        # filter by cooperative center
        elif self.actions['filter_owner'] == 'center':
            user_cc = self.request.user.profile.get_attribute('cc')
            object_list = object_list.filter(cooperative_center_code=user_cc)
        # filter by titles of responsibility of current user CC
        elif self.actions['filter_owner'] == 'indexed':
            user_cc = self.request.user.profile.get_attribute('cc')
            titles_indexed = [t.shortened_title for t in Title.objects.filter(indexrange__indexer_cc_code=user_cc)]
            if titles_indexed:
                filter_title_qs = Q()
                for title in titles_indexed:
                    filter_title_qs = filter_title_qs | Q(referenceanalytic__source__title_serial=title) | Q(referencesource__title_serial=title)

                object_list = object_list.filter(filter_title_qs)
                # by default filter by LILACS express references
                if self.actions['filter_status'] == '':
                    self.actions['filter_status'] = 0
                    object_list = object_list.filter(status=0)
            else:
                # if no indexed journals are found return a empty list
                object_list = self.model.objects.none()

        # filter by records changed by others
        elif self.actions['filter_owner'] == 'review':
            if self.actions['review_type'] == 'user':
                ref_list = refs_changed_by_other_user(self.request.user)
            else:
                ref_list = refs_changed_by_other_cc(self.request.user)

            if ref_list:
                # get only ID's from filter reference list
                reference_id_list = ref_list.keys
                object_list = object_list.filter(id__in=reference_id_list)
            else:
                object_list = object_list.none()

        return object_list

    def get_context_data(self, **kwargs):
        context = super(BiblioRefGenericListView, self).get_context_data(**kwargs)
        user_data = additional_user_info(self.request)
        user_role = user_data['service_role'].get('LILDBI')
        source_id = self.request.GET.get('source')

        context['actions'] = self.actions
        context['document_type'] = self.request.GET.get('document_type')
        context['source_id'] = self.request.GET.get('source')
        context['user_role'] = user_role
        context['indexed_database_list'] = Database.objects.all().order_by('name')
        if source_id:
            context['reference_source'] = ReferenceSource.objects.get(pk=source_id)

        return context

# ========================= BiblioRef ========================================================

class BiblioRefListView(BiblioRefGenericListView, ListView):
    """
    Extend BiblioRefGenericListView to list bibliographic records
    """
    model = Reference

class BiblioRefListSourceView(BiblioRefGenericListView, ListView):
    """
    Extend BiblioRefGenericListView to list bibliographic records
    """
    model = ReferenceSource

class BiblioRefListAnalyticView(BiblioRefGenericListView, ListView):
    """
    Extend BiblioRefGenericListView to list bibliographic records
    """
    model = ReferenceAnalytic

class BiblioRefUpdate(LoginRequiredView):
    """
    Handle creation and update of bibliographic records
    """

    success_url = reverse_lazy('list_biblioref')

    def form_valid(self, form):
        formset_descriptor = DescriptorFormSet(self.request.POST, instance=self.object)
        formset_attachment = AttachmentFormSet(self.request.POST, self.request.FILES, instance=self.object)
        formset_library = LibraryFormSet(self.request.POST, instance=self.object)
        formset_complement = ComplementFormSet(self.request.POST, instance=self.object)

        # run all validation before for display formset errors at form
        form_valid = form.is_valid()

        formset_descriptor_valid = formset_descriptor.is_valid()
        formset_attachment_valid = formset_attachment.is_valid()
        formset_library_valid = formset_library.is_valid()
        formset_complement_valid = formset_complement.is_valid()

        user_data = additional_user_info(self.request)
        # run cross formsets validations
        valid_for_publication = check_for_publication(form, {'descriptor': formset_descriptor,
                                                             'attachment': formset_attachment}, user_data)

        if (form_valid and formset_descriptor_valid and formset_attachment_valid and
           formset_complement_valid and valid_for_publication):

                self.object = form.save()

                # Check if is present conference or project complement
                complement_conference = formset_complement.cleaned_data[0].get('conference_name')
                complement_project = (formset_complement.cleaned_data[0].get('project_name') or
                                      formset_complement.cleaned_data[0].get('project_number'))

                # Update information at literature_type field
                if complement_conference:
                    self.object.literature_type += 'C'
                elif 'C' in self.object.literature_type:
                    self.object.literature_type = self.object.literature_type.replace('C', '')

                if complement_project:
                    self.object.literature_type += 'P'
                elif 'P' in self.object.literature_type:
                    self.object.literature_type = self.object.literature_type.replace('P', '')

                if (complement_conference or complement_project):
                    self.object.save()

                formset_descriptor.instance = self.object
                formset_descriptor.save()

                formset_attachment.instance = self.object
                formset_attachment.save()

                formset_library.instance = self.object
                formset_library.save()

                formset_complement.instance = self.object
                formset_complement.save()

                # update solr index
                form.save()
                # save many-to-many relation fields
                form.save_m2m()
                return HttpResponseRedirect(self.get_success_url())
        else:
            # if not valid for publication return status to original (previous) value
            if self.object:
                previous_status = self.object.previous_value('status')
                self.object.status = previous_status
                form.data['status'] = previous_status
            else:
                form.data['status'] = '-1'

            return self.render_to_response(
                           self.get_context_data(form=form,
                                                 formset_descriptor=formset_descriptor,
                                                 formset_attachment=formset_attachment,
                                                 formset_library=formset_library,
                                                 formset_complement=formset_complement,
                                                 valid_for_publication=valid_for_publication))

    def form_invalid(self, form):
            # force use of form_valid method to run all validations
            return self.form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(BiblioRefUpdate, self).get_form_kwargs()
        document_type = ''
        reference_source = None

        source_id = self.request.GET.get('source', None)
        # new analytic
        if source_id:
            reference_source = ReferenceSource.objects.get(pk=source_id)
            literature_type = reference_source.literature_type
            treatment_level = reference_source.treatment_level
            # remove congress/project from literature_type
            literature_type = re.sub('[CP]', '', literature_type)

            if literature_type == 'S':
                document_type = 'Sas'
            else:
                if 'c' in treatment_level:
                    document_type = "{0}amc".format(literature_type)
                elif 's' in treatment_level:
                    document_type = "{0}ams".format(literature_type)
                else:
                    document_type = "{0}am".format(literature_type)

        # edition/new source
        else:
            # source/analytic edition
            if self.object:
                if hasattr(self.object, 'source'):
                    reference_source = self.object.source

                # remove congress/project from literature_type
                literature_type = re.sub('[CP]', '', self.object.literature_type)

                document_type = "{0}{1}".format(literature_type, self.object.treatment_level)
            # new source
            else:
                document_type = self.request.GET.get('document_type')

        # get list of fields allowed by document_type
        fieldsets = FIELDS_BY_DOCUMENT_TYPE.get(document_type, None)

        user_data = additional_user_info(self.request)

        additional_form_parameters = {}
        additional_form_parameters['user'] = self.request.user
        additional_form_parameters['user_data'] = user_data
        additional_form_parameters['fieldsets'] = fieldsets
        additional_form_parameters['document_type'] = document_type
        additional_form_parameters['reference_source'] = reference_source

        kwargs.update(additional_form_parameters)

        return kwargs

    def get_context_data(self, **kwargs):
        context = super(BiblioRefUpdate, self).get_context_data(**kwargs)

        user_data = additional_user_info(self.request)
        user_role = user_data['service_role'].get('LILDBI')
        user_id = self.request.user.id
        if self.object:
            user_data['is_owner'] = True if self.object.created_by == self.request.user else False

        context['user_data'] = user_data
        context['user_role'] = user_role

        # create flag that control if user have permission to edit the reference
        if user_role == 'editor_llxp':
            context['user_can_edit'] = True if not self.object or (self.object.status != 1 and self.object.cooperative_center_code == user_data['user_cc']) else False
            context['user_can_change_status'] = False
        elif user_role == 'doc':
            context['user_can_edit'] = True if not self.object or self.object.status < 1 or (self.object.status != 1 and self.object.cooperative_center_code == user_data['user_cc']) else False
            context['user_can_change_status'] = False
        else:
            context['user_can_edit'] = True
            context['user_can_change_status'] = True

        view_mode = self.request.GET.get('view_mode', False)
        if view_mode:
            context['user_can_edit'] = False

        context['settings'] = settings
        context['view_mode'] = view_mode
        context['help_fields'] = get_help_fields('biblioref')

        if self.object:
            c_type = ContentType.objects.get_for_model(self.get_object())
            context['c_type'] = c_type

        if self.request.method == 'GET':
            context['formset_descriptor'] = DescriptorFormSet(instance=self.object)
            context['formset_attachment'] = AttachmentFormSet(instance=self.object)
            context['formset_library'] = LibraryFormSet(instance=self.object,
                                                        queryset=ReferenceLocal.objects.filter(cooperative_center_code=user_data['user_cc']))
            context['formset_complement'] = ComplementFormSet(instance=self.object)

        # source/analytic edition
        if self.object:
            context['document_type'] = "{0}{1}".format(self.object.literature_type, self.object.treatment_level)
        # new source
        else:
            document_type = self.request.GET.get('document_type')
            source_id = self.request.GET.get('source')

            if document_type:
                context['document_type'] = document_type
            elif source_id:
                reference_source = ReferenceSource.objects.get(pk=source_id)
                literature_type = reference_source.literature_type
                if literature_type == 'S':
                    document_type = 'Sas'
                else:
                    document_type = "{0}am".format(literature_type)

                context['document_type'] = document_type

        return context

    # after creation of source present option for creation new analytic
    def get_success_url(self):
        user_data = additional_user_info(self.request)
        user_role = user_data['service_role'].get('LILDBI')

        if user_role == 'editor_llxp':
            redirect_url = "%s?document_type=S" % reverse_lazy('list_biblioref_sources')
        else:
            redirect_url = self.success_url

        return redirect_url

class BiblioRefSourceUpdateView(BiblioRefUpdate, UpdateView):
    """
    Used as class view to update BiblioRef
    Extend BiblioRefUpdate that do all the work
    """
    model = ReferenceSource
    form_class = BiblioRefSourceForm

class BiblioRefAnaliticUpdateView(BiblioRefUpdate, UpdateView):
    """
    Used as class view to update BiblioRef
    Extend BiblioRefUpdate that do all the work
    """
    model = ReferenceAnalytic
    form_class = BiblioRefAnalyticForm

    def get_context_data(self, **kwargs):
        # add source to context of form to present source information
        context = super(BiblioRefAnaliticUpdateView, self).get_context_data(**kwargs)
        context['reference_source'] = self.object.source

        return context

    # after creation of source present option for creation new analytic
    def get_success_url(self):
        return '/bibliographic/analytics?source=%s' % self.object.source.id

class BiblioRefSourceCreateView(BiblioRefUpdate, CreateView):
    """
    Used as class view to create BiblioRef
    Extend BiblioRefUpdate that do all the work
    """
    model = ReferenceSource
    form_class = BiblioRefSourceForm

    # after creation of source present option for creation new analytic
    def get_success_url(self):
        redirect_url = ''
        if self.object.literature_type[0] == 'S':
            redirect_url = 'new-analytic?source=%s' % self.object.pk
        else:
            redirect_url = '/bibliographic/'

        return redirect_url

class BiblioRefAnalyticCreateView(BiblioRefUpdate, CreateView):
    """
    Used as class view to create BiblioRef
    Extend BiblioRefUpdate that do all the work
    """
    model = ReferenceAnalytic
    form_class = BiblioRefAnalyticForm

    def get_context_data(self, **kwargs):
        # add source to context of form to present source information
        context = super(BiblioRefAnalyticCreateView, self).get_context_data(**kwargs)
        source_id = self.request.GET.get('source', None)

        if source_id:
            reference_source = ReferenceSource.objects.get(pk=source_id)
            context['reference_source'] = reference_source

        return context

    # after creation of source present option for creation new analytic
    def get_success_url(self):
        source_id = self.request.GET.get('source', None)
        return 'analytics?source=%s' % source_id

class SelectDocumentTypeView(FormView):
    template_name = 'biblioref/select_document_type.html'
    form_class = SelectDocumentTypeForm

class BiblioRefDeleteView(LoginRequiredView, DeleteView):
    """
    Handle delete of BiblioRef objects
    """
    model = Reference
    success_url = reverse_lazy('list_biblioref')

    def get_object(self, queryset=None):
        obj = super(BiblioRefDeleteView, self).get_object()
        """ Hook to ensure object is owned by request.user. """
        if not obj.created_by == self.request.user:
            return HttpResponse('Unauthorized', status=401)

        return obj

    def delete(self, request, *args, **kwargs):
        obj = super(BiblioRefDeleteView, self).get_object()
        child_class = obj.child_class()
        c_type = ContentType.objects.get_for_model(child_class)

        # delete associated data
        Descriptor.objects.filter(object_id=obj.id, content_type=c_type).delete()
        Attachment.objects.filter(object_id=obj.id, content_type=c_type).delete()
        ReferenceLocal.objects.filter(source=obj.id).delete()
        ReferenceComplement.objects.filter(source=obj.id).delete()

        return super(BiblioRefDeleteView, self).delete(request, *args, **kwargs)

@csrf_exempt
def view_duplicates(request, reference_id):
    """
    Present list of duplicates references (identified at migration process)
    """
    duplicate_list = ReferenceDuplicate.objects.filter(reference=reference_id)
    metadata = indexing = library = complement = other = {}
    duplicate = None

    duplicate_id = request.GET.get('duplicate_id')
    if duplicate_id:
        duplicate = ReferenceDuplicate.objects.get(pk=duplicate_id)
    elif duplicate_list.count() == 1:
        duplicate = duplicate_list[0]

    if duplicate:
        try:
            metadata = json.loads(duplicate.metadata_json)
            indexing = json.loads(duplicate.indexing_json)
            library = json.loads(duplicate.library_json)
            complement = json.loads(duplicate.complement_json)
            other = json.loads(duplicate.others_json)
        except:
            # ignore possible errors at json load at field (eg. empty field)
            pass

    return render_to_response('biblioref/duplicate_detail.html', {'duplicate_list': duplicate_list,
                                                                  'duplicate': duplicate,
                                                                  'metadata': metadata,
                                                                  'indexing': indexing,
                                                                  'library': library,
                                                                  'complement': complement,
                                                                  'other': other,
                                                                  })

def refs_changed_by_other_cc(current_user):
    """
    Return dictionary with id of reference and log object changed by other cooperative centers
    """
    current_user_cc = current_user.profile.get_attribute('cc')
    result_list = defaultdict(list)

    # get last references of current user cooperative center
    refs_from_cc = Reference.objects.filter(cooperative_center_code=current_user_cc).order_by('-id')[:100]

    for reference in refs_from_cc:
        # get correct class (source our analytic)
        c_type = reference.get_content_type_id
        # filter by logs of current reference, change type and made by other users
        log_list = LogEntry.objects.filter(object_id=reference.id, content_type=c_type, action_flag=2) \
                                   .exclude(user=current_user).order_by('-id')

        if log_list:
            # exclude from list all changes that was already reviewed (logreview is created)
            log_list = log_list.exclude(logreview__isnull=False)

        # create list of log users of same cc
        exclude_user_list = []
        for log in log_list:
            log_user_cc = log.user.profile.get_attribute('cc')
            if log_user_cc == current_user_cc:
                exclude_user_list.append(log.user)
        # exclude from log list users from same cc as current user
        if exclude_user_list:
            log_list = log_list.exclude(user__in=exclude_user_list)

        if log_list:
            # group result by id (one line for each reference)
            for log in log_list:
                result_list[log.object_id] = log

    return result_list

def refs_changed_by_other_user(current_user):
    """
    Return dictionary with id of reference and log object changed by other user
    """
    log_list = []
    result_list = defaultdict(list)

    # get references created by current user
    refs_from_user = Reference.objects.filter(created_by=current_user)
    for reference in refs_from_user:
        # get correct class (source our analytic)
        c_type = reference.get_content_type_id
        # filter by logs of current reference, change type and made by other users
        changed_by_other_user = LogEntry.objects.filter(object_id=reference.id, content_type=c_type, action_flag=2) \
                                                .exclude(user=current_user).order_by('-id')
        if changed_by_other_user:
            # exclude from list all changes that was already reviewed (logreview is created)
            changed_by_other_user = changed_by_other_user.exclude(logreview__isnull=False)

        log_list.extend(changed_by_other_user)

    # group result (one line for each reference)
    if log_list:
        # group result by id (one line for each reference)
        for log in log_list:
            result_list[log.object_id] = log

    return result_list

def refs_llxp_for_indexing(current_user):

    user_cc = current_user.profile.get_attribute('cc')

    # first filter by LLXP records
    ref_list = Reference.objects.filter(status=0)

    titles_indexed = [t.shortened_title for t in Title.objects.filter(indexrange__indexer_cc_code=user_cc)]
    filter_title_qs = Q()
    for title in titles_indexed:
        filter_title_qs = filter_title_qs | Q(referenceanalytic__source__title_serial=title)

    # filter by titles indexed by current user cc
    ref_list = ref_list.filter(filter_title_qs)

    return ref_list


#! /usr/local/python_anaconda/bin/python3.4
"""
@Author: odedkushnir

"""
import sys
from optparse import OptionParser
from Bio.Seq import Seq
from file_utilities import check_filename, check_dirname
import os

def main():
    parser = OptionParser("usage: %prog [options]")
    parser.add_option("-f", "--file1", dest="file1", help="fastq1 file")
    parser.add_option("-e", "--file2", dest="file2", help="fastq2 file")
    parser.add_option("-o", "--output_file", dest="output_file", help="output fastq merged file")
    (options, args) = parser.parse_args()
    file1 = options.file1
    file2 = options.file2
    output_file = options.output_file

    concat_fastq(file1, file2, output_file)

def concat_fastq(file1, file2, output_file):
    """
    merge 2 files of fatsq to 1 file base on the id
    :param file1: fastq file 1 you want to merge
    :param file2: fastq file 2 you want to merge
    :param output_file: merged file
    :return:
    """
    with open(file1, 'r') as fastq1, open(file2, 'r') as fastq2, open(output_file, 'w') as output_file:
        f1 = fastq1.readlines()
        f2 = fastq2.readlines()
        for i in range(0, len(f1), 4):
            f1[i].strip()
            f2[i].strip()
            if f1[i].split(" ")[0] == f2[i].split(" ")[0]:
                merge_id = f1[i].split(" ")[0]
                merge_seq = str(Seq(f1[i + 1].strip()) + 'N' + Seq(f2[i + 1].strip()).reverse_complement())
                merge_dir = f1[i + 2].strip()
                merge_qual = f1[i + 3].strip() + '!' + f2[i + 3].strip()
                output_file.write(merge_id + '\n' + merge_seq + '\n' + merge_dir + '\n' + merge_qual + '\n')
            else:
                print("Problem:" + str(i))

if __name__ == "__main__":
    main()