import json
import re

def __insert_or_append(dic, key, value):
    if key not in dic:
        dic[key] = [value]
    else:
        dic[key].append(value)

def __logger(in_path, out_path, pattern, processor=None):
    in_file = open(in_path, 'r')
    out_file = open(out_path, 'w')
    p = re.compile(pattern)
    for line in in_file:
        j = json.loads(line)
        if not p.match(j['message']):
            continue
        if processor:
            out_file.write(processor(j))
        else:
            out_file.write(str(j).replace('\'', '"') + '\n')

def __processor(in_path, msg_heading):
    info = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        j = json.loads(line)
        msg, pid = j['message'], int(j['process'])

        record = {}
        for field in msg[len(msg_heading):].split(', '):
            [key, value] = field.split('=')
            try:
                value_stored = int(value)
            except:
                value_stored = value
            info[key] = value_stored

        __insert_or_append(info, pid, record)

    return info

def __csv_gen(in_path, out_path, pid, fields, processor):
    info = processor(in_path)
    out = open(out_path, 'w')
    out.write(','.join(fields) + '\n')
    for item in info[pid]:
        out_line = ','.join([str(item[field]) for field in fields])
        out.write(out_line + '\n')

def clean(in_path, out_path):

    def process(j):
        j['timestamp'] = j['timestamp'].split(' ')[1][:-6]
        for field in ['level', 'tag', 'raw']:
            j.pop(field, None)
        return str(j).replace('\'', '"') + '\n'

    __logger(in_path, out_path, r'^\[HT\]', process)

def gc_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[GC\]')

def sys_gc_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[SysGC\]')

def heap_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[Heap\]')

def mem_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[((IPut)|(IGet))\]')

def __heap_processor(in_path):
    """
    Message format:
        [HT] [Heap] ts=...,
                    bytes_allocated=..., bytes_tl_bulk_allocated=..., heap_num_bytes_allocated=...,
                    art_obj_allocated=..., art_bytes_allocated=...
    Data format:
        { pid: {ts                      : int,  // unix-style timestamp
                bytes_allocated         : int,
                bytes_tl_bulk_allocated : int,
                heap_num_bytes_allocated: int,
                art_obj_allocated       : int,
                art_bytes_allocated     : int,
        }}
    """
    pid_heap = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        l = json.loads(line)
        msg, pid = l['message'], int(l['process'])
        if msg.find('[HT] [Heap]') == -1:
            continue

        heap_alloc_info = {}
        for field in msg[12:].split(', '):
            [key, value] = field.split('=')
            heap_alloc_info[key] = int(value)

        __insert_or_append(pid_heap, pid, heap_alloc_info)

    return pid_heap

def __gc_processor(in_path):
    """
    Message format:
        [HT] [GC] [End] ts=...,
                        gc_cause=..., gc_name=...,
                        heap_obj_allocated=..., heap_bytes_allocated=...,
                        heap_obj_allocated_ever=..., heap_obj_freed_ever=..., heap_bytes_allocated_ever=..., heap_bytes_freed_ever=...,
                        gc_obj_freed=..., gc_bytes_freed=..., gc_large_obj_freed=..., gc_large_bytes_freed=...
    Data format:
        { pid: [{ ts                       : int,
                  tsh                      : int,
                  gc_cause                 : str,
                  gc_name                  : str,
                  heap_obj_allocated       : int,
                  heap_bytes_allocated     : int,
                  heap_obj_allocated_ever  : int,
                  heap_obj_freed_ever      : int,
                  heap_bytes_allocated_ever: int,
                  heap_bytes_freed_ever    : int,
                  gc_obj_freed             : int,
                  gc_bytes_freed           : int,
                  gc_large_obj_freed       : int,
                  gc_large_bytes_freed     : int,
        }]}
    """
    pid_gc = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        l = json.loads(line)
        msg, pid = l['message'], int(l['process'])
        if msg.find('[HT] [GC] [End]') == -1:
            continue

        gc_info = {}
        for field in msg[16:].split(', '):
            [key, value] = field.split('=')
            try:
                value_stored = int(value)
            except:
                value_stored = value
            gc_info[key] = value_stored

        __insert_or_append(pid_gc, pid, gc_info)

    return pid_gc

def __mem_processor(in_path):
    """
    Message format
    Data format
    """
    pid_tid_mem = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        l = json.loads(line)
        msg, pid, tid = l['message'], int(l['process']), int(l['thread'])
        if msg.find('[HT] [IPut]') == -1 and msg.find('[HT] [IGet]') == -1:
            continue

        mem_info = {}
        for field in msg[12:].split(', '):
            [key, value] = field.split('=')
            try:
                value_stored = int(value)
            except:
                value_stored = value
            mem_info[key] = value_stored

        __insert_or_append(pid_tid_mem, (pid, tid), mem_info)

    return pid_tid_mem

def heap_csv(in_path, out_path, pid, fields=None):
    if fields is None:
        fields = ['tshres', 'bytes_allocated', 'bytes_tl_bulk_allocated', 'heap_num_bytes_allocated']
    __csv_gen(in_path, out_path, pid, fields, __heap_processor)

def gc_csv(in_path, out_path, pid, fields=None):
    if fields is None:
        fields = ['tshres', 'gc_obj_freed', 'gc_bytes_freed', 'heap_obj_freed_ever', 'heap_bytes_freed_ever', 'heap_obj_allocated', 'heap_bytes_allocated']
    __csv_gen(in_path, out_path, pid, fields, __gc_processor)

def mem_csv(in_path, out_path, pid, fields=None):
    if fields is None:
        fields = ['tshres', 'method', 'field', 'iget', 'iput']
    __csv_gen(in_path, out_path, (pid, pid), fields, __mem_processor)


import setuptools

with open("README.md") as fp:
    long_description = fp.read()

setuptools.setup(
    name="serverless_app_pipeline_cdk",
    version="0.0.1",
    description="An empty CDK Python app",
    long_description=long_description,
    long_description_content_type="text/markdown",
    author="author",
    package_dir={"": "serverless_app_pipeline_cdk"},
    packages=setuptools.find_packages(where="serverless_app_pipeline_cdk"),
    install_requires=[
        "aws-cdk.core",
        "aws_cdk.aws_codedeploy",
        "aws_cdk.aws_codebuild",
        "aws_cdk.aws_codepipeline",
        "aws_cdk.aws_codecommit",
        "aws_cdk.aws_codepipeline_actions",
        "aws_cdk.aws_secretsmanager",
        "aws_cdk.aws_kms",
        "aws_cdk.aws_s3",
        "aws_cdk.aws_iam",
        "aws_cdk.aws_wafv2",
        "aws_cdk.aws_cloudfront",
        "aws_cdk.aws_certificatemanager",
    ],
    python_requires=">=3.6",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: JavaScript",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Topic :: Software Development :: Code Generators",
        "Topic :: Utilities",
        "Typing :: Typed",
    ],
)


from parser import get_generator
import sqlalchemy as db
from dbModel import student

def fill_db():
    gen = get_generator()
    engine = db.create_engine("sqlite:///Students.db")
    with engine.connect() as connection:
        while True:
            try:
                insertion_query = student.insert().values(next(gen))
                connection.execute(insertion_query)
            except AttributeError:
                break
        connection.commit()


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 13:10:03 2019

@author: Jzz
"""

import requests
import sys
from bs4 import BeautifulSoup
import re
import json
import calendar  #为了确定终止时间是在某个月的几号

import io
import time
import urllib

def Login(cookie_str):

    #浏览器登录后得到的cookie，一定要是Response Header里 status为200 OK的那个数据里的cookie
#    cookie_str = cookie
    #把cookie字符串处理成字典，以便接下来使用
    cookies = {}
    for line in cookie_str.split(';'):
#        print(line)
        key, value = line.split('=')
        cookies[key] = value

    #设置请求头
    headers = {'User-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
    #在发送get请求时带上请求头和cookies
    #resp = requests.get(url, headers = headers, cookies = cookies)
    #用get方法，得到的实际是https://www.sui.com/tally/new.do的结果，没有需要的数据

    resp = requests.get(url,headers = headers, cookies = cookies)
    print(resp.text)
    #检查是否登录成功
    if re.compile(r"***").search(resp.text):#自己的人人网的姓名
        print('Login Success')
        requestToken = re.findall("requestToken : '([^']*)',",resp.text) #正则出来是列表
        rtk = re.findall("_rtk : '([^']*)'",resp.text)
#        print(requestToken,rtk)
        return (cookies,1,requestToken[0],rtk[0])
    else:
        print('Login failed')
        return (cookies,0)

def savePic(albumUrl,cookies,requestToken,rtk):
#    try:
    headers = {'User-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
    #在发送get请求时带上请求头和cookies

    resp = requests.get(albumUrl,headers = headers, cookies = cookies)
    data = resp.text
#        print(data)
#正则提取   # "albumId":"1083919536"
    albumIdlist = re.findall('"albumId":"([^"]*)",',data)
#        imglist = re.findall('"url":"([^<]+)"}',data)
    print(albumIdlist)

 ##############根据得到的图片路径URL将图片下载下来保存本地########
    x= 0
    for albumId in albumIdlist:
        #每一个相册的网址

#        single_album_url = 'http://photo.renren.com/photo/***/album-%s/v7' %albumId  # 该网址最多只能解析前40张图片，其余的滚动鼠标，通过ajax加载出来的
        for page_index in range(1,10):
#            print(albumId,str(page_index),requestToken,rtk)
            single_album_single_page_url = 'http://photo.renren.com/photo/***/album-%s/bypage/ajax/v7?page=%s&pageSize=20&requestToken=%s&_rtk=%s'  %(albumId,str(page_index),requestToken,rtk)
            cont = requests.get(single_album_single_page_url,headers = headers, cookies = cookies)
            #相册内部的源代码
#            print(cont.text)
            imglist = re.findall('"url":"([^"]*)"',cont.text)#找到每张图片的ID
    #        print(imglist)
            if imglist !=[]: #如果为空，则终止

                #处理网址去除\
                for index,item in enumerate(imglist):
                    if '\\' in item:
                        imglist[index] = imglist[index].replace('\\','')
#                print(imglist)
                for single_pic_url in imglist:
                    print(single_pic_url)
                    ##############根据得到的图片路径URL将图片下载下来保存本地########
                    request = urllib.request.Request(url = single_pic_url, headers=headers)
                    response = urllib.request.urlopen(request)
                    img = response.read()
                    with open('F:\image\miao\miao%s.jpg' %x, 'wb') as fp:
                        fp.write(img)
        #            urllib.request.urlretrieve(single_pic_url,r'D:\image\miao\miao%s.jpg' %x)
                        print('miao%s.jpg done' %x)
                        x+=1

#登录后才能访问的网页
url = 'http://www.renren.com/34434***' # 自己的登陆主页
albumUrl = "http://photo.renren.com/photo/***/albumlist/v7?offset=0&limit=40#"# ***为你想下载图片的朋友的人人ID

cookie_str = r'***'#为简便起见，利用cookie登陆，火狐浏览器可以利用HttpFox工具查看
login_result = Login(cookie_str)
cookies = login_result[0]

#
if login_result[1] == 1:
    requestToken = login_result[2]
    rtk = login_result[3]
    savePic(albumUrl,cookies,requestToken,rtk)


#import numpy as np

class Accum():
    """
    Designer:       Andrew Carroll

    Description:    Accumulator with optional rollover/clamp.

    Attributes:     maxVal:     Maximum value of accumulator
                    rollOver:   (*optional) Set to True for automatic rollover
                                    at maxVal. Otherwise clamp at maxVal.
                                    Default = True

    Methods:        update(incrVal):        Add incrVal to accumulator
                    clear():                Clear accumulator (set to 0)
    """
    def __init__(self,maxVal,rollOver=True):
        self.maxVal = maxVal
        self.accum = 0
        self.rollOver = rollOver

    def update(self,incrVal):
        """
        Description:    Add incrVal to accumulator

        Params:         incrVal:    Value to add to accumulator

        Returns:        accum:      New accumulator value
        """
        self.accum = self.accum + incrVal
        if (self.accum > self.maxVal):
            if (self.rollOver == True):
                self.accum = self.accum - self.maxVal - 1
            else:
                self.accum = self.maxVal
        elif (self.accum < 0):
            if (self.rollOver == True):
                self.accum = self.accum + self.maxVal + 1
            else:
                self.accum = 0
        return self.accum

    def clear(self):
        """
        Description:    Clear accumulator

        Params:         None

        Returns:        None
        """
        self.accum = 0
        return

class NCO(Accum):
    """
    Designer:       Andrew Carroll

    Description:    Implements Numerically Controlled Oscillator. Special
                    Accum subclass with rollOver always set to True.

    Attributes:     maxVal:     Maximum value of accumulator

    Methods:        update(incrVal):        Add incrVal to accumulator
                    clear():                Clear accumulator (set to 0)
    """
    def __init__(self,maxVal):
        super(NCO, self).__init__(maxVal)


import numpy
import matplotlib.pyplot as plt

x = numpy.linspace(0, 2 * numpy.pi, 100)
sin_y = numpy.sin(x)
cos_y = numpy.cos(x)

plt.plot(x, sin_y)
plt.plot(x, cos_y, '-.', color='red')
plt.show()


class Solution:
    def minTimeToType(self, word: str) -> int:
        typewriter = [chr(i) for i in range(97, 97+26)]
        ind = 0
        answer = 0
        pointer = 0
        while ind < len(word):
            if word[ind] == typewriter[pointer]:
                answer += 1
                ind += 1
            else:
                if word[ind] > typewriter[pointer]:
                    needRight = ord(word[ind]) - ord(typewriter[pointer])
                    needLeft = pointer + (123 - ord(word[ind]))
                    answer += min(needRight, needLeft)
                    pointer = pointer + needRight
                elif word[ind] < typewriter[pointer]:
                    needRight = (26 - pointer) + (ord(word[ind]) - 97)
                    needLeft = ord(typewriter[pointer]) - ord(word[ind])
                    answer += min(needRight, needLeft)
                    pointer = pointer + needRight - 26
        return answer

LeetCode/1974. Minimum Time to Type Word Using Special Typewriter.py


"""Work model tests."""

import os
from unittest import TestCase
from sqlalchemy import exc

from models import db, User, Superheros, MySuperheros, SuperheroInfo, Powerstats, Biography, Appearance, Work, Connections

os.environ['DATABASE_URL'] = "postgresql:///superhero-test"

from app import app

db.create_all()

class WorkModelTestCase(TestCase):
    """Test model for work."""

    def setUp(self):
        """Create test client, add sample data."""
        db.drop_all()
        db.create_all()

        testuser = User.signup("John", "Smith", "test1", "password")
        self.testuser_id = 1111

        testuser.id = self.testuser_id
        db.session.commit()

        self.testuser = User.query.get(self.testuser_id)

        self.client = app.test_client()

    def tearDown(self):
        res = super().tearDown()
        db.session.rollback()
        return res

    def test_add_work_to_superheros(self):

        superheroinfo = SuperheroInfo(
            name="Batman"
        )

        work = Work(
            occupation="hero",
            base_of_operation="NA")

        superheroinfo.work.append(work)
        self.testuser.superheros.append(superheroinfo)

        db.session.add(superheroinfo, work)
        db.session.commit()

        self.assertEqual(len(self.testuser.superheros), 1)
        self.assertEqual(self.testuser.superheros[0].name, "Batman")
        self.assertEqual(len(superheroinfo.work), 1)
        self.assertEqual(work.superheroinfo_id, superheroinfo.id)
        self.assertEqual(superheroinfo.work[0].occupation, "hero")
        self.assertEqual(superheroinfo.work[0].base_of_operation, "NA")

    def test_add_work_to_mysuperheros(self):

        superheroinfo = SuperheroInfo(
            name="Batman"
        )

        work = Work(
            occupation="hero",
            base_of_operation="NA")

        superheroinfo.work.append(work)
        self.testuser.mysuperheros.append(superheroinfo)

        db.session.add(superheroinfo, work)
        db.session.commit()

        self.assertEqual(len(self.testuser.mysuperheros), 1)
        self.assertEqual(self.testuser.mysuperheros[0].name, "Batman")
        self.assertEqual(len(superheroinfo.work), 1)
        self.assertEqual(work.superheroinfo_id, superheroinfo.id)
        self.assertEqual(superheroinfo.work[0].occupation, "hero")
        self.assertEqual(superheroinfo.work[0].base_of_operation, "NA")


from collections import deque

def solution(queue1, queue2):
    answer = 0
    queue1, queue2 = deque(queue1), deque(queue2)
    sum1, sum2 = sum(queue1), sum(queue2)
    half_sum = (sum1 + sum2) // 2

    while queue1 and queue2:
        if sum1 > half_sum:
            sum1 -= queue1.popleft()
        elif sum1 < half_sum:
            pop_ = queue2.popleft()
            queue1.append(pop_)
            sum1 += queue1[-1]
        else:
            return answer
        answer += 1
    return -1

프로그래머스/unrated/118667. 두 큐 합 같게 만들기/두 큐 합 같게 만들기.py

두 큐 합 같게 만들기.py


# (c) 2016 Spiros Papadimitriou <spapadim@gmail.com>
#
# This file is released under the MIT License:
#    https://opensource.org/licenses/MIT
# This software is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied.

import unittest
from .homework_unittest import HomeworkTestCase, try_import

try_import("number", ["is_squarefree"])
# Next line intended to get VSCode to autocomplete and hush warnings
is_squarefree = is_squarefree  # pylint: disable=E0602

class SquareFreeTests(HomeworkTestCase):
  def test__import(self):  # double-underscore so test appears at top of UI list
    self.assertIsNotNone(is_squarefree, msg="Importing your solution failed")

  def test__is_library(self):
    self.assertLibraryModule("number.py")

  def test_225(self):
    # Test all numbers from 2 to 100, inclusive
    squarefree = [None, None] + [True] * 224  # pad, so can index directly
    # Variation of Eratosthenes' sieve,
    # to pre-compute correct answers efficiently
    for i in range(2, 16):
      sq = i*i
      for n in range(sq, 226, sq):
        squarefree[n] = False

    # Actual test runs
    for N in range(2, 226):
      result = is_squarefree(N)
      self.assertEqual(squarefree[N], result,
                       msg=f"Failed for N={N}, expected {squarefree[N]} but got {result}")

if __name__ == '__main__':
  unittest.main()


import sys
input = sys.stdin.readline
n = int(input())
arr = [tuple(map(int,input().split())) for _ in range(n)]
arr.sort()
st,fi = arr[0][0],arr[0][1]
ans = 0
for i in range(1,n):
    if arr[i][0] >= st and arr[i][1] <= fi: continue
    elif arr[i][0] >= st and arr[i][0] <= fi and arr[i][1] >= fi: fi = arr[i][1]
    elif arr[i][0] >= st:
        ans += fi-st
        st,fi = arr[i][0],arr[i][1]
ans += fi - st
print(ans)

백준/Gold/15922. 아우으 우아으이야！！/아우으 우아으이야！！.py

아우으 우아으이야！！.py


import requests

from rdj_voting.ressources import RDJ_VOTING, get_logger

_logger = get_logger(__name__)

class RdjSong:

    def __init__(self, song_title, artist_name, song_list, song_id):
        self.song_title = song_title
        self.artist_name = artist_name
        self.song_id = song_id
        self.song_list = song_list

    def send_voting(self, verbose=False):
        voting_url = RDJ_VOTING.format(self.song_list, self.song_id)
        result = requests.get(voting_url)
        if verbose:
            _logger.info("{}, {} for : {} - {}".format(result.status_code, result.text, self.song_title, self.artist_name))
        return result.status_code == 200


#Startup
import pygame
import random
import math
import webbrowser

# -- Global Constants
size = (640,480)
player_score = 0
pleasework = False
# -- Colours
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (50,50,255)
YELLOW = (255,255,0)
RED = (255, 0, 0)
# -- Initialise PyGame
pygame.init()
#Load music
pygame.mixer.music.load('The-Avengers-Theme-Song.mp3')
#Play music
pygame.mixer.music.play()
# -- Blank Screen
screen = pygame.display.set_mode(size)
# -- Title of new window/screen
pygame.display.set_caption("Space Invaders Lite")

#Displays game stats
def draw_stats(screen, x, y, stats):
    # Select the font to use, size, bold, italics
    font = pygame.font.SysFont('Calibri', 30, True, False)
    # Render the text. "True" means anti-aliased text.
    # Note: This line creates an image of the letters,
    # but does not put it on the screen yet.
    text = font.render(str(stats), True, YELLOW)
    # Puts the image of the text on the screen at x,y
    screen.blit(text, (x, y))
#Endproc

## -- Define the class Player which is a sprite
class Player(pygame.sprite.Sprite):
    # Define the constructor for Player
    def __init__(self, color, width, height, lives, score, bullet_count):

        # Call the sprite constructor
        super().__init__()
        # Create a sprite and fill it with colour
        self.width = width
        self.height = height
        self.image = pygame.Surface([width,height])
        self.image.fill(color)
        # Set the position of the sprite
        self.rect = self.image.get_rect()
        self.rect.x = 300
        self.rect.y = size[1] - height
        self.speed = 0
        self.lives = lives
        self.score = 0
        self.bullet_count = bullet_count
    #Endwhat?

    # Class update function - runs for each pass through the game loop
    def update(self):
        self.rect.x = self.rect.x + self.speed
        if self.rect.x >= size[0]:
            self.rect.x = 0
        elif self.rect.x <= 0:
            self.rect.x = size[0]
        #Endif
    #Endmethod

    def player_set_speed(self, val):
        self.speed = val
    #Endmethod

    def increase_score(self, val):
        self.score += val
    #Endmethod

    def decrease_bcount(self):
        if self.bullet_count > 0:
            self.bullet_count -= 1
        #Endif
    #Endmethod

#Endclass

class Invader(pygame.sprite.Sprite):
    # Define the constructor for Invader
    def __init__(self, color, width, height, speed, enemy):

        #Why can i not have xpos atribute that holds self.rect.x and change it when i call the class?

        # Call the sprite constructor
        super().__init__()
        self.image = pygame.image.load(enemy)
        # Set the position of the sprite
        self.height = height
        self.width = width
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(0, 600)
        self.rect.y = random.randrange(-self.height, (-150 - self.height), -1)
        self.speed = speed

    def update(self):
        self.rect.y = self.rect.y + self.speed
        if self.rect.y >= size[1]:
            invader_group.remove(self)
        #Endif
    #Endmethod

    def centralise(self):
        while self.rect.x > 0:
            self.rect.x -= 1
        #Endwhile
    #Endmethod

#Endclass

class Bullet(pygame.sprite.Sprite):
    # Define the constructor for Bullet
    def __init__(self, color, width, height):

        # Call the sprite constructor
        super().__init__()
        self.width = width
        self.height = height
        self.image = pygame.Surface([width,height])
        self.image.fill(color)
        # Set the position of the sprite
        self.rect = self.image.get_rect()
        self.rect.x = my_player.rect.x + (0.5 * my_player.width)
        self.rect.y = my_player.rect.y
        self.speed = 3

    def update(self):
        self.rect.y = self.rect.y - self.speed
        if self.rect.y < 0:
            bullet_group.remove(self)
        #Endif
    #Endmethod

#Endclass

# -- Exit game flag set to false
done = False

# Create a sprite group of the invaders
invader_group = pygame.sprite.Group()
# Create a sprite group of the bullets
bullet_group = pygame.sprite.Group()
# Create a sprite group of all sprites
all_sprites_group = pygame.sprite.Group()

# Create the Objects

number_of_invaders = 10
for count in range (number_of_invaders):
    my_invader = Invader(BLUE, 30, 30, 1, "enemy.jpg") # Invaders are blue with size 30 x 30 px
    invader_group.add(my_invader) # Adds the new invader to the group of invaders
    all_sprites_group.add(my_invader) # Adds it to the group of all Sprites
#Next count

my_invader2 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader3 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader4 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader5 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader6 = Invader(BLUE, 30, 30, 0, "enemy.jpg")

my_player = Player(YELLOW, 15, 15, 5, 0, 200)
all_sprites_group.add(my_player) # Adds it to the group of all Sprites

# -- Manages how fast screen refreshes
clock = pygame.time.Clock()

### -- Game Loop
while not done and my_player.lives > 0:

    # -- User inputs here
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN: # - A key is down
            if event.key == pygame.K_LEFT: # - If the left key pressed
                my_player.player_set_speed(-4) # - Speed set to -4
            elif event.key == pygame.K_RIGHT: # - If the right key pressed
                my_player.player_set_speed(4) # - Speed set to 4
            elif event.key == pygame.K_UP: # - If up key is pressed, Alex's github opens
               #webbrowser.open_new_tab('https://github.com/alex-silcock/silcockaw-Y12-Computer-Science/commit/e7228fab2c1dd2e32832b558ee0dd0479c6049ba')
                pass
            elif event.key == pygame.K_SPACE: # - If space key is pressed
                if my_player.bullet_count > 0:
                    my_bullet = Bullet(RED, 2, 2) # - Bullet is created
                    bullet_group.add(my_bullet) # - Bullet is added to bullet_group
                    my_player.decrease_bcount() # - Bullet count decreases
                    all_sprites_group.add(my_bullet) # - Adds bullets to all sprites group
                #Endif
        elif event.type == pygame.KEYUP: # - A key released
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                my_player.player_set_speed(0) # Speed set to 0
                #Endif
            #Endif
        #Endif
    #Nextevent

    # -- Game logic goes after this comment
    if my_invader.rect.y == size[1] + 150:
        print("round2")
        number_of_invaders = 30
        for count in range (number_of_invaders):
            my_invader2 = Invader(BLUE, 30, 30, 1, "enemy.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader2) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader2) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader2.rect.y == size[1] + 150:
        print("round3")
        number_of_invaders = 10
        for count in range (number_of_invaders):
            my_invader3 = Invader(BLUE, 50, 50, 2, "enemy.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader3) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader3) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader3.rect.y == size[1] + 150 or my_invader3.rect.y == size[1] + 151:
        print("round3")
        number_of_invaders = 10
        for count in range (number_of_invaders):
            my_invader4 = Invader(BLUE, 45, 60, 1, "fiona.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader4) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader4) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader4.rect.y == size[1] + 150:
        print("round4")
        number_of_invaders = 10
        for count in range (number_of_invaders):
            my_invader5 = Invader(BLUE, 56, 75, 2, "Spence.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader5) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader5) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader5.rect.y == size[1] + 150 or my_invader5.rect.y == size[1] + 151:
        print("round5")
        pleasework = True
        number_of_invaders = 1
        for count in range (number_of_invaders):
            clock.tick(1)
            my_invader6 = Invader(BLUE, 636, 478, 1, "piano.jpeg") # Invaders are blue with size 30 x 30 px
            my_invader6.centralise()
            invader_group.add(my_invader6) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader6) # Adds it to the group of all Sprites
        #Next count
    #Endif

    # -- When invader hits the player add 5 to score.
    player_hit_group = pygame.sprite.spritecollide(my_player, invader_group, True)
    for p in player_hit_group: #how does this work!?
        my_player.lives = my_player.lives - 1
    #nextp
    for b in bullet_group:
        invader_hit_group = pygame.sprite.spritecollide(b, invader_group, True)
        #if len(invader_hit_group) >= 2:
        #   invader_destroy_group = pygame.sprite.spritecollide(b, invader_group, True)
        for b in invader_hit_group:
            my_player.increase_score(5)
        #Nextb
    #Nextb

    all_sprites_group.update()

# -- Screen background is BLACK
    screen.fill(BLACK)

# -- Draw here
    all_sprites_group.draw(screen)
    draw_stats(screen, 10, 10, "Lives: %d" % my_player.lives)
    draw_stats(screen, 10, 40, "Score: %d" % my_player.score)
    draw_stats(screen, 10, 70, "Bullets: %d" % my_player.bullet_count)

# -- Flip display to reveal new position of objects
    pygame.display.flip()

# - The clock ticks over
    clock.tick(60)
    if pleasework == True:
        clock.tick(20)
#End While - End of game loop

pygame.quit()

#Shmuck's assemble ... we're shmuck's 1, 2 and 3, i like being me, and i like being free!
#Shmuck's assemble ... this is a little freestyle eee. We're shmuck's 1, 2 and 3, i like being me, and i like being free!


# ### filter
'''
filter(func,iterable)
功能:过滤数据
	 如果函数的返回值是True ,代表保留当前数据
	 如果函数逇返回值是False,代表舍弃当前数据
参数:
	func 自定义函数
	iterable 可迭代对象(常用:容器类型数据,range对象,迭代器)
返回值
	迭代器
'''

listvar = [1,2,3,4,4,56,6,6,7,8,9,10]
# 要所有的偶数,舍弃所有的奇数
def func(n):
	if n % 2 == 0:
		return True
	else:
		return False

it = filter(func,listvar)
res = list(it)
print(res)

# 使用匿名函数进行优化
it = filter(lambda n :True  if n % 2 == 0 else False,listvar)
print(list(it))

L04（下）迭代器、map、reduce、sorted、filter、列表、字典、集合推导式、生成器函数/课件/5.filter.py


from collections import deque, defaultdict

class Graph():
    def __init__(self):
        self.vertices = 0
        self.graph = defaultdict(list)
        self.topoOrder = deque()
        self.cycleExists = False
        self.backEdge = deque()

    def addEdgesfromFile(self, filename):
        with open(filename) as f:
            for line in f:
                templist = []
                templist = line.split(":")
                temp2 = []
                temp2 = line.split()
                temp2 = temp2[1:]
                if len(temp2) == 0:
                    temp2.append(0)
                for i in range(0, len(temp2)):
                    self.graph[int(templist[0])].append(int(temp2[i]))
            f.close()
            self.vertices = len(self.graph)

    def DFS(self):
        color = ["White"] * (self.vertices + 1)
        for i in range(1 , self.vertices + 1):
            if color[i] == "White":
                self.DFSVisit(i, color)
        if self.cycleExists == False:
            self.topoSort()
        elif self.cycleExists == True:
            print("Cycle exists, Back Edges occur at:")
            while(len(self.backEdge) > 0):
                print(self.backEdge.popleft())
    def DFSVisit(self, u, color):
        color[u] = "Gray"
        for v in self.graph[u]:
            if color[v] == "White":
                self.DFSVisit(v, color)
            if color[v] == "Gray":
                self.backEdge.appendleft((u, v))
                self.cycleExists = True
        color[u] = "Black"
        self.topoOrder.appendleft(u)
    def topoSort(self):
        self.topoOrder.remove(0)
        print("Topological Order")
        while(len(self.topoOrder) > 0):
            print(self.topoOrder.popleft())

if __name__ == "__main__":
    filename = input("Enter the name of the graph file, ex. graphin-c1.txt:  ")
    graph = Graph()
    graph.addEdgesfromFile(filename)
    print("Graph Created, Performing DFS Topo Sort")
    graph.DFS()


import cv2
import numpy as np
from object_detection import ObjectDetection
import math

# Initialize Object Detection
od = ObjectDetection()

# count line position
count_line_position = 350
offset = 2
counter = 0

# video location

cap = cv2.VideoCapture("C:/Users/91798/Documents/python/openCV/source_code/VID-20230418-WA0011.mp4")

# Initialize count
count = 0
center_points_prev_frame = []

tracking_objects = {}
track_id = 0
red_car_id = set([])

while True:
    ret, frame = cap.read()
    count += 1
    if not ret:
        break

    # Point current frame
    center_points_cur_frame = []
    center_points_red_frame = []
    #red_car_id = []
    #y = []
    # Detect objects on frame
    (class_ids, scores, boxes) = od.detect(frame)

    # Drawing  a line
    cv2.line(frame,(13,count_line_position),(445,count_line_position),(255,127,0),2)

    for box in boxes:
        (x, y, w, h) = box
        cx = int((x + x + w) / 2)
        cy = int((y + y + h) / 2)
        center_points_cur_frame.append((cx, cy))
        #print("FRAME N°", count, " ", x, y, w, h)
        # cv2.circle(frame, (cx, cy), 5, (0, 0, 255), -1)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # Get the HSV color of each pixel within the rectangle
        hsv_roi = cv2.cvtColor(frame[y:y+h, x:x+w], cv2.COLOR_BGR2HSV)
        # Set the range of color to detect (in this case, red)
        lower_red = np.array([0,70,50])
        upper_red = np.array([10,255,255])
        mask1 = cv2.inRange(hsv_roi, lower_red, upper_red)

        lower_red = np.array([170,70,50])
        upper_red = np.array([180,255,255])
        mask2 = cv2.inRange(hsv_roi, lower_red, upper_red)

        # Combine the masks to get the final mask for the red color
        mask = mask1 + mask2

        # Count the number of non-zero pixels in the mask within the rectangle
        masked_pixels = cv2.countNonZero(mask)
        total_pixels = w*h
        pixel_ratio = masked_pixels/float(total_pixels)

        if pixel_ratio > 0.05:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
            if ((cx,cy)) not in center_points_red_frame:
                if y<(count_line_position+offset) and y>(count_line_position-offset):
                    center_points_red_frame.append((cx,cy))
                    counter += 1
                    cv2.line(frame,(13, count_line_position), (445, count_line_position), (0,127,255), 3)
                    #center_points_cur_frame.remove((x,y))

                    #print('tracking id is :',track_id)
                    red_car_id.add(track_id)

                    print(red_car_id)
                    print("Red Vehicle is detected : "+str(len(red_car_id)))

    # Only at the beginning we compare previous and current frame
    if count <= 2:
        for pt in center_points_cur_frame:
            for pt2 in center_points_prev_frame:
                distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])

                if distance < 20:
                    tracking_objects[track_id] = pt
                    track_id += 1
    else:

        tracking_objects_copy = tracking_objects.copy()
        center_points_cur_frame_copy = center_points_cur_frame.copy()
        #red_car_id_copy = red_car_id.copy()

        for object_id, pt2 in tracking_objects_copy.items():
            object_exists = False
            for pt in center_points_cur_frame_copy:
                distance = math.hypot(pt2[0] - pt[0], pt2[1] - pt[1])

                # Update IDs position
                if distance < 20:
                    tracking_objects[object_id] = pt
                    object_exists = True
                    if pt in center_points_cur_frame:
                        center_points_cur_frame.remove(pt)
                    continue

            # Remove IDs lost
            if not object_exists:
                tracking_objects.pop(object_id)

        # Add new IDs found
        for pt in center_points_cur_frame:
            tracking_objects[track_id] = pt
            track_id += 1

    for object_id, pt in tracking_objects.items():
        cv2.circle(frame, pt, 5, (0, 0, 255), -1)
        cv2.putText(frame, str(object_id), (pt[0], pt[1] - 7), 0, 1, (0, 0, 255), 2)

    # print("Tracking objects")
    # print(tracking_objects)

    # print("CUR FRAME LEFT PTS")
    # print(center_points_cur_frame)

    cv2.putText(frame, " Red Vehicle Count : "+str(len(red_car_id)), (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),5)

    cv2.imshow("Original video", frame)

    # Make a copy of the points
    center_points_prev_frame = center_points_cur_frame.copy()

    key = cv2.waitKey(1)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()


### Module imports ###
import math

import torch
from torch import nn
from torchsummary import summary

### Global Variables ###

### Class declarations ###
class SRResNet(nn.Module):

    def __init__(self, scale_factor, num_residual=5):
        upsample_block_num = int(math.log(scale_factor, 2))

        super(SRResNet, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1),
            nn.PReLU()
        )
        residual = [ResidualBlock(64) for _ in range(num_residual)]
        self.residual = nn.Sequential(*residual)
        self.conv2 = nn.Sequential(
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64)
        )
        upsample = [UpsampleBLock(64, 2) for _ in range(upsample_block_num)]
        upsample.append(nn.Conv2d(64, 3, kernel_size=9, padding=4))
        self.upsample = nn.Sequential(*upsample)

    def forward(self, x):
        conv1 = self.conv1(x)
        residual = self.residual(conv1)
        conv2 = self.conv2(residual)
        upsample = self.upsample(conv1 + conv2)
        return (torch.tanh(upsample) + 1) / 2

class ResidualBlock(nn.Module):

    def __init__(self, channels):
        super(ResidualBlock, self).__init__()
        self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.bn1 = nn.BatchNorm2d(channels)
        self.prelu = nn.PReLU()
        self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm2d(channels)

    def forward(self, x):
        residual = self.conv1(x)
        residual = self.bn1(residual)
        residual = self.prelu(residual)
        residual = self.conv2(residual)
        residual = self.bn2(residual)
        return x + residual

class UpsampleBLock(nn.Module):

    def __init__(self, in_channels, up_scale):
        super(UpsampleBLock, self).__init__()
        self.conv = nn.Conv2d(in_channels, in_channels * up_scale ** 2, kernel_size=3, padding=1)
        self.pixel_shuffle = nn.PixelShuffle(up_scale)
        self.prelu = nn.PReLU()

    def forward(self, x):
        x = self.conv(x)
        x = self.pixel_shuffle(x)
        x = self.prelu(x)
        return x

### Function declarations ###
if __name__ == '__main__':
    model = SRResNet(4, 5).cuda()
    summary(model, (3, 22, 22))


import sys, heapq

sys.setrecursionlimit(100000000)

input = sys.stdin.readline

n, m = map(int, input().split())

bridge = [dict() for _ in range(n+1)]
for _ in range(m):
    a, b, c = map(int, input().split())
    if b in bridge[a]:
        if bridge[a][b] < c:
            bridge[a][b] = c
            bridge[b][a] = c
    else:
        bridge[a][b] = c
        bridge[b][a] = c

start, end = map(int, input().split())
visit = [0]*(n+1)

que = []

heapq.heappush(que, (-1000000000, start))

while que:

    cost, idx = heapq.heappop(que)

    if visit[idx]: continue
    visit[idx] = 1

    if idx==end:
        break

    for i, c in bridge[idx].items():
        heapq.heappush(que, (max(cost, -c), i))

print(-cost)


import torch.nn as nn
from torch.nn.utils import spectral_norm
from torch.nn.functional import pad
import torch

class DnCNN(nn.Module):
    def __init__(self, dimension, depth=13, n_channels=64, i_nc=1, o_nc=1, kernel_size=3, is_batch_normalize=False, is_residual=True):

        self.is_residual = is_residual

        if dimension == 2:
            conv_fn = nn.Conv2d
            bn_fn = nn.BatchNorm2d

        elif dimension == 3:
            conv_fn = nn.Conv3d
            bn_fn = nn.BatchNorm3d

        else:
            raise ValueError()

        super().__init__()
        padding = kernel_size // 2

        layers = [
            spectral_norm(conv_fn(
                in_channels=i_nc,
                out_channels=n_channels,
                kernel_size=kernel_size,
                padding=padding,
                bias=False)),
            nn.ReLU(inplace=True)
        ]

        for _ in range(depth - 1):
            layers.append(spectral_norm(conv_fn(
                in_channels=n_channels,
                out_channels=n_channels,
                kernel_size=kernel_size,
                padding=padding,
                bias=False if is_batch_normalize else True)))

            if is_batch_normalize:
                layers.append(bn_fn(n_channels))

            layers.append(nn.ReLU(inplace=True))

        layers.append(
            spectral_norm(conv_fn(
                in_channels=n_channels,
                out_channels=o_nc,
                kernel_size=kernel_size,
                padding=padding,
                bias=False)))

        self.net = nn.Sequential(*layers)

    def forward(self, x):

        input_ = x

        x = self.net(x)

        ret = input_ - x if self.is_residual else x

        return ret

activation_fn = {
    'relu': lambda: nn.ReLU(inplace=True),
    'lrelu': lambda: nn.LeakyReLU(inplace=True),
    'prelu': lambda: nn.PReLU()
}

class ConvBnActivation(nn.Module):
    def __init__(self, in_channels, out_channels, dimension=2, times=1, is_bn=False, activation='relu', kernel_size=3, is_spe_norm=False):
        super().__init__()

        if dimension == 3:
            conv_fn = lambda in_c: torch.nn.Conv3d(in_channels=in_c,
                                                   out_channels=out_channels,
                                                   kernel_size=kernel_size,
                                                   padding=kernel_size // 2
                                                   )
            bn_fn = lambda: torch.nn.BatchNorm3d(out_channels)

        elif dimension == 2:
            conv_fn = lambda in_c: torch.nn.Conv2d(in_channels=in_c,
                                                   out_channels=out_channels,
                                                   kernel_size=kernel_size,
                                                   padding=kernel_size // 2
                                                   )
            bn_fn = lambda: torch.nn.BatchNorm2d(out_channels)
        else:
            raise ValueError()

        layers = []
        for i in range(times):
            if i == 0:
                layers.append(spectral_norm(conv_fn(in_channels)) if is_spe_norm else conv_fn(in_channels))
            else:
                layers.append(spectral_norm(conv_fn(out_channels)) if is_spe_norm else conv_fn(out_channels))

            if is_bn:
                layers.append(bn_fn())

            if activation is not None:
                layers.append(activation_fn[activation]())

        self.net = nn.Sequential(*layers)

    def forward(self, x):
        return self.net(x)

class ConvtranBnActivation(nn.Module):
    def __init__(self, in_channels, out_channels, dimension=2, is_bn=False, activation='relu', kernel_size=3, is_spe_norm=False):
        self.is_bn = is_bn
        super().__init__()
        if dimension == 3:
            conv_fn = lambda: torch.nn.ConvTranspose3d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=kernel_size,
                stride=(1, 2, 2),
                padding=kernel_size // 2,
                output_padding=(0, 1, 1)
            )
            bn_fn = lambda: torch.nn.BatchNorm3d(out_channels)

        elif dimension == 2:
            conv_fn = lambda: torch.nn.ConvTranspose2d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=kernel_size,
                stride=2,
                padding=kernel_size // 2,
                output_padding=1
            )
            bn_fn = lambda: torch.nn.BatchNorm2d(out_channels)
        else:
            raise ValueError()

        self.net1 = spectral_norm(conv_fn()) if is_spe_norm else conv_fn()
        if self.is_bn:
            self.net2 = bn_fn()
        self.net3 = activation_fn[activation]()

    def forward(self, x):
        ret = self.net1(x)
        if self.is_bn:
            ret = self.net2(ret)

        ret = self.net3(ret)

        return ret

class UNet(nn.Module):
    def __init__(self, dimension, i_nc=1, o_nc=1, f_root=32, conv_times=3, is_bn=False, activation='relu',
                 is_residual=False, up_down_times=3, is_spe_norm=False, padding=(1, 4)):

        self.is_residual = is_residual
        self.up_down_time = up_down_times
        self.dimension = dimension
        self.padding = padding

        super().__init__()

        if dimension == 2:
            self.down_sample = nn.MaxPool2d((2, 2))
        elif dimension == 3:
            self.down_sample = nn.MaxPool3d((1, 2, 2))
        else:
            raise ValueError()

        self.conv_in = ConvBnActivation(
            in_channels=i_nc,
            out_channels=f_root,
            is_bn=is_bn,
            activation=activation,
            dimension=dimension,
            is_spe_norm=is_spe_norm
        )

        self.conv_out = ConvBnActivation(
            in_channels=f_root,
            out_channels=o_nc,
            kernel_size=1,
            dimension=dimension,
            times=1,
            is_bn=False,
            activation=None,
            is_spe_norm=is_spe_norm
        )

        self.bottom = ConvBnActivation(
            in_channels=f_root * (2 ** (up_down_times - 1)),
            out_channels=f_root * (2 ** up_down_times),
            times=conv_times, is_bn=is_bn, activation=activation, dimension=dimension,
            is_spe_norm=is_spe_norm
        )

        self.down_list = nn.ModuleList([
                                           ConvBnActivation(
                                               in_channels=f_root * 1,
                                               out_channels=f_root * 1,
                                               times=conv_times, is_bn=is_bn, activation=activation,
                                               dimension=dimension,
                                               is_spe_norm=is_spe_norm
                                           )
                                       ] + [
                                           ConvBnActivation(
                                               in_channels=f_root * (2 ** i),
                                               out_channels=f_root * (2 ** (i + 1)),
                                               times=conv_times, is_bn=is_bn, activation=activation,
                                               dimension=dimension,
                                               is_spe_norm=is_spe_norm
                                            )
                                           for i in range(up_down_times - 1)
                                       ])

        self.up_conv_list = nn.ModuleList([
            ConvBnActivation(
                in_channels=f_root * (2 ** (up_down_times - i)),
                out_channels=f_root * (2 ** (up_down_times - i - 1)),
                times=conv_times, is_bn=is_bn, activation=activation, dimension=dimension,
                is_spe_norm=is_spe_norm
            )
            for i in range(up_down_times)
        ])

        self.up_conv_tran_list = nn.ModuleList([
            ConvtranBnActivation(
                in_channels=f_root * (2 ** (up_down_times - i)),
                out_channels=f_root * (2 ** (up_down_times - i - 1)),
                is_bn=is_bn, activation=activation, dimension=dimension,
                is_spe_norm=is_spe_norm
            )
            for i in range(up_down_times)
        ])

    def forward(self, x):

        input_ = x

        x = pad(x, [0, self.padding[0], 0, self.padding[1]])

        x = self.conv_in(x)

        skip_layers = []
        for i in range(self.up_down_time):
            x = self.down_list[i](x)

            skip_layers.append(x)
            x = self.down_sample(x)

        x = self.bottom(x)

        for i in range(self.up_down_time):
            x = self.up_conv_tran_list[i](x)
            x = torch.cat([x, skip_layers[self.up_down_time - i - 1]], 1)
            x = self.up_conv_list[i](x)

        x = self.conv_out(x)

        if self.padding[0] > 0:
            x = x[..., :-self.padding[0]]
        if self.padding[1] > 0:
            x = x[..., :-self.padding[1], :]

        # x = x[..., :-self.padding[1], :-self.padding[0]]

        ret = input_ - x if self.is_residual else x

        return ret


class Solution:
    def twoSum(self, nums, target):
        '''
          hashmapを使ったバージョン
        '''
        # 入力配列の長さ
        length = len(nums)

        # {value: index} のマッピングテーブルを作成
        table = dict()
        for i, v in enumerate(nums):
            table[v] = i

        for j in range(length):
            # 探している値がテーブルにあるかをチェック
            if target - nums[j] in table and j != table[target - nums[j]]:
                return [j, table[target - nums[j]]]

if __name__ == '__main__':
    solution = Solution()
    nums = [2,7,11,15]
    target = 9
    print(solution.twoSum(nums, target))


#!/usr/bin/python3
# shakewebpy.py - Program to serach shakespeare
# James Skon, 2021

import cgi
import cgitb
cgitb.enable()
fileName="/var/www/html/shakewebpy/shakespeare.txt"

def removePunctuation(s):
  "Remove all punctuation from a string"
  import string
  for c in string.punctuation:
    s= s.replace(c,"")
  return s

def addToIndex(index,word,line):
  if word not in index:
    index[word]=[line] # make new entry
  else:
    index[word].append(line)

class textindex:

  def __init__(self,filename):
    "Create a dictionary of all words, with the key being the word, and the value being the number of times the word is found"
    self.index={}
    inFile = open(filename,"r")
    pos=0
    line=inFile.readline()
    while len(line)>0:
      line=line.strip().lower()
      line=removePunctuation(line.lower())
      words=line.split()
      for word in words:
        addToIndex(self.index,word,pos)
      pos=inFile.tell()  # Next line position
      line=inFile.readline()
    return

  def wordcount(self):
    return len(self.index)

  def lookup(self,word):
    word=word.lower()
    if word in self.index:
      lines=self.index[word]
      return lines
    else:
      return []

def print_header():
    print ("Content-type:text/html\n\n")

def lookupWords(index,filename,searchTerm):
  "Allow user to lookup word matches"
  lines = []
  positions=index.lookup(searchTerm)

  if len(positions)>0:
    textfile=open(filename,"r")
    for pos in positions:
      textfile.seek(pos,0)
      line=textfile.readline()
      lines.append(line+'<br />')
  else:
    lines.append(searchTerm+" not found,")
  return lines

def main():
  print_header()

  sIndex=textindex(fileName)

  form = cgi.FieldStorage()
  if (form.getvalue("word")):
    word=form.getvalue("word").upper()
    lines=lookupWords(sIndex,fileName,word)

    for line in lines:
      print(line)
  else:
    print("Error in submission")

main()


import sys
input = sys.stdin.readline

def solve():
    n = int(input())
    arr = list(map(int, input().split()))

    # 벌통을 왼쪽에
    dp1 = [0] * len(arr)
    dp1[0] = arr[0]

    for i in range(1, len(arr)):
        dp1[i] = dp1[i - 1] + arr[i]

    ans = 2 * dp1[len(dp1) - 3]

    for i in range(len(arr) - 3, -1, -1):
        if i - 1 >= 0:
            tmp = dp1[len(dp1) - 2] - (dp1[i] - dp1[i - 1]) + dp1[i - 1]
            ans = max(ans, tmp)

    # 벌통을 오른쪽에
    dp2 = [0] * len(arr)
    dp2[-1] = arr[-1]

    for i in range(len(arr) - 2, -1, -1):
        dp2[i] = dp2[i + 1] + arr[i]

    ans = max(ans, 2 * dp2[2])

    for i in range(2, len(arr)):
        if i + 1 < len(arr):
            tmp = dp2[1] - (dp2[i] - dp2[i + 1]) + dp2[i + 1]
            ans = max(ans, tmp)

    # 벌통을 가운데
    if n % 2 != 0:
        point = n // 2
        tmp = sum(arr[1:point + 1]) + sum(arr[point: len(arr) - 1])

        ans = max(ans, tmp)
    else:
        point = n // 2

        tmp = sum(arr[1:point + 1]) + sum(arr[point: len(arr) - 1])

        ans = max(ans, tmp)

        point = n // 2 - 1

        tmp = sum(arr[1:point + 1]) + sum(arr[point: len(arr) - 1])

        ans = max(ans, tmp)

    print(ans)

solve()


import sys
sys.stdin = open('input.txt', 'r')

def bfs(i, j):
    # v[i][j] = 0
    q = [(i,j)]
    while q:
        ci, cj = q.pop(0)
        for di, dj in (1,0),(-1,0),(0,1),(0,-1):
            ni, nj = ci+di, cj+dj
            if 0<=ni<N and 0<=nj<N and v[ni][nj] > v[ci][cj] + arr[ni][nj]:
                v[ni][nj] = v[ci][cj] + arr[ni][nj]
                q.append((ni,nj))

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    arr = [list(map(int,input())) for _ in range(N)]
    v = [[100000]*N for _ in range(N)]
    v[0][0] = 0
    bfs(0,0)
    ans = v[-1][-1]
    print(f'#{tc} {ans}')


import sys
input = sys.stdin.readline

T = int(input())

for _ in range(T):
    M, N, x, y = map(int, input().strip().split())

    if x <= N:
        start = x
    else:
        start = x - N

    visit = []
    # 답을 N으로 나눈 나머지가 y
    while y not in visit:
        if start not in visit:
            visit.append(start)
            start = start + (M-N)
            if start > N:
                start = start - N
            elif start <= 0:
                start = N + start
        else:
            break

    # print(visit)
    flag = -1
    for i in range(len(visit)):
        if visit[i] == y:
            flag = i
    if flag == -1:
        print(-1)
    else:
        print(x + M * flag)


import os
from flask import Flask, make_response, jsonify, request
from flask.ext.cors import CORS
import pymongo
from pymongo import MongoClient
from bson.json_util import dumps
from bson.objectid import ObjectId
from os.path import join, dirname
from dotenv import load_dotenv
from flask.ext.socketio import SocketIO, emit, send
import ast
import datetime

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

app = Flask(__name__, instance_path='/Users/Linehan/desktop/workspace/capstone/project/instance')
CORS(app, resources={r'/*' : {"origins": "*"}}, allow_headers='Content-Type')
socketio = SocketIO(app)

MONGO_URL = os.environ.get("MONGOLAB_URI")
DB_NAME = os.environ.get("DB_NAME")
if not MONGO_URL:
    MONGO_URL = "mongodb://localhost:27017/capstone"

client = MongoClient(MONGO_URL)
db = client[DB_NAME]
events_collection = db['events']

@app.route('/events')
def get_events():
    return dumps(events_collection.find())

@app.route('/create_event', methods=['POST'])
def create_event():
    form_data = ast.literal_eval((request.data).decode())
    venue_city = form_data["venueCity"]
    venue_name = form_data["venueName"]
    venue_state = form_data["venueState"]
    event_name = form_data["eventName"]
    db.events.insert_one(
        {
        "date": "11/13/2015",
        "venue": {
            "city": venue_city,
            "state": venue_state,
            "name": venue_name
            },
        "name": event_name,
        "posts": []
        }
    )

@app.route('/create_post', methods=["POST"])
def create_post():
    form_data = ast.literal_eval((request.data).decode())
    # print(form_data)
    venue_id = form_data["id"]
    post_body = form_data["body"]
    post_name = form_data["name"]
    post_date = datetime.datetime.utcnow()

    if "image" in form_data:
        post_image = form_data["image"]
        db.events.update(
            { "_id": ObjectId(venue_id)},
            { "$push":
                { "posts": {
                    "body": post_body,
                    "image": post_image,
                    "time": post_date,
                    "name": post_name
                    }
                }
        })
    else:
        db.events.update(
            { "_id": ObjectId(venue_id)},
            { "$push":
                { "posts": {
                    "body": post_body,
                    "time": post_date,
                    "name": post_name
                    }
                }
        })

    print("OKAY")
    return "OK"

# ******
# @socketio.on('message', namespace="/test")
# def test_message(message):
#     print(message)
    # socketio.emit('newPostEvent', {'newPost': {
    #             "event_id": ObjectId(venue_id),
    #              "post": {
    #                     "body": post_body,
    #                     "time": post_date,
    #                     "user_name": post_name
    #                     }
    #                 } }, namespace='/test')

# @socketio.on('connect', namespace="/test")
# def test_connect():
#     print("Connected!!!")
#     emit('sendPost', {'data': 'hello world'})
#     emit('test_event', {'data': 'Connected'})

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


from vpython import sphere, scene, vector, rate, color, arrow
from numpy import sin, cos, pi

arrow_x = arrow(pos=vector(0,0,0), axis=vector(0.5,0,0), color=color.red)
arrow_y = arrow(pos=vector(0,0,0), axis=vector(0,0.5,0), color=color.green)
arrow_z = arrow(pos=vector(0,0,0), axis=vector(0,0,0.5))

R = 0.1 # m
xp = 0. # m
yp = 1. # m
zp = 0. # m

grv = 9.8 # m/s^2

th = 30.*(pi/180.)

scene.range = 2.*yp # m

prtcl = sphere(pos=vector(xp,yp,zp), radius=R, color=color.cyan)

ax = grv*sin(th)*cos(th)
ay = grv*(cos(th) - 1)
dt = 0.005
prtcl.velocity = vector(ax, ay, 0)

t = 0

while t < 3:
    rate(100)
    prtcl.pos = prtcl.pos + prtcl.velocity*dt
    t += dt


# PARÂMETROS

# - Nomes dados aos atributos que uma função pode receber, definem quais são os argumentos aceitos por uma função, podendo ou não ter um valor padrão.

# Ex:

def calcula_salario(valor, horas=220):
      return valor * horas

print(calcula_salario(35))

# *args

# - São apenas usados por convenção
# - *args é usado para passar uma lista de argumentos variável sem palavras chave em forma de tupla,
#    pois a função que recebe não necessariamente saberá quantos argumentos serão passados.
# Ex:

def foo(*args):
      print(f'conteudo: {args}')

      for i in args:
            print(i)

foo('Hello', 'Moças', 'LuizaCode')

# **kwargs
# - É a abreviação de keyword arguments, ele permite passar um dicionário com inúmeras chaves para a função
#   Isso deixa definido que tal função irá receber tais valores.
# Ex:

def fooo(**kwargs):
      print(f'O nome dela(e) é: {kwargs.get("nome")}')

fooo(nome='Jhon',
    idade='28',
    pais='Brasil')

# DECORATOR
# - Usando o decorator, conseguimos adicionar qualquer comportamento antes e depois da execução de uma função qualquer

#LAMBDA

# sintaxe: lambda argument(s): expression
# - Boa para operações lógicas simples e funções que serão usadas apenas uma vez
# - Só podem executar uma única expressão, não pode ter mais que uma linha
# Ex:

lista = [1,2,3,4,5,6,7,8,9]
print(list(filter(lambda x: x%2==0, lista)))


#20PW14.Framing.client.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 65456
s.connect((host,port))

def bytestuff(l):
    if 'ESC' in l:
        l=l.replace("ESC", "ESC ESC")
    if 'FLAG' in l:
        l=l.replace("FLAG", "ESC FLAG")
    return l

def byteEncode(l):
    eightBitArr = []
    for i in l.split():
        if i == 'FLAG':
            eightBitArr.append('01111110')
        elif i == 'ESC':
            eightBitArr.append('10100011')
        else:
            eightBitArr.append(format(ord(i), '08b'))
    eightBitArr = " ".join(eightBitArr)
    return eightBitArr

def bitStuff(l):
    if '011111' in l:
        l=l.replace('011111', '0111110')
    return l

def framing(l):
    frames = []
    for i in l.split():
        frames.append("01111110"+i+"01111110")
    frames = ''.join(frames)
    return frames

#Input the message
msg = input(">>> ")
print("Message = ", msg)
msg = bytestuff(msg)
# print("ByteStuffedMsg = ", msg)
msg = byteEncode(msg)
# print("ByteEncodedMsg = ", msg)
msg = bitStuff(msg)
# print("BitStuffedMsg = ", msg)
msg = framing(msg)
# print("FramedMsg = ", msg)

#Sending the message
print("Sending message...")
s.send(msg.encode())

s.close()

Sem4/20XW46 - Computer Networks and TCP-IP Lab/PS7 - Framing/client.py


import numpy as np
import pygame
import random

pygame.init() #where the pygame grid starts

width, height = 820, 820 #following 3 lines control the width and height of the pygame window and the name of the window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("SPLOOSH KABOOM")

BLUE = (43, 101, 236) #these three colors are used to generate colors within the 20x20 grid
RED = (255, 0, 0)
GREEN = (0, 255, 0)

grid_size = 20 #controls grid size
tile_size = 40
grid_padding = 10

grid = np.zeros((grid_size, grid_size), dtype=int)

ship_sizes = [4, 4, 4, 3, 3, 2] #list of the amount of ships plus their varying sizes (three 4 tile ships, two three tile ships, and one 2 tile ship)

for size in ship_sizes:
    valid = False
    while not valid:
        x = random.randint(0, grid_size - 1)
        y = random.randint(0, grid_size - 1) #chooses a random general area of where a ship can be
        orientation = random.choice(["horizontal", "vertical"]) #randomly decides if the ship will be vertical or horziontal

        if orientation == "horizontal": #aligns ship to be  horziontal
            if y + size <= grid_size and np.count_nonzero(grid[x, y:y + size]) == 0:
                grid[x, y:y + size] = 1
                valid = True
        else: #aligns ship to be vertical
            if x + size <= grid_size and np.count_nonzero(grid[x:x + size, y]) == 0:
                grid[x:x + size, y] = 1
                valid = True

hit_count = 0
ships_sunk = 0
totalclicks = 0  #these three variables track variables that will change throughout the loop
font = pygame.font.Font(None, 36)

running = True #as long as running is true the code will run
print("hey welcome to SPLOOSH KABOOM your goal is to find all 6 ships and sink them ")
while running: #code is in a while true loop until win condition is met
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and ships_sunk < 6:
            if pygame.mouse.get_pressed()[0]: #code registers player's click and finds the row and col where the player clicked
                pos = pygame.mouse.get_pos()
                col = (pos[0] - grid_padding) // tile_size
                row = (pos[1] - grid_padding) // tile_size
                try:
                    if grid[row][col] == 1: #using the value of row and col where the player click if it equals to 1 that means the player hit a ship
                        hit_count += 1
                        grid[row][col] = -1
                        totalclicks += 1
                        print("KABOOM!")
                    if hit_count == 20: #when hit count is 20 (the total amount of hits when you add all the ship totals together ) playe meets win condition
                            ships_sunk = 6
                            if ships_sunk == 6:
                                running = False
                                print("Congratulations! You sunk all the ships!")
                                print("it took ya" + str(totalclicks)+ " clicks.")
                    elif grid[row][col] == 0: #when the value of row and grid make a 0 it means the player missed
                        grid[row][col] = -2
                        print("sploosh...")
                        totalclicks += 1
                except: #when player clicks out of bounds usually an error happens but using try and execept makes it so it doesn't break this is a temp solution until i find a way to fix it
                    print("ERROR: Out Of Bounds. That wasn't very splash kaboomy of you")
    screen.fill(BLUE) #makes the default grid all blue

    for row in range(grid_size):
        for col in range(grid_size):
            x = col * tile_size + grid_padding
            y = row * tile_size + grid_padding
            pygame.draw.rect(screen, BLUE, (x, y, tile_size, tile_size), 1)

            if grid[row][col] == -1: #when ship is hit marked with green tile
                pygame.draw.rect(screen, GREEN, (x + 1, y + 1, tile_size - 2, tile_size - 2))
            elif grid[row][col] == -2: #when ship is missed marked with red tile
                pygame.draw.rect(screen, RED, (x + 1, y + 1, tile_size - 2, tile_size - 2))

    pygame.display.flip()

pygame.quit()


import torch
import torch.nn as nn
import torchvision

class HardSwish(nn.Module):
    def __init__(self, inplace=True):
        super(HardSwish, self).__init__()
        self.relu6 = nn.ReLU6(inplace)

    def forward(self, x):
        return x*self.relu6(x+3)/6

def ConvBNActivation(in_channels,out_channels,kernel_size,stride,activate):
    return nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, groups=in_channels),
            nn.BatchNorm2d(out_channels),
            nn.ReLU6(inplace=True) if activate == 'relu' else HardSwish()
        )

def Conv1x1BNActivation(in_channels,out_channels,activate):
    return nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1),
            nn.BatchNorm2d(out_channels),
            nn.ReLU6(inplace=True) if activate == 'relu' else HardSwish()
        )

def Conv1x1BN(in_channels,out_channels):
    return nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1),
            nn.BatchNorm2d(out_channels)
        )

class SqueezeAndExcite(nn.Module):
    def __init__(self, in_channels, out_channels,se_kernel_size, divide=4):
        super(SqueezeAndExcite, self).__init__()
        mid_channels = in_channels // divide
        self.pool = nn.AvgPool2d(kernel_size=se_kernel_size,stride=1)
        self.SEblock = nn.Sequential(
            nn.Linear(in_features=in_channels, out_features=mid_channels),
            nn.ReLU6(inplace=True),
            nn.Linear(in_features=mid_channels, out_features=out_channels),
            HardSwish(inplace=True),
        )

    def forward(self, x):
        b, c, h, w = x.size()
        out = self.pool(x)
        out = out.view(b, -1)
        out = self.SEblock(out)
        out = out.view(b, c, 1, 1)
        return out * x

class SEInvertedBottleneck(nn.Module):
    def __init__(self, in_channels, mid_channels, out_channels, kernel_size, stride,activate, use_se, se_kernel_size=1):
        super(SEInvertedBottleneck, self).__init__()
        self.stride = stride
        self.use_se = use_se
        # mid_channels = (in_channels * expansion_factor)

        self.conv = Conv1x1BNActivation(in_channels, mid_channels,activate)
        self.depth_conv = ConvBNActivation(mid_channels, mid_channels, kernel_size,stride,activate)
        if self.use_se:
            self.SEblock = SqueezeAndExcite(mid_channels, mid_channels, se_kernel_size)

        self.point_conv = Conv1x1BNActivation(mid_channels, out_channels,activate)

        if self.stride == 1:
            self.shortcut = Conv1x1BN(in_channels, out_channels)

    def forward(self, x):
        out = self.depth_conv(self.conv(x))
        if self.use_se:
            out = self.SEblock(out)
        out = self.point_conv(out)
        out = (out + self.shortcut(x)) if self.stride == 1 else out
        return out

class MobileNetV3(nn.Module):
    def __init__(self, num_classes=1000,type='large'):
        super(MobileNetV3, self).__init__()
        self.type = type

        self.first_conv = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1),
            nn.BatchNorm2d(16),
            HardSwish(inplace=True),
        )

        if type=='large':
            self.large_bottleneck = nn.Sequential(
                SEInvertedBottleneck(in_channels=16, mid_channels=16, out_channels=16, kernel_size=3, stride=1,activate='relu', use_se=False),
                SEInvertedBottleneck(in_channels=16, mid_channels=64, out_channels=24, kernel_size=3, stride=2, activate='relu', use_se=False),
                SEInvertedBottleneck(in_channels=24, mid_channels=72, out_channels=24, kernel_size=3, stride=1, activate='relu', use_se=False),
                SEInvertedBottleneck(in_channels=24, mid_channels=72, out_channels=40, kernel_size=5, stride=2,activate='relu', use_se=True, se_kernel_size=28),
                SEInvertedBottleneck(in_channels=40, mid_channels=120, out_channels=40, kernel_size=5, stride=1,activate='relu', use_se=True, se_kernel_size=28),
                SEInvertedBottleneck(in_channels=40, mid_channels=120, out_channels=40, kernel_size=5, stride=1,activate='relu', use_se=True, se_kernel_size=28),
                SEInvertedBottleneck(in_channels=40, mid_channels=240, out_channels=80, kernel_size=3, stride=1,activate='hswish', use_se=False),
                SEInvertedBottleneck(in_channels=80, mid_channels=200, out_channels=80, kernel_size=3, stride=1,activate='hswish', use_se=False),
                SEInvertedBottleneck(in_channels=80, mid_channels=184, out_channels=80, kernel_size=3, stride=2,activate='hswish', use_se=False),
                SEInvertedBottleneck(in_channels=80, mid_channels=184, out_channels=80, kernel_size=3, stride=1,activate='hswish', use_se=False),
                SEInvertedBottleneck(in_channels=80, mid_channels=480, out_channels=112, kernel_size=3, stride=1,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=112, mid_channels=672, out_channels=112, kernel_size=3, stride=1,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=112, mid_channels=672, out_channels=160, kernel_size=5, stride=2,activate='hswish', use_se=True,se_kernel_size=7),
                SEInvertedBottleneck(in_channels=160, mid_channels=960, out_channels=160, kernel_size=5, stride=1,activate='hswish', use_se=True,se_kernel_size=7),
                SEInvertedBottleneck(in_channels=160, mid_channels=960, out_channels=160, kernel_size=5, stride=1,activate='hswish', use_se=True,se_kernel_size=7),
            )

            self.large_last_stage = nn.Sequential(
                nn.Conv2d(in_channels=160, out_channels=960, kernel_size=1, stride=1),
                nn.BatchNorm2d(960),
                HardSwish(inplace=True),
                nn.AvgPool2d(kernel_size=7, stride=1),
                nn.Conv2d(in_channels=960, out_channels=1280, kernel_size=1, stride=1),
                HardSwish(inplace=True),
            )
        else:
            self.small_bottleneck = nn.Sequential(
                SEInvertedBottleneck(in_channels=16, mid_channels=16, out_channels=16, kernel_size=3, stride=2,activate='relu', use_se=True, se_kernel_size=56),
                SEInvertedBottleneck(in_channels=16, mid_channels=72, out_channels=24, kernel_size=3, stride=2,activate='relu', use_se=False),
                SEInvertedBottleneck(in_channels=24, mid_channels=88, out_channels=24, kernel_size=3, stride=1,activate='relu', use_se=False),
                SEInvertedBottleneck(in_channels=24, mid_channels=96, out_channels=40, kernel_size=5, stride=2,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=40, mid_channels=240, out_channels=40, kernel_size=5, stride=1,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=40, mid_channels=240, out_channels=40, kernel_size=5, stride=1,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=40, mid_channels=120, out_channels=48, kernel_size=5, stride=1,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=48, mid_channels=144, out_channels=48, kernel_size=5, stride=1,activate='hswish', use_se=True, se_kernel_size=14),
                SEInvertedBottleneck(in_channels=48, mid_channels=288, out_channels=96, kernel_size=5, stride=2,activate='hswish', use_se=True, se_kernel_size=7),
                SEInvertedBottleneck(in_channels=96, mid_channels=576, out_channels=96, kernel_size=5, stride=1,activate='hswish', use_se=True, se_kernel_size=7),
                SEInvertedBottleneck(in_channels=96, mid_channels=576, out_channels=96, kernel_size=5, stride=1,activate='hswish', use_se=True, se_kernel_size=7),
            )
            self.small_last_stage = nn.Sequential(
                nn.Conv2d(in_channels=96, out_channels=576, kernel_size=1, stride=1),
                nn.BatchNorm2d(576),
                HardSwish(inplace=True),
                nn.AvgPool2d(kernel_size=7, stride=1),
                nn.Conv2d(in_channels=576, out_channels=1280, kernel_size=1, stride=1),
                HardSwish(inplace=True),
            )

        self.classifier = nn.Linear(in_features=1280,out_features=num_classes)

    def init_params(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.Linear):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def forward(self, x):
        x = self.first_conv(x)
        if self.type == 'large':
            x = self.large_bottleneck(x)
            x = self.large_last_stage(x)
        else:
            x = self.small_bottleneck(x)
            x = self.small_last_stage(x)
        x = x.view(x.size(0), -1)
        out = self.classifier(x)
        return out

if __name__ == '__main__':
    model = MobileNetV3(type='small')
    print(model)

    input = torch.randn(1, 3, 224, 224)
    out = model(input)
    print(out.shape)


#cross validating models
#Create a pipeline that preprocesses the data, trains the model, and then evaluates it
#using cross-validation:

#importing libraries
""""
from sklearn import  datasets
from sklearn import  metrics
from sklearn.model_selection import  KFold,cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

#load digit dataset
digits = datasets.load_digits()

#create feature matrix
features = digits.data

#create target vector
target = digits.target

#create Standardizer
standardizer = StandardScaler()

# Create logistic regression object

logistic_model = LogisticRegression()

# Create a pipeline that standardizes, then runs logistic regression

pipeline = make_pipeline(standardizer,logistic_model)

# Create k-Fold cross-validation

kf = KFold(n_splits=10,shuffle=True,random_state=1)

# Conduct k-fold cross-validation
cv_results = cross_val_score(pipeline,
                             features,
                             target,
                             cv=kf,
                             scoring="accuracy",
                             n_jobs=1)
#find the mean result
print(cv_results.mean())
print(cv_results)

#creating a baseline regression model to compare against your model
from sklearn.datasets import load_boston
from sklearn.dummy import DummyRegressor
from sklearn.model_selection import train_test_split

#loading data
boston = load_boston()

#create fetures
features, target = boston.data, boston.target

# Make test and training split
features_train, features_test, target_train, target_test = train_test_split(
 features, target, random_state=0)

#create dummy regressor
dummy = DummyRegressor(strategy= "mean")

#train dummy regressor
dummy.fit(features_train,target_train)

#get R-square score
print(dummy.score(features_test,target_test))

#compare model

from sklearn.linear_model import LinearRegression
ols = LinearRegression()
ols.fit(features_train,target_train)

#get R-scored
print(ols.score(features_test,target_test))
"""

#to evaluate a model using cross entrophy

# Load libraries

"""
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
# Generate features matrix and target vector
X, y = make_classification(n_samples = 10000,
 n_features = 3,
 n_informative = 3,
 n_redundant = 0,
 n_classes = 2,
 random_state = 1)
# Create logistic regression
logit = LogisticRegression()
# Cross-validate model using accuracy
print(cross_val_score(logit, X, y, scoring="accuracy"))

# Cross-validate model using precision
print(cross_val_score(logit, X, y, scoring="precision"))

# Cross-validate model using recall
print(cross_val_score(logit, X, y, scoring="recall"))

# Cross-validate model using f1 this is creating a balance between recall and precision
print(cross_val_score(logit,X,y,scoring = "f1"))
"""

# Load libraries
"""
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, roc_auc_score
from sklearn.model_selection import train_test_split
# Create feature matrix and target vector
features, target = make_classification(n_samples=10000,
 n_features=10,
n_classes=2,
n_informative=3,
random_state=3)
# Split into training and test sets
features_train, features_test, target_train, target_test = train_test_split(
 features, target, test_size=0.1, random_state=1)

# Create classifier
logit = LogisticRegression()
# Train model
logit.fit(features_train, target_train)
# Get predicted probabilities
target_probabilities = logit.predict_proba(features_test)[:,1]
# Create true and false positive rates
false_positive_rate, true_positive_rate, threshold = roc_curve(target_test,
 target_probabilities)
# Plot ROC curve
plt.title("Receiver Operating Characteristic")
plt.plot(false_positive_rate, true_positive_rate)
plt.plot([0, 1], ls="--")
plt.plot([0, 0], [1, 0] , c=".7"), plt.plot([1, 1] , c=".7")
plt.ylabel("True Positive Rate")
plt.xlabel("False Positive Rate")
#plt.show()

# Get predicted probabilities
logit.predict_proba(features_test)[0:1]

print("Threshold:", threshold[116])
print("True Positive Rate:", true_positive_rate[116])
print("False Positive Rate:", false_positive_rate[116])

"""
"""
11.7 Visualizing a Classifier’s Performance
Problem
Given predicted classes and true classes of the test data, you want to visually compare
the model’s quality.
Solution
Use a confusion matrix, which compares predicted classes and true classes:
"""

# Load libraries
"""
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
# Load data
iris = datasets.load_iris()
# Create feature matrix
features = iris.data
# Create target vector
target = iris.target
# Create list of target class names
class_names = iris.target_names
# Create training and test set
features_train, features_test, target_train, target_test = train_test_split(
 features, target, random_state=1)

# Create logistic regression
classifier = LogisticRegression()

# Train model and make predictions
target_predicted = classifier.fit(features_train,
 target_train).predict(features_test)
# Create confusion matrix
matrix = confusion_matrix(target_test, target_predicted)
# Create pandas dataframe
dataframe = pd.DataFrame(matrix, index=class_names, columns=class_names)
# Create heatmap
sns.heatmap(dataframe, annot=True, cbar=None, cmap="Blues")
plt.title("Confusion Matrix"), plt.tight_layout()
plt.ylabel("True Class"), plt.xlabel("Predicted Class")
plt.show()
"""

#to evaluate regression model using mean_square_error

# Load libraries
from sklearn.datasets import make_regression
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
# Generate features matrix, target vector
features, target = make_regression(n_samples = 100,
 n_features = 3,
 n_informative = 3,
 n_targets = 1,
 noise = 50,
 coef = False,
 random_state = 1)

# Create a linear regression object
ols = LinearRegression()

#evaluate model

print(cross_val_score(ols,features,target,scoring = "neg_mean_square_error"))

#NB use mse for linear model and silhouette_score for evaluating how good your model is


import os
from django.urls import (
    path,
)
from .views import (
    ProductList,
    ProductsDetail,
    ProductUpdate,
)

app_name = os.path.basename(os.path.dirname(os.path.abspath(__file__)))

urlpatterns = [
    path('<int:pk>/edit/', ProductUpdate.as_view(), name='ProductUpdate'),
    path('<int:pk>/', ProductsDetail.as_view(), name='ProductsDetail'),
    path('', ProductList.as_view(), name='all'),
]


import json
import math
import os
os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
import os.path as osp
import random
import sys
from glob import glob

import cv2
import h5py
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as LA
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import default_collate
from perception.webcam_sensor import WebcamSensor
from autolab_core import ColorImage, Image, PointCloud, RigidTransform, camera_intrinsics
from phoxipy import PhoXiSensor
from perception.colorized_phoxi_sensor import ColorizedPhoXiSensor

from sym.config import CI, CM

class ShapeNetDataset(Dataset):
    def __init__(self, rootdir, split):
        self.rootdir = rootdir
        self.split = split

        filelist = np.genfromtxt(f"{rootdir}/{split}.txt", dtype=str)
        random.seed(0)
        random.shuffle(filelist)
        filelist = [f for f in filelist if "03636649" not in f]  # remove lamps
        if (
            split == "train"
            and hasattr(CI, "only_car_plane_chair")
            and CI.only_car_plane_chair
        ):
            filelist = [
                f
                for f in filelist
                if "02691156" in f or "02958343" in f or "03001627" in f
            ]
        self.filelist = [f"{rootdir}/{f}" for f in filelist]
        self.filelist2 = filelist
        self.size = len(self.filelist)
        print(f"n{split}:", self.size)

    def __len__(self):
        return self.size

    def __getitem__(self, idx):
        prefix = self.filelist[idx]
        image = cv2.imread(f"{prefix}.png", -1).astype(np.float32)
        # import pdb;pdb.set_trace()
        image = image / 255.0
        # plt.imshow(image)
        # plt.show()
        image = np.rollaxis(image, 2).copy()

        depth = cv2.imread(f"{prefix}_depth0001.exr", -1).astype(np.float32)[:, :, 0:1]

        depth[depth > 20] = 0
        plt.imshow(depth)
        plt.colorbar()
        plt.show()
        depth[depth < 0] = 0
        depth[depth != depth] = 0
        depth = np.rollaxis(depth, 2).copy() # (256, 256, 1) => (1, 256, 256)

        with open(f"{prefix}.json") as f:
            js = json.load(f)
        Rt, K_ = np.array(js["RT"]), np.array(js["K"])
        K = np.eye(4)
        K[:3, :3] = K_[np.ix_([0, 1, 3], [0, 1, 2])]
        # K[:3] *= -1
        # print(Rt, K)
        KRt = K @ Rt

        oprefix = self.filelist2[idx]
        fname = np.zeros([60], dtype="uint8")
        fname[: len(oprefix)] = np.frombuffer(oprefix.encode(), "uint8")

        depth_scale = 1 / abs(Rt[2][3])

        ########### Take depth as input ##################
        depth_noisy = depth.copy()
        depth_noisy += np.random.normal(0, 0.1*abs(Rt[2][3]), depth.shape)
        image_with_depth = np.concatenate((image, depth_noisy), axis=0)
        # plt.imshow(np.rollaxis(image_with_depth, 0, 3)[:, :, :4])
        # plt.show()
        ########### Take depth as input ##################

        S0 = [
            KRt @ np.diagflat([1, -1, 1, 1]) @ LA.inv(KRt),
            KRt @ np.diagflat([-1, 1, 1, 1]) @ LA.inv(KRt),
            KRt @ np.diagflat([-1, -1, 1, 1]) @ LA.inv(KRt),
        ]
        result = {
            "fname": torch.tensor(fname).byte(),
            "image": torch.tensor(image).float(),
            # "image": torch.tensor(image_with_depth).float(),
            "depth": torch.tensor(depth).float() * depth_scale,
            "K": torch.tensor(K).float(),
            "RT": torch.tensor(Rt).float(),
        }

        w0, ws = sample_plane(Rt)
        S = [K @ w2S(w) @ LA.inv(K) for w in ws]
        y = [to_label(w, w0) for w in ws]
        result["S"] = torch.tensor(S).float()
        result["y"] = torch.tensor(y).float()
        result["w"] = torch.tensor(ws).float()
        result["w0"] = torch.tensor(w0).float()

        return result

class Pix3dDataset(Dataset):
    def __init__(self, rootdir, split):
        self.rootdir = rootdir
        self.split = split
        with open(f"{rootdir}/pix3d_info.json", "r") as fin:
            data_lists = json.load(fin)
        data_valid = set(np.loadtxt(f"{rootdir}/pix3d-valid.txt", dtype=str))

        data_lists = [
            d
            for d in data_lists
            if not d["truncated"] and not d["occluded"] and d["img"][:-4] in data_valid
        ]
        random.seed(0)
        random.shuffle(data_lists)
        if self.split == "train":
            data_lists = [data_lists[i] for i in range(len(data_lists)) if i % 10 != 0]
            self.size = len(data_lists) * 2
        elif self.split == "valid":
            data_lists = [data_lists[i] for i in range(len(data_lists)) if i % 10 == 0]
            self.size = len(data_lists)
        else:
            raise NotImplementedError

        self.data_lists = data_lists

        print(f"n{split}:", self.size)

    def __len__(self):
        return self.size

    def __getitem__(self, idx):
        do_flip = False
        if self.split == "train":
            do_flip = idx % 2 == 1
            idx //= 2

        data_item = self.data_lists[idx]
        fimage = osp.join(self.rootdir, data_item["img"])
        fdepth = osp.join(self.rootdir, data_item["depth"])
        fmask = osp.join(self.rootdir, data_item["mask"])

        image = cv2.imread(fimage, -1).astype(np.float32)/255.0
        image = np.rollaxis(image, 2).copy()
        mask = cv2.imread(fmask).astype(np.float32)[None, :, :, 0] / 255.0
        image = np.concatenate([image, mask])
        depth = cv2.imread(fdepth, -1).astype(np.float32)[:, :, 0:1]
        depth[depth > 20] = 0
        depth[depth < 0] = 0
        depth[depth != depth] = 0

        depth = np.rollaxis(depth, 2).copy()
        Rt, K = np.array(data_item["Rt"]), np.array(data_item["K"])
        K[:3] *= -1

        if do_flip:
            K = np.diagflat([-1, 1, 1, 1]) @ K
            image = image[:, :, ::-1].copy()
            depth = depth[:, :, ::-1].copy()

        KRt = K @ Rt
        S0 = [KRt @ np.diagflat([-1, 1, 1, 1]) @ LA.inv(KRt)]

        w0, ws = sample_plane(Rt, np.array([1, 0, 0, 0]))
        S = [K @ w2S(w) @ LA.inv(K) for w in ws]
        y = [to_label(w, w0) for w in ws]
        depth_scale = 1 / (w0 @ Rt[:3, 3])

        # print(S0)
        # print("Rt", Rt)
        # print("S0", Rt @ np.diagflat([-1, 1, 1, 1]) @ LA.inv(Rt))
        # print("S0", w2S(w0))
        # print("w0", w0)
        # print("depth_scale", depth_scale)
        S0 = [K @ w2S(w0) @ LA.inv(K)]
        # print(S0)

        oprefix = data_item["mask"][5:-4]
        fname = np.zeros([60], dtype="uint8")
        fname[: len(oprefix)] = np.frombuffer(oprefix.encode(), "uint8")

        result = {
            "fname": torch.tensor(fname).byte(),
            "image": torch.tensor(image).float(),
            "depth": torch.tensor(depth).float() * depth_scale,
            "S0": torch.tensor(S0).float(),
            "K": torch.tensor(K).float(),
            "RT": torch.tensor(Rt).float(),
        }
        result["S"] = torch.tensor(S).float()
        result["y"] = torch.tensor(y).float()
        result["w"] = torch.tensor(ws).float()
        result["w0"] = torch.tensor(w0).float()

        return result

class RealDataset(Dataset):
    def __init__(self, rootdir, split):
        self.rootdir = rootdir
        self.split = split

        self.camera = PhoXiSensor("1703005")
        self.camera.start()
        self.camera._set_intr()
        filelist = glob(f"{rootdir}/*.npy")
        #Get all the items that have "segmented" in its file name.
        filelist = [s for s in filelist if "segmented" in s]
        print(filelist)
        self.filelist = filelist
        self.size = len(self.filelist)
        print(f"n{split}:", self.size)

    def __len__(self):
        return self.size

    def __getitem__(self, idx):
        prefix = self.filelist[idx]

        # image = cv2.imread(f"{prefix}", -1).astype(np.float32)
        image = np.load(f"{prefix}", allow_pickle=True)
        print("png taken in image shape", image.shape)
        depth = image[:,:,3:]
        image = image[:,:,:3]
        # import pdb;pdb.set_trace()
        # image[:,:,-1] = image[:,:,-1] * 255
        image = cv2.cvtColor(image, cv2.COLOR_RGB2RGBA)
        image[:,:,:3] = image[:,:,:3] / 255.0
        print(image.shape)
        plt.imshow(image)
        plt.show()

        ############# if also feed in depth as input ############
        # image = np.concatenate((image, depth), axis=2)
        # print(image.mean(axis=2))
        #########################################################

        image = np.rollaxis(image, 2).copy()
        print(image.shape)

        # K = np.identity(4)
        # K[:3, :3] = self.camera._camera_intr._K
        # K[0, 2] = 550 + 128
        # K[1, 2] = 280 + 128
        # K[2, 2] = -1
        x_dim = 1032
        y_dim = 772
        clip_x = 190+130
        clip_y = 190
        height = y_dim - 2*clip_y
        width = x_dim - 2*clip_x
        #Row of crop window center
        crop_ci = clip_y + height / 2
        crop_cj = clip_x + width / 2
        # K = np.identity(4)
        # K[:3, :3] = self.camera._camera_intr._K
        # print("K", K)
        # K[0, 2] -= clip_x
        # K[1, 2] -= clip_y
        # K[0] *= 256/(x_dim - 2*clip_x)
        # # K[1] *= 256 / (x_dim - 2 * clip_x)
        # # K[0] *= 256 / (y_dim - 2 * clip_y)
        # # KRt = K @ Rt
        # K[1] *= 256 / (y_dim - 2 * clip_y)
        # K[2,2] = -1
        camera_intrinsics = self.camera.intrinsics
        # print("K before cropping", self.camera.intrinsics._K)
        camera_intrinsics = camera_intrinsics.crop(height, width, crop_ci, crop_cj)
        camera_intrinsics = camera_intrinsics.resize(256 / height)
        K = np.identity(4)
        K[:3, :3] = camera_intrinsics._K
        # K[2,2] = -1
        # K[:3] *= -1
        print("K", K)

        oprefix = self.filelist[idx]
        fname = np.zeros([60], dtype="uint8")
        fname[: len(oprefix)] = np.frombuffer(oprefix.encode(), "uint8")

        # depth_scale = 1 / abs(Rt[2][3])

        result = {
            "fname": torch.tensor(fname).byte(),
            "image": torch.tensor(image).float(),
            "depth": torch.tensor(depth).float(),
            "K": torch.tensor(K).float()
            # "RT": None,
        }
        #
        # w0, ws = sample_plane(Rt)
        # S = [K @ w2S(w) @ LA.inv(K) for w in ws]
        # y = [to_label(w, w0) for w in ws]
        # result["S"] = None
        # result["y"] = None
        # result["w"] = None
        # result["w0"] = None

        return result

def sample_plane(Rt, plane=np.array([0, 1, 0, 0]), plane2=np.array([1, 0, 0, 0])):
    w0_ = LA.inv(Rt).T @ plane
    # find plane normal s.t. w0 @ x + 1 = 0
    w0 = w0_[:3] / w0_[3]
    # normalize so that w[2]=1
    w0 = w0 / w0[2]

    if CM.detection.sample_hard_negative:
        # sample around second symmetry axis (hard negative)
        w1_ = LA.inv(Rt).T @ plane2
        w1 = w1_[:3] / w1_[3]
        w1 = w1 / w1[2]
        ws = [
            sample_symmetry(w0, 0, math.pi / 2),
            sample_symmetry(w1, 0, CM.detection.theta[0]),
        ]
    else:
        while True:
            w = sample_symmetry(w0, 0, math.pi / 2)
            if sum(to_label(w, w0)) == 0:
                break
        ws = [w]
    for theta1, theta0 in zip(CM.detection.theta, CM.detection.theta[1:] + [0]):
        ws.append(sample_symmetry(w0, theta0 * 1.001, theta1 * 0.999))
    return w0, ws

def sample_symmetry(w0, theta0, theta1, delta=1):
    w = sample_sphere(w0 / LA.norm(w0), theta0, theta1)
    return w / (delta * w[2])

def sample_sphere(v, theta0, theta1):
    def orth(v):
        x, y, z = v
        o = np.array([0.0, -z, y] if abs(x) < abs(y) else [-z, 0.0, x])
        o /= LA.norm(o)
        return o

    costheta = random.uniform(math.cos(theta1), math.cos(theta0))
    phi = random.random() * math.pi * 2
    v1 = orth(v)
    v2 = np.cross(v, v1)
    r = math.sqrt(1 - costheta ** 2)
    w = v * costheta + r * (v1 * math.cos(phi) + v2 * math.sin(phi))
    return w / LA.norm(w)

def w2S(w):
    S = np.eye(4)
    S[:3, :3] = np.eye(3) - 2 * np.outer(w, w) / np.sum(w ** 2)
    S[:3, 3] = -2 * w / np.sum(w ** 2)
    return S

def to_label(w, w0):
    theta = math.acos(np.clip(abs(w @ w0) / LA.norm(w) / LA.norm(w0), -1, 1))
    return [theta < theta0 for theta0 in CM.detection.theta]


#This definition checks whether if the family instance is flipped or not
# and gives the list of elements that are flipped and a Boolean list for filtering in detail.

import clr
clr.AddReference('System.Core')
clr.AddReference('RhinoInside.Revit')
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')

from System import Enum

import rhinoscriptsyntax as rs
import Rhino
import RhinoInside
import Grasshopper
from Grasshopper.Kernel import GH_RuntimeMessageLevel as RML
from RhinoInside.Revit import Revit, Convert
from Autodesk.Revit import DB

# access the active document object
doc = Revit.ActiveDBDocument

def show_warning(msg):
    ghenv.Component.AddRuntimeMessage(RML.Warning, msg)

def show_error(msg):
    ghenv.Component.AddRuntimeMessage(RML.Error, msg)

def show_remark(msg):
    ghenv.Component.AddRuntimeMessage(RML.Remark, msg)

Bools = []
IsMirrored = []
NotMirrored = []

Elements = Elements if isinstance(Elements, list) else [Elements]

for element in Elements:
    if element.Mirrored == True:
        Bools.append(True)
        IsMirrored.append(element)
    else:
        Bools.append(False)
        NotMirrored.append(element)


"""Visualization tool for state spaces."""
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

def visualize_correlation(output_file: Path | str | None, X: np.ndarray) -> None:
    """Visualize the correlation between states.

    Args:
        output_file: File to write the plot to.
        X: shape (N, dX), states
    """
    corr = np.corrcoef(X, rowvar=False)
    sns.heatmap(
        corr,
        cmap="bwr",
        vmin=-1,
        vmax=1,
        mask=np.triu(np.ones_like(corr, dtype=bool), 1),  # Mask upper triangle
    )
    plt.xlabel("$x$")
    plt.ylabel("$x$")
    plt.title("Correlation")

    plt.tight_layout()
    if output_file is not None:
        plt.savefig(output_file)
    else:
        plt.show()
    plt.close()


import re
from datetime import datetime

import pdfminer.high_level

import categories
from mail_api.abstract_mail_api import AbstractAttachment
from message_handler import MessageHandler
from utils import temporary_locale

class MusikHugMessageHandler(MessageHandler):
    def get_type(self):
        return categories.SUPPLIES

    def get_query_params(self):
        return {
            self.SUBJECT: "Ihre Bestellung wurde versandt",
            self.SENDER: "musikhug.ch",
        }

    def extract_txt(self, pdffile: str):
        with temporary_locale("de_CH"):
            text: str = pdfminer.high_level.extract_text(pdffile)
            purchase_date: str = re.search(
                r"\b(\d+\. (?:Januar|Februar|März|April|Mai|Juni|Juli|"
                r"August|September|Oktober|November|Dezember).\d\d\d\d)\b",
                text,
            )[1]
            self.purchase_date = datetime.strptime(purchase_date, "%d. %B %Y")
            self.amount = float(re.findall(r"\b(\d+\.\d+)\b", text)[-1])

    def handle_attachment(self, attachment: AbstractAttachment):
        pdffile: str = self.save(attachment)
        self.filename = attachment.get_filename()
        self.extract_txt(pdffile)