from django.http import HttpResponse
from serializers import UserMedicalHistorySerializer, UserProfileSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import authentication_classes, permission_classes
from models import DeviceHubProject
from devicehub import getData
from rest_framework import status

class NoHardwareEndpoint(Exception):
    message = "No hardware endpoint registered for user"

def index(request):
    return HttpResponse("NOT ALLOWED", status=403)

@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
class UserProfile(APIView):
    def get(self, request, format=None):
        user = request.user
        serializer = UserProfileSerializer(user, many=False)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = UserProfileSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
class UserMedicalHistory(APIView):
    def get(self, request, format=None):
        user = request.user
        serializer = UserMedicalHistorySerializer(user, many=False)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = UserMedicalHistorySerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
class UserDataHistory(APIView):
    def get(self, request, item=None, format=None):
        user = request.user
        max_num_points = 1000
        try:
            dh = user.userprofile.devicehubproject
            if not isinstance(dh, DeviceHubProject):
                raise NoHardwareEndpoint
        except Exception as e:
            data = {
                'success': False,
                'error_msg': e.message,
            }
            return Response(data)
        else:
            data = {
                'success': True,
                'pulse': dh.pulse(limit=max_num_points),
                'temperature': dh.temperature(limit=max_num_points),
                'blood_sugar': dh.blood_sugar(limit=max_num_points),
                'ambient_temperature': dh.ambient_temperature(limit=max_num_points),
                'ambient_humidity': dh.ambient_humidity(limit=max_num_points),
                'ambient_air_quality': dh.ambient_air_quality(limit=max_num_points),
                'panic': dh.panic(limit=max_num_points),
            }
            if item is not None:
                return Response(data[item])
            else:
                return Response(data)

@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
class UserLatestData(APIView):
    def get(self, request, format=None):
        user = request.user
        try:
            dh = user.userprofile.devicehubproject
            if not isinstance(dh, DeviceHubProject):
                raise NoHardwareEndpoint
        except Exception as e:
            data = {
                'success': False,
                'error_msg': e.message,
            }
            return Response(data)
        else:
            data = {
                'success': True,
                'pulse': dh.pulse(),
                'temperature': dh.temperature(),
                'blood_sugar': dh.blood_sugar(),
                'ambient_temperature': dh.ambient_temperature(),
                'ambient_humidity': dh.ambient_humidity(),
                'ambient_air_quality': dh.ambient_air_quality(),
                'panic': dh.panic(),
            }
            return Response(data)

@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
class UserDataLearn(APIView):
    def get(self, request, format=None):
        user = request.user
        return Response(getData(user))


# 사탕 : https://www.acmicpc.net/problem/11256

from sys import stdin
input = stdin.readline

def print_box_number():
    J, N = map(int, input().rstrip().split())
    RC = [R * C for R, C in [list(map(int, input().rstrip().split())) for _ in range(N)]]
    RC.sort(reverse=True)

    box = 0
    while True:
        if J <= 0:
            break
        J -= RC.pop(0)
        box += 1
    print(box)

T = int(input().rstrip())
for _ in range(T):
    print_box_number()


from menu import products

def get_product_by_id(_id: int):
    if type(_id) != int:
            raise TypeError("product id must be an int")
    for dish in products:
        if dish["_id"] == _id:
            return dish
    return {}

def get_products_by_type(_type: str):
    if type(_type) != str:
        raise TypeError("product type must be a str")
    lis = []
    for dish in products:
        if dish["type"] == _type:
            lis.append(dish)
    return lis

def menu_report():
    average = 0
    most_common_type = ""
    max_type_value = 0
    types={}
    for product in products:
        average += product["price"]
        types[product["type"]]= len(get_products_by_type(product["type"]))
    for _type in types.items():
        if _type[1] > max_type_value:
            max_type_value = _type[1]
            most_common_type = _type[0]

    return f"Products Count: {len(products)} - Average Price: ${round(average/len(products),2)} - Most Common Type: {most_common_type}"

def add_product(menu: list, **kwargs):
    max_product_id = 0
    for product in menu:
        if product["_id"] > max_product_id:
            max_product_id = product["_id"]
    max_product_id += 1
    kwargs["_id"] = max_product_id
    menu.append(kwargs)
    return kwargs


import os

from backend.app import app
from real_agents.adapters.models import ChatOpenAI, ChatAnthropic
from real_agents.adapters.llm import BaseLanguageModel

LLAMA_DIR = "PATH_TO_LLAMA_DIR"

@app.route("/api/llm_list", methods=["POST"])
def get_llm_list():
    """Gets the whole llm list."""
    return [
        {"id": llm, "name": llm} for llm in [
            "gpt-3.5-turbo-16k",
            "gpt-4",
            "claude-v1",
            "claude-2",
            "lemur-chat"
        ]
    ]

def get_llm(llm_name: str, **kwargs) -> BaseLanguageModel:
    """Gets the llm model by its name."""
    if llm_name in ["gpt-3.5-turbo-16k", "gpt-4"]:
        return ChatOpenAI(
            model_name=llm_name,
            streaming=True,
            verbose=True,
            **kwargs
        )
    elif llm_name in ["claude-v1", "claude-2"]:
        anthropic_api_key = os.getenv("ANTHROPIC_API_KEY", "")
        return ChatAnthropic(
            model=llm_name,
            streaming=True,
            verbose=True,
            anthropic_api_key=anthropic_api_key,
            **kwargs,
        )
    elif llm_name == "lemur-chat":
        return ChatOpenAI(
            model_name="lemur-70b-chat-v1",
            streaming=True,
            openai_api_base="https://model-api.xlang.ai/v1",
            verbose=True,
            max_tokens=2048,
            **kwargs
        )
    else:
        raise ValueError(f"llm_name {llm_name} not found")


import sys, os
from setuptools import setup

dependencies = ['Pillow', 'RPi.GPIO', 'spidev']

setup(
    name='waveshare-epd',
    description='Waveshare e-Paper Display',
    author='Waveshare',
    package_dir={'': 'lib'},
    packages=['waveshare_epd'],
    install_requires=dependencies,
)


import requests

def test_base_functionality():
    # CREATE new test record (POST)
    test_headers = {"title" : "a1", "description" : "a1", "date" : "2077-04-23"}
    response = requests.post("http://localhost:8000/create/", json=test_headers)
    assert response.ok, "Error when trying to create a new record"
    # GET all records (GET)
    response = requests.get("http://localhost:8000/tasks/all")
    assert response.ok, "Error while getting the todo list"
    # GET all records (ids only)
    response = requests.get("http://localhost:8000/id-info/")
    # GET id from last record
    last_id = str(response.json()[-1]['id'])
    # GET by id (GET)
    response = requests.get(f"http://localhost:8000/tasks/{last_id}")
    assert response.ok, "Error while getting the record by id"
    # CHANGE status of test record (PUT)
    response = requests.put(f"http://localhost:8000/change-status/{last_id}/", json={"done" : "true"})
    assert response.ok, "Error when trying to change status"
    # DELETE test record (DELETE)
    response = requests.delete("http://localhost:8000/delete/"+last_id)
    assert response.ok, "Error while deleting the record"


import os
import sys
import logging

from populate_secrets import get_all_files_in_dir

if __name__ == "__main__":
    logging.info("Beginning Script")

    if len(sys.argv) < 2:
        logging.fatal("< 2 cmd arg")
        sys.exit(1)

    repo_root = sys.argv[1]
    if not len(repo_root):
        logging.error("unable to find repo root")

    dir_path = f"{repo_root}/test-framework/features"
    all_files = get_all_files_in_dir(dir_path)

    if not len(all_files):
        logging.error("No Files Found To Delete In " + dir_path)
        sys.exit(0)

    for filename in all_files:
        if filename.find(".feature") > -1:
            os.remove(dir_path + "/" + filename)
            logging.info(filename + " Removed")

    logging.info("Script Complete")


from time import time

from algorithm.breadth_first_search import BreadthFirstSearch
from algorithm.depth_first_search import DepthFirstSearch
from problem.queens import QueensState

if __name__ == '__main__':

    for i in range(8,14):
        t0 = time()

        s = QueensState(i)

        bfs = BreadthFirstSearch(s)

        bfs.search(True, False)

        t1=time()

        print(f"bfs: time = {t1 - t0}s")

        dfs = DepthFirstSearch(s)

        dfs.search(True, False)

        print(f"dfs: time = {time() - t1}s")


from youtube_dl import YoutubeDL
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pyexcel

url = "https://www.apple.com/itunes/charts/songs/" #doawload webpage

conn = urlopen(url) #open connection

raw_data = conn.read()#read raw data

webpage_text = raw_data.decode("utf-8")#decode data
#find ROI
soup = BeautifulSoup(webpage_text, "html.parser") #connect to soup

section = soup.find("section","section chart-grid")

li_list = section.find_all("li")

new_list =[]
for li in li_list:
    a1 = li.h3.a
    a2 = li.h4.a
    namesong = a1.string
    artist = a2.string
    song ={
        "Namesong": namesong,
        "artist": artist
    }
    new_list.append(song)

new_list1 = []
for i in range(len(new_list)):
    a = new_list[i]["Namesong"] + " " + new_list[i]["artist"]
    new_list1.append(a)

for i in range(len(new_list1)):
    options = {
    'default_search': 'ytsearch', # tell downloader to search instead of directly downloading
    'max_downloads': 1 # Tell downloader to download only the first entry (video)
    }
    dl = YoutubeDL(options)
    dl.download([new_list1[i]])


from rply import LexerGenerator

class WccLexer:
	def __init__(self):
		lg = LexerGenerator()

		lg.add('NUMBER', r'\d+')
		lg.add('PLUS', r'\+')
		lg.add('MINUS', r'-')
		lg.add('EXIT', r'exit')

		lg.ignore(r'\s+')

		self.lexer = lg.build()

	def lex(self, text):
		return self.lexer.lex(text)


from Crypto.Cipher import AES
from hexutils import *
from xor import xor
from random import randint
import pkcs7

def dup_blocks(enc, block_size=16):
    if len(enc)%block_size != 0: return 0
    duplicates = 0
    blocks = set()
    for n in range(0,len(enc),block_size):
        block = enc[n:n+block_size]
        if block in blocks:
            duplicates += 1
        else:
            blocks.add(block)
    return duplicates

def cbc_encrypt(text, key, iv, block_size=16):
    cipher = AES.new(key, AES.MODE_ECB)
    enc = ''
    prev = iv
    for n in range(0, len(text), block_size):
        block = xor(text[n:n+block_size], prev)
        enc_block = cipher.encrypt(block)
        enc += enc_block
        prev = enc_block
    return enc

def cbc_decrypt(enc, key, iv, block_size=16):
    cipher = AES.new(key, AES.MODE_ECB)
    dec = ''
    prev = iv
    for n in range(0, len(enc), block_size):
        block = enc[n:n+block_size]
        dec_block = cipher.decrypt(block)
        dec += xor(dec_block, prev)
        prev = block
    return dec


print('61 · Search for a Range')

def searchRange(self, A, target):

# find the first then find the last position of the target value
    if len(A) ==0:
        return [-1,-1]
    start,end =0, len(A)-1
    while start +1 < end:
        mid = (end + start) // 2
        if target > A[mid]:
            start = mid
        elif target < A[mid]:
            end = mid
        else:
            end = mid
    if A[start] == target:
        left =start
    elif A[end] == target:
        left =end
    else:
        return [-1,-1]
    start, end = left, len(A)-1
    while start + 1 < end:
        mid = (end + start) //2
        if target > A[mid]:
            start = mid
        elif target < A[mid]:
            end = mid
        else:
            start = mid
    if A[end] == target:
        right =end
    else:
        right = start

    return [left, right]

A = [5, 7, 7, 8, 8, 10]
target = 8

print(searchRange(0,A,target))


"""
描述： 王婷同学的学习资料
时间：2018-12-7
作者：Acmen
"""

import numpy as np
import matplotlib.pyplot as plt

"""
回顾新东西：
1. matplotlib: 画图的一个库
2. numpy: 数组的封装库
3. 从互联网上获取别人写好的开源库：pip install xxxxx 写入到一个后缀为bat文件中
4. 利用numpy和matplotlib画了一张图
"""
def PlotShow():
	x = np.array([1,2,3,4,5,6,7,8])
	y = np.array([3,5,7,6,2,6,10,15])
	plt.plot(x, y, 'r')
	plt.bar(x, y, 0.2, alpha=1, color='b')
	plt.show()

PlotShow()


# -*- coding: iso-8859-15 -*-
"""
Simple test for event service
"""

from Testing import ZopeTestCase

ZopeTestCase.installProduct('CMFCore', quiet=1)
ZopeTestCase.installProduct('CMFDefault', quiet=1)
ZopeTestCase.installProduct('MailHost', quiet=1)
ZopeTestCase.installProduct('CPSCore', quiet=1)
ZopeTestCase.installProduct('ZCTextIndex', quiet=1)
import unittest

from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.SecurityManager import setSecurityPolicy
from Testing.makerequest import makerequest
from Products.CMFCore.tests.base.security \
     import PermissiveSecurityPolicy, AnonymousUser

from Products.CPSCore.EventServiceTool import EventServiceTool

class EventServiceToolTest(ZopeTestCase.ZopeTestCase):
    """
    Test event service
    """

    def _make_tool(self):
        portal = self.folder
        tool = EventServiceTool()
        portal._setObject(tool.getId(), tool)

    def test_0_create(self):
        self._make_tool()

    def test_1_add_subscriber(self):
        self._make_tool()
        portal = self.folder
        evtool = portal.portal_eventservice
        evtool.manage_addSubscriber(
            subscriber='portal_subscriber',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
        )
        self.assertEqual(len(evtool.getSubscribers()), 1)

    def test_11_add_subscriber_without_activation_specified(self):
        self._make_tool()
        portal = self.folder
        evtool = portal.portal_eventservice
        evtool.manage_addSubscriber(
            subscriber='portal_subscriber',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
        )
        self.assertEqual(len(evtool.getSubscribers()), 1)
        sub = evtool.getSubscriberByName('portal_subscriber')
        self.assert_(sub.activated)

    def test_2_del_subscriber(self):
        self._make_tool()
        portal = self.folder
        evtool = portal.portal_eventservice

        # Subscriber 1
        id = evtool.manage_addSubscriber(
            subscriber='portal_subscriber',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
            )

        self.assert_(id)
        internal_subscribers = evtool._notification_dict['*']['*'][
            'asynchronous']
        self.assertEqual(len(evtool.getSubscribers()), 1)
        self.assertEqual(len(internal_subscribers),1)

        # Subscriber 2
        id2 = evtool.manage_addSubscriber(
            subscriber='portal_subscriber2',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
            )

        self.assert_(id2)
        self.assertEqual(len(evtool.getSubscribers()), 2)
        internal_subscribers = evtool._notification_dict['*']['*'][
            'asynchronous']
        self.assertEqual(len(internal_subscribers), 2)

        # Delete the subscriber 1
        evtool.manage_delObjects([id])
        internal_subscribers = evtool._notification_dict['*']['*'][
            'asynchronous']
        self.assertEqual(len(evtool.getSubscribers()), 1)
        self.assertEqual(len(internal_subscribers),1)

        # Delete the subscriber 2
        evtool.manage_delObjects([id2])
        self.assertEqual(len(evtool.getSubscribers()), 0)
        self.assertEqual(evtool._notification_dict,{})

    def test_2_getSubscriberByName(self):
        self._make_tool()
        portal = self.folder
        evtool = portal.portal_eventservice

        # Subscriber 1
        id = evtool.manage_addSubscriber(
            subscriber='portal_subscriber',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
            )

        # Subscriber 2
        id2 = evtool.manage_addSubscriber(
            subscriber='portal_subscriber2',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
            )

        # Test sub1
        sub1 = evtool.getSubscriberByName('portal_subscriber')
        self.assert_(sub1)
        self.assertEqual(sub1.getId(), id)

        # Test sub2
        sub2 = evtool.getSubscriberByName('portal_subscriber2')
        self.assert_(sub2)
        self.assertEqual(sub2.getId(), id2)

        # Test a non existent one
        subx = evtool.getSubscriberByName('portal_subscriber3')
        self.assertEqual(subx, None)

        # Test a non existent one with default returned value
        class Klass:
            pass

        instance = Klass()
        subx = evtool.getSubscriberByName('portal_subscriber3', instance)
        self.assertEqual(subx, instance)

    def test_order_subscribers(self):
        # XXX: assuming events are distributed in the order given by
        # getSubscribers() method
        self._make_tool()
        portal = self.folder
        evtool = portal.portal_eventservice

        # Subscriber 1
        id = evtool.manage_addSubscriber(
            subscriber='portal_subscriber1',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
            )

        # Subscriber 2
        id2 = evtool.manage_addSubscriber(
            subscriber='portal_subscriber2',
            action='action',
            meta_type="*",
            event_type="*",
            notification_type="asynchronous",
            compressed=0,
            activated=1,
            )

        subs_names = [x.subscriber for x in evtool.getSubscribers()]
        self.assertEqual(subs_names, ['portal_subscriber1',
                                      'portal_subscriber2'])

        # moving portal_subscriber2 on top
        subs = evtool.getSubscriberByName('portal_subscriber2')
        subs_id = subs.getId()
        evtool.moveObjectsToTop(ids=(subs_id,))

        subs_names = [x.subscriber for x in evtool.getSubscribers()]
        self.assertEqual(subs_names, ['portal_subscriber2',
                                      'portal_subscriber1'])

    # XXX: add more tests

def test_suite():
    loader = unittest.TestLoader()
    return loader.loadTestsFromTestCase(EventServiceToolTest)

if __name__ == '__main__':
    unittest.TextTestRunner().run(test_suite())


import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable

from typing import Optional, Tuple, Type

from .common import LayerNorm2d, MLPBlock

from .image_encoder import (
    window_partition,
    window_unpartition,
    add_decomposed_rel_pos,
    ImageEncoderViT,
    Block,
    Attention,
)

class TokenClusteringBlock(nn.Module):
    def __init__(self, num_spixels=None, n_iters=5, temperture=0.01, window_size=5):
        super().__init__()
        if isinstance(num_spixels, tuple):
            assert len(num_spixels) == 2
        elif num_spixels is not None:
            x = int(math.sqrt(num_spixels))
            assert x * x == num_spixels
            num_spixels = (x, x)
        self.num_spixels = num_spixels
        self.n_iters = n_iters
        self.temperture = temperture
        assert window_size % 2 == 1
        self.r = window_size // 2

    def calc_init_centroid(self, images, num_spixels_width, num_spixels_height):
        """
        calculate initial superpixels

        Args:
            images: torch.Tensor
                A Tensor of shape (B, C, H, W)
            spixels_width: int
                initial superpixel width
            spixels_height: int
                initial superpixel height

        Return:
            centroids: torch.Tensor
                A Tensor of shape (B, C, H * W)
            init_label_map: torch.Tensor
                A Tensor of shape (B, H * W)
            num_spixels_width: int
                A number of superpixels in each column
            num_spixels_height: int
                A number of superpixels int each raw
        """
        batchsize, channels, height, width = images.shape
        device = images.device

        centroids = torch.nn.functional.adaptive_avg_pool2d(
            images, (num_spixels_height, num_spixels_width)
        )

        with torch.no_grad():
            num_spixels = num_spixels_width * num_spixels_height
            labels = (
                torch.arange(num_spixels, device=device)
                .reshape(1, 1, *centroids.shape[-2:])
                .type_as(centroids)
            )
            init_label_map = torch.nn.functional.interpolate(
                labels, size=(height, width), mode="nearest"
            ).type_as(centroids)
            init_label_map = init_label_map.repeat(batchsize, 1, 1, 1)

        init_label_map = init_label_map.reshape(batchsize, -1)
        centroids = centroids.reshape(batchsize, channels, -1)

        return centroids, init_label_map

    def forward(self, pixel_features, num_spixels=None):
        if num_spixels is None:
            num_spixels = self.num_spixels
            assert num_spixels is not None
        else:
            if isinstance(num_spixels, tuple):
                assert len(num_spixels) == 2
            else:
                x = int(math.sqrt(num_spixels))
                assert x * x == num_spixels
                num_spixels = (x, x)
        pixel_features = pixel_features.permute(0, 3, 1, 2)
        num_spixels_height, num_spixels_width = num_spixels
        num_spixels = num_spixels_width * num_spixels_height
        spixel_features, init_label_map = self.calc_init_centroid(
            pixel_features, num_spixels_width, num_spixels_height
        )

        device = init_label_map.device
        spixels_number = torch.arange(num_spixels, device=device)[None, :, None]
        relative_labels_widths = init_label_map[:, None] % num_spixels_width - spixels_number % num_spixels_width
        relative_labels_heights = torch.div(init_label_map[:, None], num_spixels_width, rounding_mode='trunc') - torch.div(spixels_number, num_spixels_width, rounding_mode='trunc')
        mask = torch.logical_and(torch.abs(relative_labels_widths) <= self.r, torch.abs(relative_labels_heights) <= self.r)
        mask_dist = (~mask) * 1e16

        pixel_features = pixel_features.reshape(*pixel_features.shape[:2], -1)  # (B, C, L)
        permuted_pixel_features = pixel_features.permute(0, 2, 1)       # (B, L, C)

        for _ in range(self.n_iters):
            dist_matrix = self.pairwise_dist(pixel_features, spixel_features)    # (B, L', L)
            dist_matrix += mask_dist
            affinity_matrix = (-dist_matrix * self.temperture).softmax(1)
            spixel_features = torch.bmm(affinity_matrix.detach(), permuted_pixel_features)
            spixel_features = spixel_features / affinity_matrix.detach().sum(2, keepdim=True).clamp_(min=1e-16)
            spixel_features = spixel_features.permute(0, 2, 1)

        dist_matrix = self.pairwise_dist(pixel_features, spixel_features)
        hard_labels = torch.argmin(dist_matrix, dim=1)

        B, C, _ = spixel_features.shape
        spixel_features = spixel_features.permute(0, 2, 1).reshape(B, num_spixels_height, num_spixels_width, C)
        return spixel_features, hard_labels

    def pairwise_dist(self, f1, f2):
        return ((f1 * f1).sum(dim=1).unsqueeze(1)
                + (f2 * f2).sum(dim=1).unsqueeze(2)
                - 2 * torch.einsum("bcm, bcn -> bmn", f2, f1))

    def extra_repr(self):
        return f"num_spixels={self.num_spixels}, n_iters={self.n_iters}"

def naive_unpool(f_regions, region_indices):
    _, _, C = f_regions.shape
    N, L = region_indices.shape
    index = region_indices.view(N, L, 1).expand(N, L, C)
    result = f_regions.gather(1, index)
    return result

class State:
    def __init__(self, unpooling):
        self.unpooling = unpooling
        self.__updated = False

    @property
    def updated(self):
        return self.__updated

    def get(self, name, default=None):
        return getattr(self, name, default)

    def update_state(self, **states: dict):
        self.__updated = True
        for k, v in states.items():
            setattr(self, k, v)

    def call(self, input: torch.Tensor):
        return self.unpooling(input, self)

class UnpoolingBase(nn.Module):
    def forward(self, x, state: State):
        if not state.updated:
            return x, False
        return self._forward(x, state)

    def derive_unpooler(self):
        return State(self)

class NaiveUnpooling(UnpoolingBase):
    def _forward(self, x, state: State):
        return naive_unpool(x, state.hard_labels), False

class TokenReconstructionBlock(UnpoolingBase):
    def __init__(self, k=20, temperture=0.01):
        super().__init__()

        self.k = k
        self.temperture = temperture

    def _forward(self, x, state: State):
        feat = state.feat_before_pooling
        sfeat = state.feat_after_pooling
        ds = (
            (feat * feat).sum(dim=2).unsqueeze(2)
            + (sfeat * sfeat).sum(dim=2).unsqueeze(1)
            - 2 * torch.einsum("bnc, bmc -> bnm", feat, sfeat)
        )  # distance between features and super-features
        ds[ds < 0] = 0
        weight = torch.exp(-self.temperture * ds)
        if self.k >= 0:
            topk, indices = torch.topk(weight, k=self.k, dim=2)
            mink = torch.min(topk, dim=-1).values
            mink = mink.unsqueeze(-1).repeat(1, 1, weight.shape[-1])
            mask = torch.ge(weight, mink)
            zero = Variable(torch.zeros_like(weight)).to(weight.device)
            attention = torch.where(mask, weight, zero)
        attention = F.normalize(attention, dim=2)
        ret = torch.einsum("bnm, bmc -> bnc", attention, x)

        return ret, False

class HourglassImageEncoderViT(ImageEncoderViT):
    def __init__(
        self,
        img_size: int = 1024,
        patch_size: int = 16,
        in_chans: int = 3,
        embed_dim: int = 768,
        depth: int = 12,
        num_heads: int = 12,
        mlp_ratio: float = 4.0,
        out_chans: int = 256,
        qkv_bias: bool = True,
        norm_layer: Type[nn.Module] = nn.LayerNorm,
        act_layer: Type[nn.Module] = nn.GELU,
        use_abs_pos: bool = True,
        use_rel_pos: bool = False,
        rel_pos_zero_init: bool = True,
        window_size: int = 0,
        global_attn_indexes: Tuple[int, ...] = (),
        hourglass_clustering_location: int = -1,
        hourglass_num_cluster: int = 100,
        hourglass_cluster_iters: int = 5,
        hourglass_temperture: float = 0.01,
        hourglass_cluster_window_size: int = 5,
        hourglass_reconstruction_k: int = 20,
    ) -> None:
        """
        Args:
            img_size (int): Input image size.
            patch_size (int): Patch size.
            in_chans (int): Number of input image channels.
            embed_dim (int): Patch embedding dimension.
            depth (int): Depth of ViT.
            num_heads (int): Number of attention heads in each ViT block.
            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
            qkv_bias (bool): If True, add a learnable bias to query, key, value.
            norm_layer (nn.Module): Normalization layer.
            act_layer (nn.Module): Activation layer.
            use_abs_pos (bool): If True, use absolute positional embeddings.
            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
            window_size (int): Window size for window attention blocks.
            global_attn_indexes (list): Indexes for blocks using global attention.
        """
        super().__init__(
            img_size=img_size,
            patch_size=patch_size,
            in_chans=in_chans,
            embed_dim=embed_dim,
            depth=depth,
            num_heads=num_heads,
            mlp_ratio=mlp_ratio,
            out_chans=out_chans,
            qkv_bias=qkv_bias,
            norm_layer=norm_layer,
            act_layer=act_layer,
            use_abs_pos=use_abs_pos,
            use_rel_pos=use_rel_pos,
            rel_pos_zero_init=rel_pos_zero_init,
            window_size=window_size,
            global_attn_indexes=global_attn_indexes,
        )

        hourglass_clustering_location = hourglass_clustering_location if hourglass_clustering_location >= 0 else depth + 1

        self.window_size = window_size
        self.ws_new = int(math.sqrt(hourglass_num_cluster))

        self.blocks = nn.ModuleList()
        for i in range(depth):
            block = HourglassBlock(
                dim=embed_dim,
                num_heads=num_heads,
                mlp_ratio=mlp_ratio,
                qkv_bias=qkv_bias,
                norm_layer=norm_layer,
                act_layer=act_layer,
                use_rel_pos=use_rel_pos,
                rel_pos_zero_init=rel_pos_zero_init,
                window_size=(window_size if i < hourglass_clustering_location else self.ws_new) if i not in global_attn_indexes else 0,
                window_size_ckpt=window_size,
                input_size=(img_size // patch_size, img_size // patch_size),
            )
            self.blocks.append(block)

        self.clustering_location = hourglass_clustering_location
        self.token_clustering_block = TokenClusteringBlock(
            num_spixels=hourglass_num_cluster,
            n_iters=hourglass_cluster_iters,
            temperture=hourglass_temperture,
            window_size=hourglass_cluster_window_size,
        )
        self.token_reconstruction_block = TokenReconstructionBlock(
            k=hourglass_reconstruction_k,
            temperture=hourglass_temperture,
        )

    def cluster(self, x, reconstructer):
        # x: B, H, W, C
        H, W = x.shape[1:3]
        x, pad_hw = window_partition(x, self.window_size)  # B*Nw, WH, WW, C
        Bnw, _, _, C = x.shape

        reconstructer.update_state(
            feat_before_pooling=x.view(-1, self.window_size * self.window_size, C)
        )
        x, hard_labels = self.token_clustering_block(x)  # B*H*W, Wh, Ww, C
        reconstructer.update_state(hard_labels=hard_labels)
        reconstructer.update_state(feat_after_pooling=x.view(Bnw, -1, C))

        # merge window
        # Reverse window partition
        h = pad_hw[0] // self.window_size * x.shape[1]
        w = pad_hw[1] // self.window_size * x.shape[2]
        x = window_unpartition(x, self.ws_new, (h, w), (h, w))
        # out: B, h, w, C
        return x, pad_hw

    def reconstruct(self, x, H, W, recontructer, pad_hw):
        # x: B, h, w, C
        x, _ = window_partition(x, self.ws_new)   # B*Nw, Wh, Ww, C
        Bnw, _, _, C = x.shape
        x = x.view(Bnw, -1, C)

        x, _ = recontructer.call(x) # B*Nw, WH*WW, C

        # merge windows
        x = x.view(-1, self.window_size, self.window_size, C)
        x = window_unpartition(x, self.window_size, pad_hw, (H, W)) # B, H, W, C
        return x

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.patch_embed(x)
        if self.pos_embed is not None:
            x = x + self.pos_embed

        H, W = x.shape[1], x.shape[2]
        reconstructer = self.token_reconstruction_block.derive_unpooler()
        reconstructer.update_state(hw_shape=(H, W))

        for i, blk in enumerate(self.blocks):
            if i == self.clustering_location:
                x, pad_hw = self.cluster(x, reconstructer)
            x = blk(x)

        if x.shape[1] != H or x.shape[2] != W:
            x = self.reconstruct(x, H, W, reconstructer, pad_hw)

        x = self.neck(x.permute(0, 3, 1, 2))

        return x

    def load_hourglass_args(self, **hourglass_args):
        hourglass_clustering_location = hourglass_args.get('hourglass_clustering_location', self.clustering_location)
        hourglass_num_cluster = hourglass_args.get('hourglass_num_cluster', self.token_clustering_block.num_spixels[0] * self.token_clustering_block.num_spixels[1])
        hourglass_cluster_iters = hourglass_args.get('hourglass_cluster_iters', self.token_clustering_block.n_iters)
        hourglass_temperture = hourglass_args.get('hourglass_temperture', self.token_clustering_block.temperture)
        hourglass_cluster_window_size = hourglass_args.get('hourglass_cluster_window_size', self.token_clustering_block.r * 2 + 1)
        hourglass_reconstruction_k = hourglass_args.get('hourglass_reconstruction_k', self.token_reconstruction_block.k)

        self.clustering_location = hourglass_clustering_location if hourglass_clustering_location >= 0 else len(self.blocks) + 1

        self.ws_new = int(math.sqrt(hourglass_num_cluster))
        for i, blk in enumerate(self.blocks):
            blk.window_size = (self.window_size if i < self.clustering_location else self.ws_new) if blk.window_size != 0 else 0

        self.token_clustering_block = TokenClusteringBlock(
            num_spixels=hourglass_num_cluster,
            n_iters=hourglass_cluster_iters,
            temperture=hourglass_temperture,
            window_size=hourglass_cluster_window_size,
        )
        self.token_reconstruction_block = TokenReconstructionBlock(
            k=hourglass_reconstruction_k,
            temperture=hourglass_temperture,
        )

class HourglassBlock(Block):
    """Transformer blocks with support of window attention and residual propagation blocks"""

    def __init__(
        self,
        dim: int,
        num_heads: int,
        mlp_ratio: float = 4.0,
        qkv_bias: bool = True,
        norm_layer: Type[nn.Module] = nn.LayerNorm,
        act_layer: Type[nn.Module] = nn.GELU,
        use_rel_pos: bool = False,
        rel_pos_zero_init: bool = True,
        window_size: int = 0,
        input_size: Optional[Tuple[int, int]] = None,
        window_size_ckpt: int = 0,
    ) -> None:
        """
        Args:
            dim (int): Number of input channels.
            num_heads (int): Number of attention heads in each ViT block.
            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
            qkv_bias (bool): If True, add a learnable bias to query, key, value.
            norm_layer (nn.Module): Normalization layer.
            act_layer (nn.Module): Activation layer.
            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
            window_size (int): Window size for window attention blocks. If it equals 0, then
                use global attention.
            input_size (int or None): Input resolution for calculating the relative positional
                parameter size.
        """
        super(HourglassBlock, self).__init__(
            dim=dim,
            num_heads=num_heads,
            mlp_ratio=mlp_ratio,
            qkv_bias=qkv_bias,
            norm_layer=norm_layer,
            act_layer=act_layer,
            use_rel_pos=use_rel_pos,
            rel_pos_zero_init=rel_pos_zero_init,
            window_size=window_size,
            input_size=input_size,
        )

        self.attn = Attention(
            dim,
            num_heads=num_heads,
            qkv_bias=qkv_bias,
            use_rel_pos=use_rel_pos,
            rel_pos_zero_init=rel_pos_zero_init,
            input_size=input_size if window_size == 0 else (window_size_ckpt, window_size_ckpt),
        )


import sys
import const
import Util as util

class Flow(object):
    """
    Components:
    1. signature: hashed integer of {src_ip, dst_ip,
                                     transport_layer_protocol_type,
                                     src_port, dst_port}
                  (regardless of order)
    2. flow: list of TCP packets
    3. properties:
        (1) http
        (2) index_range: among the whole QxDM trace (min, max)
    """
    def __init__(self, signature):
        self.signature = signature
        self.flow = []
        self.properties = {
            "http": None,\
            "index_range": {"min": None, \
                            "max": None}, \
            "GET_index": None, \
            "url": []
            }
        self.cross_layer_trace = []

    # set the URLs request
    # notice urls is a list
    def setURL(self, urls):
        self.properties["url"] = urls

    # Add new packet to the flow
    def addPacket(self, entry, index):
        self.flow.append(entry)

        # update http type
        if entry.http["type"] != None and \
           entry.http["host"] != None and \
           entry.http["referer"] == None and \
           self.properties["http"] == None:
            self.properties["http"] = entry.http

        # update the range property
        if self.properties["index_range"]["min"] == None or \
           self.properties["index_range"]["min"] > index:
            self.properties["index_range"]["min"] = index

        if self.properties["index_range"]["max"] == None or \
           self.properties["index_range"]["max"] < index:
            self.properties["index_range"]["max"] = index

        # update the http GET index
        if self.properties["GET_index"] == None and \
           entry.http["type"] == "GET":
            self.properties["GET_index"] = len(self.flow) - 1

        # link that entry's flow entry to this instance
        entry.tcp["flow"] = self

    # generate the cross layer trace by wrapping around
    # lower layer information for a certain amount of time interval
    def getCrossLayerTrace(self, complete_trace):
        if len(self.cross_layer_trace) > 0:
            return self.cross_layer_trace
        if len(self.flow) == 0:
            print >> sys.stderr, "ERROR: flow length is zero"

        flow_start_time = complete_trace[self.properties["index_range"]["min"]].timestamp
        flow_end_time = complete_trace[self.properties["index_range"]["max"]].timestamp

        lower_layer_earliest_time = flow_start_time - const.FLOW_TIME_WIN
        lower_layer_latest_time = flow_end_time + const.FLOW_TIME_WIN

        trace_len = len(complete_trace)

        for start_index in range(self.properties["index_range"]["min"], -1, -1):
            if complete_trace[start_index].timestamp < lower_layer_earliest_time:
                break

        for end_index in range(self.properties["index_range"]["max"], trace_len, 1):
            if complete_trace[end_index].timestamp > lower_layer_latest_time:
                break

        # add lower layer entries in the trace
        flow_set = set(self.flow)

        for i in range(start_index, end_index + 1):
            if complete_trace[i].logID != const.PROTOCOL_ID:
                self.cross_layer_trace.append(complete_trace[i])
            elif i >= self.properties["index_range"]["min"] and \
                 i <= self.properties["index_range"]["max"] and \
                 complete_trace[i] in flow_set:
                self.cross_layer_trace.append(complete_trace[i])

        return self.cross_layer_trace

    # get Hashed value for the flow
    def getHashedPayload(self):
        hashedPayload = []
        for entry in self.flow:
            hashedPayload.append(util.getHashedPayload(entry))
        return hashedPayload

    # get the last the IP packet before the flow
    def getLastPacketBeforeFlow(self, complete_trace):
        indexList = range(self.properties["index_range"]["min"])
        indexList.reverse()

        entry = None

        for index in indexList:
            entry = complete_trace[index]
            if entry.logID == const.PROTOCOL_ID:
                return entry

        return entry

    # create signature from a entry
    # if entry is a valid TCP entry, then return signature
    # otherwise, return None
    @staticmethod
    def extractFlowSignature(entry):
        if entry.logID == const.PROTOCOL_ID and \
           entry.ip["src_ip"] != None and \
           entry.ip["dst_ip"] != None and \
           entry.ip["tlp_id"] != None and \
           entry.tcp["src_port"] != None and \
           entry.tcp["dst_port"] != None:
            DEL = "+"
            return str(hash(entry.ip["src_ip"]) ^ hash(entry.ip["dst_ip"])) + DEL + \
                   str(entry.ip["tlp_id"]) + DEL + \
                   str(hash(entry.tcp["src_port"]) * hash(entry.tcp["dst_port"]))
        else:
            return None


from math import log, ceil

number = int(input())

# number = 2251799813685247
# digits = ceil(log(number, 2))
# print(digits)

for base in range(2, number+1):
    # print(base)
    # print(base)
    digits = ceil(log(number, base))

    dig_sum = 0
    base_add = base

    dig_sum = ((base**digits ) -1) // (base-1)
    print(digits, base, dig_sum, digits)
    # for _ in range(digits):
    #     dig_sum += base_add
    #     base_add *= base

    if dig_sum == number:
        print(base)
        break


#Step 4

import networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations
from matplotlib import pyplot

#pyplot.gca().invert_yaxis()
#pyplot.gca().invert_xaxis()

g = nx.Graph()
g.add_node('Charlotteseville', pos=(38.0673201, -78.4930928)) # 8 Superchargers
g.add_node('Chester', pos = (37.3674726,-77.416648)) # 8 Superchargers
g.add_node('Glen_Allen', pos =(37.6697846, -77.4616425))# 20 superchaergers
g.add_node('Lexington', pos = (37.7973062, -79.4186505)) # 6 Superchargers
g.add_node('Mt_Jackson', pos = (38.7602417,	-78.6311195))# 8 Superchargers
g.add_node('Norfolk', pos = (36.8605204, -76.2073749)) # 6 superchargers
g.add_node('Richmond', pos = (37.5280639, -77.3554433)) # 20 superchargers
g.add_node('South_Hill', pos =(36.7483035,	-78.1036949))# 6 Superchargers
g.add_node('Strasburg', pos = (39.0052144, -78.3378302)) # 6 Superchargers
g.add_node('Woodbridge', pos = (38.6408382,	-77.2963031)) #10 Superchargers
g.add_node('Wytheville', pos = (36.9462562, -81.0548087)) #6 Superchargers
#Weighted Nodes
#With Weights Edges 101, 131, 142, 45, 86 (p=5) (-10 to get to the actual Number)
'''
g.add_node('Martinsville', pos =(36.68377756,-79.8654368))
g.add_node('Russell', pos = (36.93363198, -82.09416184))
g.add_node('Gloucester', pos =(37.43738723,	-76.54385427))
g.add_node('Stafford', pos =(38.42248789, -77.46005923))
g.add_node('Prince_William', pos =(38.70453558, -77.48111347))
'''
#UnWeighted Nodes
#Without Weights Edges 12, 113, 133, 30 , 64 (p=5)

g.add_node('Henry', pos =(36.68405319, -79.87400618))
g.add_node('Hampton', pos =(37.05019338,-76.36758735))
g.add_node('Middlesex', pos =(37.63470068, -76.57988891))
g.add_node('Southampton', pos =(36.72649424,-77.10727935))
g.add_node('Norton', pos =(36.94090281,-82.60945802))

nodes = ['Charlotteseville','Chester','Glen_Allen','Lexington','Mt_Jackson','Norfolk','Richmond','South_Hill','Strasburg','Woodbridge','Wytheville']
WeightedNodes = ['Martinsville', 'Russell', 'Gloucester', 'Stafford', 'Prince_William']
NonWeigthedNodes = ['Henry', 'Hampton', 'Middlesex', 'Southampton', 'Norton']
g.add_nodes_from(NonWeigthedNodes)
f = g.add_nodes_from(nodes)

#g=nx.complete_graph()

print("Nodes of graph: ")
print(g.nodes())

g.add_edge('Wytheville','Lexington', distance = 107.4)
g.add_edge('Lexington','Charlotteseville', distance = 53.8)
g.add_edge('Lexington','Mt_Jackson', distance = 79.1)
g.add_edge('Charlotteseville','Mt_Jackson', distance = 48.5)
g.add_edge('Mt_Jackson','Strasburg', distance = 23.1)
g.add_edge('Strasburg','Woodbridge', distance = 61.5)
g.add_edge('Woodbridge','Glen_Allen', distance = 67.7)
g.add_edge('Glen_Allen','Richmond', distance = 11.4)
g.add_edge('Richmond','Chester', distance = 11.6)
g.add_edge('Richmond','Norfolk', distance = 78.2)
g.add_edge('Chester','South_Hill', distance = 57.1)
g.add_edge('Wytheville','South_Hill', distance = 163.7)

''''
#With Weights Edges 101, 131, 142, 45, 86 (p=5) (-10 to get to the actual Number)
#35
g.add_edge('Martinsville', 'Wytheville', distance = 68.24 )
#76
g.add_edge('Martinsville', 'South_Hill', distance = 97.67 )
#91
g.add_edge('Russell', 'Wytheville', distance = 57.40)
#121
g.add_edge('Stafford','Woodbridge', distance = 121.68)
#132
g.add_edge('Stafford','Glen_Allen', distance = 88.78)
g.add_edge('Gloucester','Richmond', distance = 44.93)
g.add_edge('Gloucester','Woodbridge', distance =92.68)
'''

#Without Weights Edges 12, 113, 133, 30 , 64 (p=5)

g.add_edge('Norton','Wytheville',distance =85.84)
g.add_edge('Henry','Wytheville',distance = 67.78)
g.add_edge('Henry','South_Hill',distance = 98.14)
g.add_edge('Southampton','South_Hill',distance = 78.99)
g.add_edge('Southampton','Norfolk',distance = 1.50)
g.add_edge('Middlesex','Glen_Allen', distance = 48.29)
g.add_edge('Middlesex','Hampton', distance = 137.48)
g.add_edge('Hampton','Norfolk', distance =1.50)

pos = {city:(long, lat) for (city, (lat,long)) in nx.get_node_attributes(g, 'pos').items()}
nx.draw(g, pos, with_labels=True, node_size=50)
#red current superchargers
nx.draw_networkx_nodes(g,pos,node_color='r',node_size=50,alpha=0.4)
#Blue new superchargers
print (nx.dijkstra_path(g, 'Wytheville','Woodbridge'))

plt.show()


# template for "Stopwatch: The Game"
import simplegui

# define global variables
interval = 100
count = 0
t = 0
total = 0
mili = 0

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
    global mili
    minu = 0
    mili = int(t)%10          #gives us millisecs

    remainder1 = int(t)//10
    sec = remainder1%100     #gives us second

    if(sec>=60):
        minu = int(t)//1000 + sec//60 #minutes
        sec = sec%60

    else:
        minu = int(t)//1000

    if(sec<10):
        sec = "0"+str(sec)

    return str(minu)+":"+str(sec)+"."+str(mili)

# define event handlers for buttons; "Start", "Stop", "Reset"
def Start():
    timer.start()

def Stop():
    global count
    global total
    global mili
    timer.stop()
    total = total +1
    if (mili == 0):
        count = count +1

def Reset():
    global t
    global count
    global total
    timer.stop()
    t = 0
    count = 0
    total = 0

# define event handler for timer with 0.1 sec interval
def tick():
    global t
    t = t + 1
    return

# define draw handler
def draw_handler(canvas):
    canvas.draw_text(format(t), (133, 160), 70, 'Green')
    canvas.draw_text(str(total)+"/"+str(count), (20,20), 30, "Red")
    canvas.draw_circle((210, 190), 150, 5, 'Blue')
    canvas.draw_text("Stop Watch", (100, 250), 50, 'White')

# create frame
frame = simplegui.create_frame("Time converter", 400, 400)
frame.set_draw_handler(draw_handler)

# register event handlers
frame.add_button("Stop", Stop, 100)
frame.add_button("Start", Start, 100)
frame.add_button("Reset", Reset, 100)
timer = simplegui.create_timer(interval, tick)

# start frame
frame.start()

# Please remember to review the grading rubric


import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np

class BigModel(nn.Module):
    def __init__(self):
        super(BigModel, self).__init__()
        self.fc1 = nn.Linear(784, 512)
        self.fc2 = nn.Linear(512, 256)
        self.fc3 = nn.Linear(256, 10)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)
        return x

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)

def prune_network(model, pruning_rate=0.5, method="global"):
    for name, param in model.named_parameters():
        if "weight" in name:
            tensor = param.data.cpu().numpy()
            if method == "global":
                threshold = np.percentile(abs(tensor), pruning_rate * 100)
            else:  # local pruning
                threshold = np.percentile(abs(tensor), pruning_rate * 100, axis=1, keepdims=True)
            mask = abs(tensor) > threshold
            param.data = torch.FloatTensor(tensor * mask.astype(float)).to(param.device)

def train_with_pruning(model, dataloader, criterion, optimizer, device='cpu', num_epochs=10, pruning_rate=0.5):
    model.train()
    model.to(device)

    for epoch in range(num_epochs):
        running_loss = 0.0
        for batch_idx, (inputs, targets) in enumerate(dataloader):
            inputs, targets = inputs.to(device), targets.to(device)

            # 前向传播
            outputs = model(inputs.view(inputs.size(0), -1))
            loss = criterion(outputs, targets)

            # 反向传播
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

        print(f"Epoch {epoch + 1}, Loss: {running_loss / len(dataloader)}")

        # 在每个 epoch 结束后进行剪枝
        prune_network(model, pruning_rate, method="global") # <================================== just prune the weights ot 0 but still allow them to grow back by optimizer.step()

    return model

big_model = BigModel()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(big_model.parameters(), lr=1e-3)
big_model = train_with_pruning(big_model, train_loader, criterion, optimizer, device='cuda', num_epochs=10, pruning_rate=0.1)

# 保存训练好的模型
torch.save(big_model.state_dict(), "trained_with_pruning_model.pth")


from flask import Flask,render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)

#Este codigo funciono con una instalación de XAMPP en windows.
#No funcionaba con localhost ni con la dirección de la máquina. Funciono con 127.0.0.1
app.config['MYSQL_HOST'] = '127.0.0.1'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'flask'

mysql = MySQL(app)

@app.route('/form')
def form():
    return render_template('form.html')

@app.route('/login', methods = ['POST', 'GET'])
def login():
    if request.method == 'GET':
        return "Login via the login Form"

    if request.method == 'POST':
        name = request.form['name']
        age = request.form['age']
        print("{}{}".format(name,age))
        cursor = mysql.connection.cursor()
        #Nombre de tabla:testing
        cursor.execute(''' INSERT INTO testing VALUES(%s,%s)''',(name,age))
        mysql.connection.commit()
        cursor.close()
        return f"Done!!"

app.run(host='localhost', port=5000)


#how to use for loop with list

fruits = ["Apple","Orange","Banana","Pineapple"]

#sort the order
fruits.sort()

# print(fruits)

#now run for loop to read each element of list fruits

for each_fruits in fruits:
    print(each_fruits)


# The following program creates a quad tree from a point list. It also simulate random uniform motion of particles. Pressing SPACE
# toggles whether or not particles move. The quadtree is updated accordingly

import pygame
import sys
import random
import copy
from time import sleep

# Initialize pygame
pygame.init()
(SWIDTH, SHEIGHT) = (600, 600)
screen = pygame.display.set_mode((SWIDTH, SHEIGHT))

white = (255, 255, 255)

POINTS  = 100
CAPACITY = 5

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.rectangle = None

    def draw(self):
        pygame.draw.circle(screen, (255, 255, 0), (int(self.x), int(self.y)), 2)

    def update(self):
        ux = random.uniform(-5, 5)
        uy = random.uniform(-5, 5)

        self.x += ux
        self.y += uy

class Rectangle:
    def __init__(self, x, y, length, width):
        # x and y represent coordinates of the upper left corner
        self.x = x
        self.y = y
        self.length = length
        self.width = width

        self.upperleft = None
        self.upperright = None
        self.lowerleft = None
        self.lowerright = None

        self.capacity = CAPACITY
        self.contained = []
        self.pointsInside = 0

    def draw(self):
        if self.pointsInside != 0:
            pygame.draw.rect(screen, white, (self.x,self.y, self.length, self.width), 1)

        if self.upperleft != None:      self.upperleft.draw()
        if self.upperright != None:     self.upperright.draw()
        if self.lowerleft != None:      self.lowerleft.draw()
        if self.lowerright != None:     self.lowerright.draw()

    def check(self, point):
        xpos = point.x
        ypos = point.y
        if self.x <= xpos and xpos <= self.x + self.length and self.y <= ypos and ypos <= self.y + self.width:
            return True
        return False

    def decompose(self, point):
        xpos = point.x
        ypos = point.y

        # Check if point is inside the rectangle
        if self.check(point):
            self.pointsInside += 1

            if self.upperleft == None and self.pointsInside <= self.capacity:      self.contained.append(point)
        else:
            return

        # Check if the node is full. If it is subdivide
        if self.pointsInside >= self.capacity:
            hl = float(self.length / 2.0)
            hw = float(self.width / 2.0)
            hx = float(self.x + hl)
            hy = float(self.y + hw)
            if self.upperleft == None:      self.upperleft = Rectangle(self.x, self.y, hl, hw)
            if self.upperright == None:     self.upperright = Rectangle(hx, self.y ,hl, hw)
            if self.lowerleft == None:      self.lowerleft = Rectangle(hx, hy, hl, hw)
            if self.lowerright == None:      self.lowerright = Rectangle(self.x, hy,hl, hw)

            # We ensure that only the last nodes in the tree actually contain the points
            for pt in self.contained:
                if self.upperleft.check(pt):
                    self.upperleft.contained.append(pt)
                    self.upperleft.pointsInside += 1
                elif self.upperright.check(pt):
                    self.upperright.contained.append(pt)
                    self.upperright.pointsInside += 1
                elif self.lowerleft.check(pt):
                    self.lowerleft.contained.append(pt)
                    self.lowerleft.pointsInside += 1
                elif self.lowerright.check(pt):
                    self.lowerright.contained.append(pt)
                    self.lowerright.pointsInside += 1

            self.contained *= 0

        # If the current node has been subdivided, then recur down the tree to the children nodes
        if self.pointsInside > self.capacity:
            self.upperleft.decompose(point)
            self.upperright.decompose(point)
            self.lowerleft.decompose(point)
            self.lowerright.decompose(point)

def main():
    points = []
    qtree = Rectangle(0, 0, SWIDTH, SHEIGHT)

    for i in range(0, POINTS):
        x = random.randint(0, SWIDTH)
        y = random.randint(0, SHEIGHT)
        points.append(Point(x, y))

    for pt in points:
        qtree.decompose(pt)
    motion = False

    while True:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:       sys.exit()

            if e.type == pygame.MOUSEBUTTONDOWN:
                points *= 0
                qtree = Rectangle(0, 0, SWIDTH, SHEIGHT)
                for i in range(0, POINTS):
                    x = random.randint(0, SWIDTH)
                    y = random.randint(0, SHEIGHT)
                    pt = Point(x, y)
                    points.append(pt)
                    qtree.decompose(pt)
                motion = False

            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_SPACE:
                    motion = not motion

        screen.fill((0, 0, 0))

        if motion:
            qtree = Rectangle(0, 0, SWIDTH, SHEIGHT)
        for pt in points:
            if motion:
                pt.update()
                qtree.decompose(pt)
            pt.draw()

        qtree.draw()

        pygame.display.flip()

main()


import time
import cv2
import numpy as np
import threading
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QWidget, QSizePolicy, QComboBox
from PySide6.QtGui import QPainter, QColor, QGuiApplication, QImage
import mediapipe.python.solutions.face_mesh as mp_face_mesh
import mediapipe.python.solutions.face_mesh_connections as mp_face_mesh_connections
import utils
import observer

class CameraWidget(QWidget):
    def __init__(self):
        super().__init__()

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        #Face recognition
        self.face_mesh = mp_face_mesh.FaceMesh(
            max_num_faces=1,
            refine_landmarks=True,
            min_detection_confidence=0.5,
            min_tracking_confidence=0.5)
        self.faceLandmarks = [None]

        #Video capture
        self.video_capture = cv2.VideoCapture(observer.get('cameraId'))
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.loadNextLiveFrame)
        self.timer.start(33)

        self.currentFrame = None
        self.recordedFrames = [[],[]] # [frames, frameInterval]
        self.prevFrameTime = None
        self.recordFrame = lambda _: None
        self.drawFrameLandmarks = lambda _: None
        self.imageCenter = None
        self.zoom_factor = 1.0
        self.time = [0]
        self.loadNextLiveFrame()

        self.stopThread = False
        threading.Thread(target=self.liveResult).start()

        observer.register("isRecording", self.startRecord)
        observer.register("isRecording", lambda value: observer.update("showLandmarks", not value))
        observer.register("videoLoaded", self.changeVideoCapture)
        observer.register("isPlaying", self.playLoadedVideo)
        observer.register("previousFrame", lambda _: self.previousFrame())
        observer.register("nextFrame", lambda _: self.nextFrame())
        observer.register("goToStart", lambda _: self.toStart())
        observer.register("goToEnd", lambda _: self.toEnd())
        observer.register("framePosition", self.updateStartEndObserver)
        observer.register("faceLandmarks", lambda faceLandmarks, self=self: setattr(self, 'faceLandmarks', faceLandmarks))
        observer.register("showLandmarks", lambda showLandmarks, self=self: setattr(self, 'drawFrameLandmarks', self.drawLandmarks) if showLandmarks else setattr(self, 'drawFrameLandmarks', lambda _: None))
        observer.register("zoom", lambda zoom, self=self: setattr(self,"zoom_factor",zoom))
        observer.register("framePosition", self.mouthTracking)
        observer.register("loadedFrames", lambda frames, self=self: setattr(self,"recordedFrames",frames))
        observer.register("goToFrame", lambda position: (observer.update("framePosition", position-1),self.loadNextRecordedFrame()))

        observer.update("videoLoaded", False)
        observer.update("videoLength", 0)
        observer.update("loadedFrames", self.recordedFrames)
        observer.update("imageSize", self.currentFrame.shape[:2])
        observer.update("isAtStart", False)
        observer.update("isAtEnd", False)
        observer.update("faceLandmarks", self.faceLandmarks)
        observer.update("showLandmarks", True)
        observer.update("zoom", self.zoom_factor)
        observer.update("mouthTracking", False)
        observer.update("videoSaved", False)
        observer.update("dataSaved", False)

    def paintEvent(self, event):
        image = self.currentFrame.copy()
        self.drawFrameLandmarks(image)
        w,h = image.shape[1]/self.zoom_factor, image.shape[0]/self.zoom_factor
        if not self.imageCenter: self.mouthTracking(0)
        x1 = int(self.imageCenter[0]-w/2)
        x2 = int(self.imageCenter[0]+w/2)
        y1 = int(self.imageCenter[1]-h/2)
        y2 = int(self.imageCenter[1]+h/2)
        if x1 < 0:
            x2 += x1
            x1 = 0
        elif x2 > image.shape[1]:
            x1 += x2 - image.shape[1]
            x2 = image.shape[1]
        if y1 < 0:
            y2 += y1
            y1 = 0
        elif y2 > image.shape[0]:
            y1 += y2 - image.shape[0]
            y2 = image.shape[0]
        image = image[y1:y2, x1:x2]
        convertedImage = self.convert_frame_to_image(image)
        painter = QPainter(self)
        painter.fillRect(self.rect(), QColor("black"))
        painter.drawImage(self.rect().center() - convertedImage.rect().center(), convertedImage)

    def wheelEvent(self, event):
        modifiers = QGuiApplication.keyboardModifiers()
        if modifiers == Qt.ControlModifier:
            delta = event.angleDelta().y()
            if delta > 0:
                self.zoom_factor *= 1.1  # Increase zoom factor
            else:
                self.zoom_factor /= 1.1  # Decrease zoom factor
            if self.zoom_factor < 1.0:
                self.zoom_factor = 1.0
            if self.zoom_factor > 10.0:
                self.zoom_factor = 10.0
            observer.update("zoom", self.zoom_factor)
            self.update()

    def convert_frame_to_image(self, frame):
        height, width, channel = frame.shape
        bytes_per_line = channel * width
        q_image = QImage(np.ascontiguousarray(frame.data), width, height, bytes_per_line, QImage.Format_RGB888)
        q_image = q_image.scaledToHeight(self.height())
        return q_image.rgbSwapped()

    def changeVideoCapture(self, videoLoaded):
        self.video_capture.release()
        if videoLoaded:
            self.timer.timeout.disconnect()
            self.timer.timeout.connect(self.loadNextRecordedFrame)
            observer.update("videoLength", len(self.recordedFrames[0]))
            observer.update("isPlaying", False)
            self.toStart()
        else:
            self.timer.timeout.disconnect()
            self.timer.timeout.connect(self.loadNextLiveFrame)
            self.timer.start(33)
            self.video_capture = cv2.VideoCapture(observer.get('cameraId'))

    def playLoadedVideo(self, isPlaying):
        if not observer.get("videoLoaded"): return
        if isPlaying:
            if observer.get("isAtEnd"): self.toStart()
            observerIndex = observer.register("isAtEnd",
                lambda isAtEnd: (observer.update("isPlaying",False),
                                 observer.unregister("isAtEnd",observerIndex))
                                 if isAtEnd else None)
            self.timer.start(self.recordedFrames[1][observer.get("framePosition")])
        else:
            self.timer.stop()

    def previousFrame(self):
        if not observer.get("videoLoaded"): return
        observer.update("framePosition", observer.get("framePosition") - 2)
        self.loadNextRecordedFrame()

    def nextFrame(self):
        if not observer.get("videoLoaded"): return
        self.loadNextRecordedFrame()

    def toStart(self):
        if not observer.get("videoLoaded"): return
        observer.update("framePosition", -1)
        self.loadNextRecordedFrame()

    def toEnd(self):
        if not observer.get("videoLoaded"): return
        observer.update("framePosition", observer.get("videoLength")-2)
        self.loadNextRecordedFrame()

    def startRecord(self, record):
        if not record: return
        self.tmpRecordObserverIndex = None

        observer.update("checkIfSaved", (
            lambda self=self: (
                observer.update("videoLoaded", False) if observer.get("videoLoaded") else None,
                setattr(self, "prevFrameTime", None),
                setattr(self, "recordedFrames", [[],[]]),
                setattr(self, "recordFrame", self.saveFrame),
                setattr(self, "tmpRecordObserverIndex", observer.register("isRecording", lambda value: None if value else self.stopRecord(self.tmpRecordObserverIndex))),
            ),
            lambda: setattr(self, "tmpRecordObserverIndex", observer.register("isRecording", lambda value: (observer.update("isRecording", False),observer.unregister("isRecording", self.tmpRecordObserverIndex)) if value else None)),
        ))

    def stopRecord(self, observerIndex):
        observer.unregister("isRecording", observerIndex)
        observer.update("loadedFrames", self.recordedFrames)
        self.recordFrame = lambda _: None
        self.faceLandmarks = utils.faceMeshProcess(self.recordedFrames[0])
        observer.update("faceLandmarks", self.faceLandmarks)
        observer.update("videoLoaded", True)

    def loadNextLiveFrame(self):
        if not self.video_capture.isOpened():
            frame = cv2.imread("resources/no_video_source.png")
        else :
            ret, frame = self.video_capture.read()
            if not ret:
                frame = cv2.imread("resources/no_video_source.png")
            else :
                frame = cv2.flip(frame, 1)
        self.currentFrame = frame
        observer.update("framePosition", 0)
        self.recordFrame(frame)
        self.update()

    def loadNextRecordedFrame(self):
        framePosition = observer.get("framePosition")+1
        self.currentFrame = self.recordedFrames[0][framePosition]
        observer.update("framePosition", framePosition)
        if observer.get("isPlaying"): self.timer.start(self.recordedFrames[1][framePosition])
        self.update()

    def saveFrame(self, frame):
        currentTime = time.time()
        interval = (currentTime - self.prevFrameTime if self.prevFrameTime else 0)*1000
        self.prevFrameTime = currentTime
        self.recordedFrames[0].append(frame)
        self.recordedFrames[1].append(interval)

    def mouthTracking(self,framePosition):
        h,w = self.currentFrame.shape[:2]
        if observer.get("mouthTracking") and self.faceLandmarks[framePosition][0][0]:
            x1 = self.faceLandmarks[framePosition][61][0]*w
            x2 = self.faceLandmarks[framePosition][291][0]*w
            y1 = self.faceLandmarks[framePosition][0][1]*h
            y2 = self.faceLandmarks[framePosition][17][1]*h
            self.imageCenter = (int((x1 + x2)/2), int((y1 + y2)/2))
        else:
            self.imageCenter = (int(w/2), int(h/2))

    def liveResult(self):
        while not observer.get("videoLoaded") and not self.stopThread:
            results = self.face_mesh.process(self.currentFrame).multi_face_landmarks
            nbLandmarks = max([num for tup in mp_face_mesh_connections.FACEMESH_TESSELATION for num in tup])
            self.faceLandmarks[0] = [[l.x,l.y,l.z] for l in results[0].landmark] if results else [[None,None,None]]*nbLandmarks
            observer.update("faceLandmarks", self.faceLandmarks)

    def drawLandmarks(self,image):
        face_landmarks = self.faceLandmarks[observer.get("framePosition")]
        if not face_landmarks: return
        for landmark in face_landmarks:
            x,y,_ = landmark
            if x and y:
                x = int(landmark[0] * image.shape[1])
                y = int(landmark[1] * image.shape[0])
            cv2.circle(image, (x, y), 1, (200, 200, 200), -1)

    def updateStartEndObserver(self, pos):
        IsAtStart, isAtEnd = pos == 0, pos == observer.get("videoLength")-1
        if IsAtStart != observer.get("isAtStart") :
            observer.update("isAtStart", IsAtStart)
        if isAtEnd != observer.get("isAtEnd"):
            observer.update("isAtEnd", isAtEnd)

class CameraSelector(QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.currentIndexChanged.connect(self.handle_webcam_selection)
        self.populate_webcam_list()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.populate_webcam_list()
        super().mousePressEvent(event)

    def populate_webcam_list(self):
        self.clear()
        num_webcams = 10  # Assuming a maximum of 10 webcams
        available_webcams = []

        for i in range(num_webcams):
            cap = cv2.VideoCapture(i)
            if cap.isOpened():
                available_webcams.append(i)
                cap.release()

        self.addItems([f"Camera {i}" for i in available_webcams] if len(available_webcams) > 0 else ["No camera detected"])

    def handle_webcam_selection(self, index):
        observer.update('cameraId', index)


from __future__ import (absolute_import, division, print_function)

class ExpIniFileLoader(object):

    metadata = None

    def __init__(self, full_file_name=None):
        self.full_file_name = full_file_name
        self._retrieve_metadata()

    def _retrieve_metadata(self):
        _metadata = {}

        f = open(self.full_file_name, 'r')
        _file_contain = f.read()
        _file_array = _file_contain.split('\n')
        for _entry in _file_array:
            if not(_entry.strip() == ""):
                [key, value] = self.isolate_key_value(_entry)
                _metadata[key] = value

        self.metadata = _metadata

    def isolate_key_value(self, entry):
        _line_array = entry.split(' ')
        if len(_line_array) > 1:
            return [_line_array[0], _line_array[1]]


# 1. 입력조건
# 첫째줄에 n(1 <= n <= 100,000)과 k(1 <= n <= 100,000)가 공백을 기준으로 하여 각각 자연수로 주어진다.

# 2. 출력조건
# 첫째 줄에 N이 1이 될 때까지 1번 혹은 2번의 과정을 수행해야 하는 횟수의 최솟값을 출력한다.

# n, K를 공백을 기준으로 구분하여 입력 받기
n, k = map(int, input().split())

result = 0

while True:
    # n이 k로 나누어 떨어지는 수가 될 때까지 빼기
    target = (n // k) * k
    result += n - target
    n = target
    # n이 k보다 작을 때(더 이상 나눌 수 없을 때) 반복문 탈출
    if n < k:
        break
    # k로 나누기
    result += 1
    n //= k

# 마지막으로 남은 수에 대하여 1씩 빼기
result += (n - 1)
print(result)


import os
import pickle
from os.path import join as pathjoin

"""
Functions that handle the Custom Attributes extension.

For SpreadSheet-based CustomAttributes, OpenCount assumes that the input
spreadsheetpaths are .csv-like files of the form:

in, out
in_0, out_0
in_1, out_1
...
in_N, out_N

"""

"""
Output files:

<projdir>/custom_attrs.p

A list of marshall'd custom_attributes (i.e. dictionaries):
  [m_custattr_i, ... ]
"""

TYPE_CATTR = 'cattr'
TYPE_SPREADSHEET = 'spreadsheet'
TYPE_FILENAME = 'filename'

class CustomAttribute(object):

    def __init__(self, attrname,
                 is_tabulationonly=False):
        """
        str attrname:
        bool is_tabulationonly:
        """
        self.attrname = attrname
        self.is_tabulationonly = is_tabulationonly

    def marshall(self):
        return {'attrname': self.attrname, 'is_tabulationonly': self.is_tabulationonly,
                'type': TYPE_CATTR}

class Spreadsheet_Attr(CustomAttribute):

    def __init__(self, attrname, sspath, attrin, is_tabulationonly):
        CustomAttribute.__init__(self, attrname, is_tabulationonly)
        self.sspath = sspath
        self.attrin = attrin

    def marshall(self):
        dct = CustomAttribute.marshall(self)
        dct['sspath'] = self.sspath
        dct['attrin'] = self.attrin
        dct['type'] = TYPE_SPREADSHEET
        return dct

class Filename_Attr(CustomAttribute):

    def __init__(self, attrname, filename_regex, is_tabulationonly):
        CustomAttribute.__init__(self, attrname, is_tabulationonly)
        self.filename_regex = filename_regex

    def marshall(self):
        dct = CustomAttribute.marshall(self)
        dct['filename_regex'] = self.filename_regex
        dct['type'] = TYPE_FILENAME
        return dct

def load_custom_attrs(proj):
    """ Returns the custom_attrs data structure if it exists, or None
    if it doesn't exist yet.
    Input:
      obj project
    Output:
      list of CustomAttribute instances
    """
    path = pathjoin(proj.projdir_path, proj.custom_attrs)
    if not os.path.exists(path):
        return None
    marshalled = pickle.load(open(path, 'rb'))
    return [unmarshall_cust_attr(m) for m in marshalled]


import streamlit as st
from mainPage import switch_page, hide_sidebar
from database import get_user_info
from emailGenerator import email_gen

hide_sidebar()

st.image('icon.png', width = 210)
st.header('Verify Your Email')
st.caption(f"Check {variable(0)} for an email containing a verification code from getoutauthentication@gmail.com. If you haven't recieved an email within 5 minutes, reload the page.")

with st.form('email_verification'):
   email_verification = st.text_input('Verification Code')
   submitted = st.form_submit_button('Submit')

#print(email_gen(user_email))
   if submitted:
      if (email_gen(variable(0)) == int(email_verification)):
         switch_page('interface')
      else:
         st.write("The wrong code was entered. Please verify you've copied the code from the email exactly and try again.")


from collections import defaultdict

class Solution:
    def threeSum(self, nums):  # 超时
        res = set()
        nums_dict = defaultdict(list)
        for i, v in enumerate(nums):
            nums_dict[v].append(i)

        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if -(nums[i] + nums[j]) in nums_dict:
                    # 如果这个值的index与i,j不同
                    index_list = nums_dict[-(nums[i] + nums[j])]
                    for index in index_list:
                        if index != i and index != j:
                            three_num = tuple(sorted([nums[i], nums[j], nums[index]]))
                            # print(three_num)
                            # 判断三个数是否存在
                            res.add(three_num)
                            break

        return [list(item) for item in res]

    def threeSum1(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        '''先对数组进行排序， 然后按照左右指针的方法， 找到对应的解'''
        nums.sort()
        self.ans = []
        left, right = 0, len(nums) - 1
        for a in range(len(nums) - 2):
            # 前一个和它相等就重复了
            if a > 0 and nums[a - 1] == nums[a]:
                continue

            left = a + 1
            self.sumTwo(nums, left, right, -nums[a])

        return self.ans

    def sumTwo(self, nums, left, right, target):
        while left < right:
            summation = nums[left] + nums[right]
            if summation == target:
                self.ans.append((-target, nums[left], nums[right]))

                left, right = left + 1, right - 1
                # 如果和前一个一样，就重复了， 相同数字的判断只需要一次
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
            elif summation < target:
                left += 1
            else:
                right -= 1

if __name__ == '__main__':
    nums = [-1, 0, 1, 2, -1, -4]
    solution = Solution()
    res = solution.threeSum1(nums)
    print(res)


import numpy as np
import statsmodels.api as sm
import pandas as pd
import json

df = pd.read_csv("2017_utilization_reduced.csv.gz", dtype={"nppes_provider_zip": str})

df = df.loc[df.nppes_entity_code=="I", :]

# Include this as a covariate to proxy for practice size
df["total_npi_cnt"] = df.groupby("npi")["line_srvc_cnt"].transform(np.sum)
df["log_total_npi_cnt"] = np.log(df.total_npi_cnt)

# Include this as a covariate to proxy for zip code attributes
# related to population demographics
df["total_zip_cnt"] = df.groupby("nppes_provider_zip")["line_srvc_cnt"].transform(np.sum)
df["log_total_zip_cnt"] = np.log(df.total_zip_cnt)

fml = [
    "line_srvc_cnt ~ provider_type + log_total_npi_cnt + log_total_zip_cnt",
    "line_srvc_cnt ~ nppes_provider_state + log_total_npi_cnt + log_total_zip_cnt",
    "line_srvc_cnt ~ provider_type + nppes_provider_state + log_total_npi_cnt + log_total_zip_cnt"
]

with open("hcpcs_description.json") as fr:
    hcpcs = json.load(fr)

scale = []
icc = []
codes = []

mx = 2

for code, dg in df.groupby("hcpcs_code"):

    # Focus on the most common codes
    if dg.shape[0] < 25000:
        continue

    codes.append(code)
    print(code)

    model = sm.GEE.from_formula(fml[mx], family=sm.families.Poisson(), groups="nppes_provider_zip",
        cov_struct=sm.cov_struct.Exchangeable(), data=dg)
    result = model.fit(maxiter=1, first_dep_update=0)

    # Estimate the scale parameter as if this were a quasi-Poisson model
    scale.append(np.mean(result.resid_pearson**2))

    icc.append(result.cov_struct.dep_params)

hd = [hcpcs[c] for c in codes]

rslt = pd.DataFrame({"code": codes, "icc": icc, "scale": scale, "description": hd})
rslt = rslt.sort_values(by="icc")
rslt.to_csv("model.csv", index=None)


from tkinter import Button, Canvas, Entry, Frame, Label, Scrollbar
from tkinter.filedialog import askopenfilename
from tkinterdnd2 import DND_FILES

# Värvid, fondid
FRAME_BG = 'lightgrey'
ACTIVE_BG = 'black'
ACTIVE_FG = 'white'
HEADER_FONT = 'Calibri', 64, 'bold', 'underline'
LARGE_FONT = 'Calibri', 48
SMALL_FONT = 'Calibri', 24
SMALL_FONT_BOLD = 'Calibri', 24, 'bold'

def drop_file(event, entry):
        """
        Drag and drop

        event : Tkinter Event object that provides a file path string
        entry : Tkinter Entry object in which to insert the file path string
        """
        entry.delete(0, 'end')
        entry.insert(0, event.data)

class Question:
    def __init__(self, gui):
        """
        Widgetid mis tuleb luua kui andmeid sisestatakse

        """
        # Jätame meelde kas küsimusele vastata õieti
        self.is_correct = False
        self.is_correct_arr = []
        self.updated_in_session = False
        self.is_revealed = False

        # Defineerime parent scrollframe'i ja raami borderi
        self.gui = gui
        self.scrollframe = gui.question_scrollframe
        self.frame = Frame(self.scrollframe, bd='1', relief='solid')

        # Labels
        self.question_label = Label(self.frame, font=SMALL_FONT, text='Küsimus:')
        self.answer_label = Label(self.frame, font=SMALL_FONT, text='Vastus:')
        self.image_label = Label(self.frame, font=SMALL_FONT, text='Pilt:')

        # Entries
        self.question_entry = Entry(self.frame, font=SMALL_FONT)
        self.answer_entry = Entry(self.frame, font=SMALL_FONT)
        self.image_entry = Entry(self.frame, font=SMALL_FONT)

        # Nupud
        self.choose_button = Button(self.frame, bd=3, font=SMALL_FONT, text='Vali pilt...', command=self.select_image)
        self.remove_button = Button(self.frame, bd=3, font=SMALL_FONT_BOLD, text='X', command=self.remove, width=4)

        # Widgetid ekraanile
        self.frame.pack(side='top', fill='x')
        self.question_label.pack(side='left', padx=5)
        self.question_entry.pack(side='left', padx=5)
        self.answer_label.pack(side='left', padx=5)
        self.answer_entry.pack(side='left', padx=5)
        self.image_label.pack(side='left', padx=5)
        self.image_entry.pack(side='left', padx=5)
        self.choose_button.pack(side='left', padx=5)
        self.remove_button.pack(side='left', padx=5)

        # Drag ja drop failidele
        self.image_entry.drop_target_register(DND_FILES)
        self.image_entry.dnd_bind('<<Drop>>', lambda event: drop_file(event, self.image_entry))

    def select_image(self):
        #"Vali pilt" nupu funktsioon

        filename = askopenfilename(filetypes=[('PNG Files', '*.png'), ('JPG Files', '*.jpg')])
        if filename != '':
            self.image_entry.delete(0, 'end')
            self.image_entry.insert(0, filename)
            self.image_entry.xview_moveto(1)

    def remove(self):
        #Küsimuse eemaldamise (X) nupp.

        self.frame.destroy()
        self.scrollframe.update()
        self.gui.questions.remove(self)

class ScrollFrame(Frame):
    def __init__(self, frame):
        #Skrollitav frame widget
        self.scrollbar = Scrollbar(frame, width=24, bg=FRAME_BG)
        self.scrollbar.pack(side='right', fill='y', expand=False)

        self.canvas = Canvas(frame, yscrollcommand=self.scrollbar.set, bg=FRAME_BG)
        self.canvas.pack(side='bottom', fill='both', expand=True, padx=5, pady=5)

        self.scrollbar.configure(command=self.canvas.yview)
        self.canvas.bind('<Configure>', self.fill_canvas)
        self.canvas.bind('<Destroy>', lambda _: self.canvas.unbind_all('<MouseWheel>'))
        self.canvas.bind_all('<MouseWheel>', self.on_mousewheel)

        Frame.__init__(self, frame, bd=2, relief='solid', bg=FRAME_BG)
        self.windows_item = self.canvas.create_window(0, 0, window=self, anchor='nw')

    def on_mousewheel(self, event):
        """
        Hiirenupuga saab skrollida

        event : Tkinter MouseWheel event
        """
        self.canvas.yview_scroll(int(-1*(event.delta/120)), 'units')

    def fill_canvas(self, event):
        """
        Kohanda canvas laiust

        event : Tkinter Configure event
        """
        canvas_width = event.width
        self.canvas.itemconfig(self.windows_item, width=canvas_width)

    def update(self):
        self.update_idletasks()
        self.canvas.configure(scrollregion=self.canvas.bbox(self.windows_item))


#!/bin/python
#usage: python GO_occurrences.py [file to be parsed]
#will print how many times each GO term is in a file

#need sys to pass user inputs to script
import sys

#need csv to read in the tab-delimited file
import csv

#load inputs as an argument
input = sys.argv

#open file and make it a list of lists
with open(input[1]) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
lines = [x.strip() for x in content]

#GO_numbers will be a dictionary that contains GO terms as keys and the number of times that GO term is in the file as the value

GO_numbers = {}

for line in lines:
    #if the GO term is not in GO_numbers yet
    if line not in GO_numbers:
        #add that GO term to GO_numbers and set its value to 1
        GO_numbers[line] = 1
    #if that GO term is in GO_numbers and its value is 1
    else:
        #add one to that value
        GO_numbers[line] += 1

for i in GO_numbers:
    print(i + '\t' + str(GO_numbers[i]))

Gene family expansions and contractions in section Fumigati/GO_occurrences.py


class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        slow, fast=0,0
        while fast < len(nums):
            if nums[fast] != val:
                nums[slow] = nums[fast]
                slow += 1
            fast += 1
        return slow

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        while i < len(nums):
            if nums[i] == val:
                nums[i], nums[-1] = nums[-1],nums[i]
                nums.pop()
            else:
                i += 1
        return i


from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import tensorflow as tf
import pickle
import numpy as np
import pandas as pd
from anytree import AnyNode
from scipy.special import softmax
from tqdm.auto import tqdm

from dph.core.evaluation.metrics import global_accuracy, global_measures, hierarchical_measures
from dph.core.parameters.parameters import Parameters
from dph.utils.saver import Saver

class Evaluator:

    @staticmethod
    def evaluate(saver: Saver,
                 split: str,
                 labels: list,
                 model: tf.keras.Model,
                 test_dataset: tf.data.Dataset,
                 hierarchy: AnyNode,
                 p: Parameters):
        """
        Evaluates a model using the given test dataset and saves the results with help of the given saver object.

        :param saver: Saver object to save evaluation results
        :param split: split name
        :param labels: Labels
        :param model:
        :param test_dataset:
        :param hierarchy: Hierarchy structure for evaluation
        :param p:
        """
        evaluation = {}
        confusion_matrices = pd.ExcelWriter(saver.log_dir + f'/confusion_matrices_{split}.xlsx')

        test_dataset = test_dataset.batch(p.batch_size_val)

        # Predict dataset
        level_predictions = model.predict(test_dataset.map(lambda inputs, _: inputs))[0]
        level_predictions = [(levels, predictions) for levels, predictions in level_predictions.items()]
        level_predictions = sorted(level_predictions, key=lambda levels: levels[0])  # sort by levels

        # Save Confusion Matrix
        pickle.dump(level_predictions, open(saver.log_dir + f'/level_predictions{split}.p', 'wb'))

        y_pred, y_pred_orig = Evaluator.calculate_y_pred(hierarchy, labels, level_predictions)

        # Calculate y_true and loss
        y_true = {}
        loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
        losses = {}
        for level_num, level_prediction in enumerate(level_predictions):
            y_true_one_hot = list(test_dataset.unbatch().map(lambda _, l: l[level_num]))
            losses[level_num] = loss_object(y_true_one_hot, level_predictions[level_num][1])
            y_true[level_num] = [labels[level_num][int(np.argmax(one_hot))] if np.sum(one_hot) > 0 else 'nan'
                                 for one_hot in y_true_one_hot]

        try:
            # Per-Level metrics
            for level_num, level_prediction in enumerate(level_predictions):
                cm = pd.DataFrame(confusion_matrix(y_true[level_num], y_pred[level_num], labels[level_num]),
                                  index=labels[level_num],
                                  columns=labels[level_num])
                cm.to_excel(confusion_matrices, sheet_name="level_" + str(level_prediction[0]))

                # Calculate Accuracy to validate used predictions
                metrics = {
                    "loss": float(losses[level_num]),
                    "accuracy": float(accuracy_score(y_true[level_num], y_pred[level_num])),
                    "accuracy_orig": float(accuracy_score(y_true[level_num], y_pred_orig[level_num])),
                    "weighted_precision": float(
                        precision_score(y_true[level_num], y_pred[level_num], average='weighted')),
                    "weighted_precision_orig": float(
                        precision_score(y_true[level_num], y_pred_orig[level_num], average='weighted')),
                    "weighted_recall": float(recall_score(y_true[level_num], y_pred[level_num], average='weighted')),
                    "weighted_recall_orig": float(
                        recall_score(y_true[level_num], y_pred_orig[level_num], average='weighted')),
                    "weighted_f1": float(f1_score(y_true[level_num], y_pred[level_num], average='weighted')),
                    "weighted_f1_orig": float(f1_score(y_true[level_num], y_pred_orig[level_num], average='weighted'))
                }

                evaluation["level_" + str(level_prediction[0])] = metrics

            # Global Metrics
            evaluation["loss"] = float(sum(losses.values()))
            evaluation["global_accuracy"] = global_accuracy(y_true, y_pred)
            evaluation["global_measures_weighted"] = global_measures(y_true, y_pred, 'weighted')
            evaluation["global_measures_macro"] = global_measures(y_true, y_pred, 'macro')
            evaluation["hierarchical_measures"] = hierarchical_measures(hierarchy, y_true, y_pred)
        except ValueError:
            pass

        tf.print(evaluation)
        saver.save_dict(evaluation, f"metrics_{split}")
        confusion_matrices.save()

    @staticmethod
    def calculate_y_pred(hierarchy, labels, level_predictions):
        # Calculate y_pred with Postprocessing
        y_pred = dict([(level_num, []) for level_num, _ in enumerate(level_predictions)])
        nan_node = AnyNode(id='nan')
        level_softmaxs = [(level_prediction[0], [softmax(logits) for logits in level_prediction[1]])
                          for level_prediction in level_predictions]
        for idx in tqdm(range(len(level_softmaxs[0][1]))):
            def get_best_node(parent, level_softmaxs_slice, depth, probability=1):
                level_num = depth - len(level_softmaxs_slice)
                level_softmax = level_softmaxs_slice[0][1]

                # Find possible children
                children_dict = dict([(child.id, child) for child in parent.children])
                if "nan" in labels[level_num]:
                    children_dict['nan'] = nan_node

                # Find indices of possible children
                indices_by_idd = dict([(idd, index) for index, idd in enumerate(labels[level_num])])
                indices_possible = np.array(
                    [indices_by_idd[idd] for idd in sorted(children_dict.keys())])
                # Find child with highest probability
                best_indices = indices_possible[np.argsort(level_softmax[idx][indices_possible])]
                y_pred_idx_best, y_pred_idx_prob_best = nan_node, 0

                if len(level_softmaxs_slice) == 1:
                    # recursion base case
                    y_pred_idx_best = children_dict[labels[level_num][best_indices[-1]]]
                    y_pred_idx_prob_best = level_softmax[idx][best_indices[-1]]
                else:
                    for i in range(min(len(children_dict), 10)):
                        y_pred_idx_cand = children_dict[labels[level_num][best_indices[-i]]]
                        y_pred_idx_prob_cand = level_softmax[idx][best_indices[-i]]
                        y_pred_idx_cand, y_pred_idx_prob_cand \
                            = get_best_node(y_pred_idx_cand, level_softmaxs_slice[1:], depth,
                                            y_pred_idx_prob_cand)

                        if y_pred_idx_prob_cand > y_pred_idx_prob_best:
                            y_pred_idx_best, y_pred_idx_prob_best = y_pred_idx_cand, y_pred_idx_prob_cand

                if y_pred_idx_best == nan_node:
                    y_pred_idx_best = parent
                return y_pred_idx_best, y_pred_idx_prob_best * probability

            y_pred_idx, _ = get_best_node(hierarchy, level_softmaxs, len(level_softmaxs))
            path = list(y_pred_idx.path)[1:]
            y_pred_list = [node.id for node in path]
            y_pred_list = y_pred_list + ['nan'] * (len(y_pred) - len(y_pred_list))

            for level_num in range(len(y_pred)):
                y_pred[level_num].append(y_pred_list[level_num])

        # calculate y_pred as it is put out by the classifier
        y_pred_orig = {}
        for level_num, level_prediction in enumerate(level_predictions):
            y_pred_orig[level_num] = [labels[level_num][i] for i in
                                      np.argmax(level_prediction[1], axis=1)]

        return y_pred, y_pred_orig


import flask
import os
import collections
import math
import datetime

import rib.config
import rib.app
import rib.exception
import rib.filter
import rib.utility

_ENTRY = \
    collections.namedtuple(
        '_ENTRY', [
            'filename',
            'rel_filepath',
            'mtime_phrase',
            'size_phrase',
        ])

@rib.app.APP.route("/image/browse", methods=['GET'])
def image_browse_get():
    rel_path = flask.request.args.get('path', '')

    if rel_path and rel_path[0] == '/':
        raise \
            rib.exception.HttpError(
                "Path must be relative to image-root or empty: [{}]".format(
                path))

    u = rib.utility.Utility()
    image_root_path = u.get_image_root()

    path = image_root_path

    rel_path = rel_path.rstrip('/')

    if rel_path != '':
        path += os.sep + rel_path

    if os.path.exists(path) is False:
        raise \
            rib.exception.HttpFilesystemSubjectDoesNotExistError(
                "Path does not exist in image-root: [{}]".format(rel_path))

    children = os.listdir(path)
    children = sorted(children)

    directories = []
    files = []

    f = rib.filter.Filter()
    u = rib.utility.Utility()

    len_ = len(image_root_path)

    for filename in children:
        filepath = os.path.join(path, filename)

        if f.include(filepath) is False:
            continue

        rel_filepath = filepath[len_ + 1:]

        s = os.stat(filepath)
        mtime_dt = datetime.datetime.fromtimestamp(s.st_mtime)

        if os.path.isdir(filepath) is True:
            e = _ENTRY(
                    rel_filepath=rel_filepath,
                    filename=filename,
                    mtime_phrase=mtime_dt.strftime(rib.config.LONG_TIMESTAMP_FORMAT),
                    size_phrase=None)

            directories.append(e)
        else:
            try:
                u.detect_image(filepath)
            except rib.utility.FileNotAnImageError:
                continue

            size_phrase = \
                '{:.1f}'.format(float(s.st_size) / 1024.0 / 1024.0)

            e = _ENTRY(
                    rel_filepath=rel_filepath,
                    filename=filename,
                    mtime_phrase=mtime_dt.strftime(rib.config.LONG_TIMESTAMP_FORMAT),
                    size_phrase=size_phrase)

            files.append(e)

    if path == '':
        parent_rel_path = None
    else:
        parent_rel_path = os.path.dirname(rel_path)

    context = {
        'parent_rel_path': parent_rel_path,
        'rel_path': rel_path,
        'files': files,
        'directories': directories,
    }

    content = \
        flask.render_template(
            'image/browse.html',
            **context)

    response = flask.make_response(content)
    response.headers['Content-Type'] = 'text/html'

    return response