from django.shortcuts import render, HttpResponse, Http404
from django.core.exceptions import ObjectDoesNotExist
from MainApp.models import Item

user = {
    "name": "Иван",
    "middle": "Петрович",
    "surname": "Сидоров",
}

#items = [
#    {"id": 1, "name": "Кросовки abibas", "quantity":5},
#    {"id": 2, "name": "Куртка кожанная", "quantity":2},
#    {"id": 3, "name": "Coca-cola 1 литр", "quantity":12},
#    {"id": 4, "name": "Картофель фри", "quantity":0},
#    {"id": 5, "name": "Кепка", "quantity":124},
#]

def main(request):
    return render(request, 'index.html')

def about(request):
    text = f"""
    Имя: {user['name']}

    Отчество: {user['middle']}

    Фамилия: {user['surname']}

    """
    return HttpResponse(text)

def show_item(request, id):
    try:
        current_item = Item.objects.get(id=id)
    except ObjectDoesNotExist:
        raise Http404
    context = {
        "item": current_item
    }
    return render(request, "item.html", context)

def items_list(request):
    items = Item.objects.all()
    context = {
        "items": items
    }
    return render(request, "items.html", context)


import requests

# if __name__ == '__main__':
    # url = "https://f.video.weibocdn.com/001xiVoKgx07M0ORpxH9010412004zkY0E010.mp4?label=mp4_ld&trans_finger=81b11b8c5ffb62d33ceb3244bdd17e7b&ori=0&ps=1BVp4ysnknHVZu&Expires=1619085090&ssig=%2BrGCkMHNS1&KID=unistore,video"
    # r = requests.get(url, stream=True)
    # with open('name.mp4', "wb") as mp4:
    #     for chunk in r.iter_content(chunk_size=1024 * 1024):
    #         if chunk:
    #             mp4.write(chunk)

def download_file(url):
 local_filename = url.split('/')[-1]

 r = requests.get(url, stream=True)
 with open("/Users/cy/Downloads/video_sipder/"+local_filename, 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)

if __name__ == '__main__':
    earl = "https://www.youtube.com/watch?v=DBYjZTdrJlA"
    download_file(earl)


# Written by Gerd Mund & Robert Logiewa

from flask import (
    render_template,
    abort,
    current_app as app,
    json,
    make_response,
)
from app.main import bp
from app.api import handlers
import pandas as pd
from app.models import (
    DataSet,
    DataSetSchema,
    FusionHypothesis,
    FusionHypothesisSchema,
    BirdMapping,
    BirdMappingSchema,
)
from app.main import plotFunction as plt
import time

@bp.route("/")
@bp.route("/index")
def index():
    """ Index page, contains general results """
    app.logger.info("Opening index page")

    app.logger.debug("Retrieving data from birds api endpoint")
    response = handlers.getBirds()

    # Make sure the api returned actual results
    if not response or response.status_code != 200 or not response.is_json:
        app.logger.warning("birds api endpoint failed")
        abort(500)

    app.logger.debug("Retrieve bird mappings from database")
    mq = BirdMapping.query.all()
    ms = BirdMappingSchema(many=True)
    m = ms.dump(mq).data

    app.logger.debug("Combine mappings and data")
    mapping = pd.DataFrame(m).set_index("id")
    amounts = pd.DataFrame(response.get_json(), index=["weight"]).T
    data = pd.concat([amounts, mapping], axis=1, sort=True).fillna(0).T

    app.logger.debug("Finalize data for index page")
    birds_data = json.loads(data.to_json(orient="columns"))
    return (render_template("index.html", birdsData=birds_data), 200)

@bp.route("birds/<string:id>")
def bird_details(id):
    """ Shows the details of a particular bird """

    # Get bird details from api
    response = handlers.getBirdDetails(id)
    if not response or response.status_code != 200 or not response.is_json:
        abort(500)

    details = response.get_json()
    sd = pd.Series(details)

    # Filter the data based on the bird id
    m = BirdMapping.query.filter_by(id=id).first()
    ms = BirdMappingSchema()
    mo = ms.dump(m).data
    sm = pd.Series(mo)

    # Finalize data for details page
    df = pd.concat([sd, sm], axis=0)
    j = json.loads(df.to_json(orient="columns"))

    plt.calcPlot(j)
    return render_template("details.html", bird=j, title=j["name"])

@bp.route("dump_database", methods=["GET"])
def dumpDatabase():
    """Dumps the entirety of the database to a json file that is then downloaded"""

    # Query all bird mappings
    m = BirdMapping.query.all()
    ms = BirdMappingSchema(many=True)
    mo = ms.dump(m).data

    # Query all bird data
    d = DataSet.query.all()
    ds = DataSetSchema(many=True)
    do = ds.dump(d).data

    # Query all hypotheses
    h = FusionHypothesis.query.all()
    dh = FusionHypothesisSchema(many=True)
    ho = dh.dump(h).data

    # Make output object
    content = {"raw_data": do, "hypotheses": ho,  "mappings": mo}

    # Convert to json and then present file to user
    response = make_response(json.dumps(content))
    response.mimetype = "application/json"
    response.headers[
        "Content-Disposition"
    ] = "attachment;filename=database.json"
    return response


T = int(input())
for tc in range(T):
    a = int(input())
    b = list(map(int, input().split()))

    for i in range(a - 1, 0, -1):
        for j in range(i):
            if b[j] > b[j + 1]:
                b[j], b[j + 1] = b[j + 1], b[j]

    print(f'#{tc+1} ', end='')
    print(*b)


from typing import List

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        if p == s: return [0]
        word = dict()
        substrings = dict()
        res = list()
        for c in p:
            word[c] = word.get(c, 0) + 1
        for i in range(len(s)):
            c = s[i]
            substrings[c] = substrings.get(c, 0) + 1
            if i >= len(p):
                c = s[i - len(p)]
                n = substrings.pop(c) - 1
                if n > 0: substrings[c] = n
            if word == substrings:
                res.append(i - len(p) + 1)
        return res


import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

class LinearRegression:
    def __init__(self, lr=0.001, n_iter=1000):
        """ Linear regression implementation

        Parameters
        ----------
        n_iter : int, optional (default=1000)
            The number of iterations to perform gradient descent.

        lr : float, optional (default=0.001)
            Determines the step size at each iteration while moving toward a minimum.

        """
        self.lr = lr
        self.n_iter = n_iter

    def fit(self, X_train, y_train):
        X_train, y_train = X_train.reshape([-1, X_train.shape[-1]]), y_train.reshape([-1])
        n_samples, n_features = X_train.shape[-2], X_train.shape[-1]
        self.weights = np.random.normal(0, 1, (n_features,))
        self.bias = np.random.normal(0, 1, (1,))

        for _ in range(self.n_iter):
            dw = X_train.T @ (2 * (X_train @ self.weights + self.bias - y_train)) / n_samples
            db = np.sum(2 * (X_train @ self.weights + self.bias - y_train)) / n_samples
            self.weights -= self.lr * dw
            self.bias -= self.lr * db

    def predict(self, X_test):
        return X_test @ self.weights + self.bias

    def evaluate(self, X_test, y_test, mode='mae'):
        if mode == 'mae':
            beta = 1
        elif mode == 'mse':
            beta = 2
        else:
            beta = 1
        beta = 1 if mode == 'mae' else 2
        return np.sum(np.abs(self.predict(X_test) - y_test) ** beta) / y_test.size

if __name__ == '__main__':
    X, y = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=1234)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)
    mean, std = np.mean(X_train, -2), np.std(X_train, -2)
    X_train = (X_train - mean) / (std + 0.00001)
    X_test = (X_test - mean) / (std + 0.00001)
    clf = LinearRegression()
    clf.fit(X_train, y_train)
    mae = clf.evaluate(X_test, y_test)
    print(f"MAE = {mae:.4f}")
    cmap = plt.get_cmap("viridis")
    fig = plt.figure(figsize=(8, 6))
    plt.scatter(X_train, y_train, color=cmap(0.9), s=10)
    plt.scatter(X_test, y_test, color=cmap(0.5), s=10)
    plt.plot(X_test, clf.predict(X_test), color="black", linewidth=2, label="Prediction")
    plt.show()


"""/**
 * @author [Jai Miles]
 * @email [jaimiles23@gmail.com]
 * @create date 2020-05-20 23:22:50
 * @modify date 2020-05-22 23:32:45
 * @desc [
    Data module for speed challenge. Contains data for:
    - General
    - Welcomes
    - Player personalized messages
    - Choosing difficulties
    - Timer
    - Completion
    - High score
    - Relatize Z-Score responses
 ]
 */
"""

##########
# General
##########

SC_DIFFICULTIES = (
    "normal",
    "hard",
    "advanced",
    "insane",
)

SC_DIFF_DICT = {
    "normal"    :   (0, 10),
    "hard"      :   (0, 12),
    "advanced"  :   (10, 20),
    "insane"    :   (20, 30)
}

MT_QUESTION_SYNS = (
    "questions",
    "problems",
    "times tables",
    "tables",
)

##########
# Welcomes
##########

MODE_NAME = "Speed Challenge!"

MS_SC_FIRST_WELCOME = f"Welcome to {MODE_NAME}"
MS_PURPOSE = "In this mode, you answer times tables as quickly as you can."
MS_HOW_SCORED = "I score you on how fast you answer my questions."

MMT_SC_FIRST_WELCOME = (
    MS_SC_FIRST_WELCOME,
    1.5,
    MS_PURPOSE,
    2,
    MS_HOW_SCORED,
)

MT_SHORT_WELCOME = (
    "Welcome back to",
    "Welcome to",
    "Let's start",
)
MTT_SHORT_WELCOME = (
    MT_SHORT_WELCOME,
    MODE_NAME,
)

MT_LONG_WELCOME = (
    "How quickly can you answer the ",
    "How fast can you solve the ",
)

MTT_LONG_WELCOME = (
    MT_SHORT_WELCOME,
    MODE_NAME,
    1,
    MT_LONG_WELCOME,
    MT_QUESTION_SYNS,
)

##########
# Player personalized messages
##########

MT_HIGH_SCORE = (
    "Your highscore in {} difficulty is {}.",
    "Your record in {} difficulty is {}.",
)

MT_AVERAGE_SCORE = (
    "In {} difficulty, you usually get {} .",
    "In {} difficulty, you often get around {}.",
)

MT_BEAT_IT = (
    "Let's beat that!",
    "Let's try and beat that!",
    "Let's set a new record!",

    "Can you beat it?",
    "Do you think you can beat that?",
)

##########
# Choose Difficulty
##########

MT_WHAT = (
    "What",
    "What",
    "Which",
)
MS_DIFFICULTY = "difficulty",
MT_ATTEMPT = (
    "should we play?",
    "do you want to play?",

    "should we try?",
    "do you want to try?",
)

MMT_WHAT_DIFFICULTY = (
    MT_WHAT,
    MS_DIFFICULTY,
    MT_ATTEMPT,
)

MT_CAN_USE = (
    "You can choose",
    "You can play",
)
MS_ONE_OF_FOLLOWING = "one of the following difficulties:"
MS_DIFF_LIST = "Normal, Hard, Advanced, or Insane."
MMT_CAN_USE_DIFF = (
    MT_CAN_USE,
    MS_ONE_OF_FOLLOWING,
    0.5,
    MS_DIFF_LIST
)

MS_GET_DIFF_HELP = "If you want to hear about each difficulty, ask me for help."

MT_USE = (
    "Let's use",
    "I'll set up",
    "Starting",
)
MS_DIFFICULTY_FORMAT = "{} difficulty."

MT_SORRY = (
    "Sorry,",
    "Sorry,",
    "I'm sorry,",
)
MT_NOT_REGISTER = (
    "I didn't catch that.",
    "I didn't hear you.",
    "I didn't get that.",
)
MT_RETRY = (
    "Please try again.",
    "Can you try again?",
)
MTT_TRY_AGAIN = (
    MT_SORRY,
    MT_NOT_REGISTER,
    1,
    MT_RETRY,
)

##########
# Timer
##########

MT_START_TIMER = (
    "Starting timer, now!",
    "Timer starting now!",
    "I'm starting the timer now!",
)

##########
# Completed Speed Challenge
##########

MT_COMPLETED_SC = (
    "You completed",
    "You finished",
    "You answered",
)

MS_SC_MINUTES_SECONDS_SCORE = "{} minutes and {} seconds"
MS_SC_SECONDS_SCORE = "{} seconds"

MS_FIN_SC_DIF_SEC = "{} difficulty in {}!"
MS_FIN_SC_NUMQ_SEC = "{} questions in {}!"
MS_FIN_SC_LOWTBL_UPPTBL_SEC = "my questions from the {} to {} times tables in {}!"

##########
# Speed Challenge High Score
##########
MS_FIRST_HS = "I'll set your highscore for {} difficulty as {}."

########## Beat highscore MTT
MS_YOU = "You"
MT_BEAT = (
    "beat",
    "passed",
)
MS_YOUR = "your"
MT_OLD_HS_SYNS = (
    "old highscore",
    "highscore",

    "old record",
    "record",
)
MS_OF = "of"
MTT_BEAT_OLD_HS = (
    MS_YOU,
    MT_BEAT,
    MS_YOUR,
    MT_OLD_HS_SYNS,
    MS_OF,
)       # format with seconds, & seconds
MS_SC_SCORE_SECONDS = "{}!"

########## New High score
MS_YOUR_NEW = "Your new"
MT_HS_SYNS = (
    "high score",
    "record",
    "personal record",
)
MS_FOR_DIFF_SECONDS = "for {} difficulty is {}."

MMT_NEW_HS = (
    MS_YOUR_NEW,
    MT_HS_SYNS,
)

########## Tied HS

MT_TIE_HS = (
    "You tied your highscore of {}!",
    "That ties your highscore of {}!",
    "{}? Ha! That's your high score!",
)
MT_TIE_HS_PART_2 = (
    "Close one!",
    "Set a new one next time!",
)

##########
# Relative Z-Score responses
##########

MT_BETTER_NEXT_TIME = (
    "Let's be even faster next time.",
    "Let's get even faster next time.",
    "We can do better next time.",
    "We'll be faster next time.",
)

MT_NORM_ATTEMPT = (
    "Keep practicing and get even faster.",
    "Good game.",
    "Nice game.",
)

MT_GOOD_ATTEMPT = (
    "That's faster than usual!",
    "You're definitely getting faster!",
    "You're getting faster at this!",
    "You're getting faster each time!",
    "You get faster each time!",
)

MT_AWESOME_ATTEMPT = (
    "You were really fast this time!",
    "You're on the way to setting a new record!",
    "You almost set a new record!",
    "Keep this up, and you'll set a new high score!",
)


# views.py
import pandas as pd
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render
from .models import BMSSENSOR
from .models import CsvOrExcelUpload
from .forms import FuturePredictionForm
from django.contrib.auth.decorators import login_required

@login_required
def energy_prediction(request, pk):
    user = request.user
    file_data = CsvOrExcelUpload.objects.get(id=pk, user=user)

    if request.method == 'POST':
        form = FuturePredictionForm(request.POST)
        if form.is_valid():
            future_date = form.cleaned_data['future_date']
            future_time = form.cleaned_data['future_time']
            future_datetime = datetime.combine(future_date, future_time)
            if file_data.upload_file.name.endswith(('.csv', '.xls', '.xlsx')):
                df = pd.read_csv(file_data.upload_file) if file_data.upload_file.name.endswith('.csv') else pd.read_excel(file_data.upload_file)

                # Calculate COST_PER_UNIT_LIGHTING, COST_PER_UNIT_HVAC, and COST_PER_UNIT_POWER_OUTLET
                cost_per_unit_lighting = calculate_cost_per_unit(df, 'General Lighting(W/m2)')
                cost_per_unit_hvac = calculate_cost_per_unit(df, 'Cooling (Electricity)(W/m2)')
                cost_per_unit_power_outlet = calculate_cost_per_unit(df, 'System Pumps(W/m2)')

                # Connect to the BMS to get power distribution information
                df = connect_to_bms(df, request, file_data)

                # Create a prediction DataFrame for the selected future date and time
                future_prediction_df = create_future_prediction_df(df, future_datetime)

                # Apply AI-based energy optimization logic to the future prediction data
                optimized_future_df = optimize_energy_ai(future_prediction_df.copy(), cost_per_unit_lighting, cost_per_unit_hvac, cost_per_unit_power_outlet)

                # Calculate energy cost for each zone in the future
                optimized_future_df = calculate_energy_cost(optimized_future_df)

                # Calculate total cost for all zones in the future
                total_future_cost = optimized_future_df[['zone1_cost', 'zone2_cost']].sum().sum()  # Adjust column names if needed

                # Create a line plot to visualize the future prediction
                plt.plot(future_prediction_df['Date/Time'], optimized_future_df['General Lighting(W/m2)'], label='Optimized Lighting(W/m2)')
                plt.xlabel('Date/Time')
                plt.ylabel('Energy Consumption(W/m2)')
                plt.title('Future Energy Cost Prediction')
                plt.xticks(rotation=45)
                plt.legend()

                # Save the plot to a BytesIO object
                img = BytesIO()
                plt.savefig(img, format='png')
                img.seek(0)
                img_base64 = base64.b64encode(img.read()).decode()

                # Pass the plot as a base64-encoded image to the template
                context = {
                    'form': form,
                    'plot_image': f'data:image/png;base64,{img_base64}',
                    'data_table': optimized_future_df.to_html(classes='table table-striped table-bordered table-hover'),
                    'total_cost': total_future_cost
                }

                return render(request, 'energy_prediction.html', context)
    else:
        form = FuturePredictionForm()

    context = {'form': form}
    return render(request, 'energy_prediction.html', context)

def calculate_cost_per_unit(data, column_name):
    # Calculate cost per unit for a given column (e.g., 'General Lighting(W/m2)')
    total_cost = data[column_name].sum()
    total_energy = data[column_name].count()
    return total_cost / total_energy if total_energy != 0 else 0.0

def connect_to_bms(data, request, file_data):
    # Placeholder logic to simulate BMS sensor data retrieval
    # You should replace this with actual data retrieval logic
    try:
        # Get BMS sensor data based on user and timestamp (placeholder)
        bms_sensor = BMSSENSOR.objects.get(user=request.user, timestamp=file_data.timestamp)
        bms_data = {
            'energy_level': bms_sensor.energy_level,
            'temperature': bms_sensor.temperature
        }

        # Update office_data with BMS data (placeholder)
        data.update(bms_data)

    except BMSSENSOR.DoesNotExist:
        # Handle the case where the BMSSENSOR with the specified user and timestamp does not exist
        print("BMSSENSOR does not exist.")
    except Exception as e:
        # Handle any other unexpected exceptions
        print(f"An error occurred: {str(e)}")

    return data

def optimize_energy_ai(data, cost_per_unit_lighting, cost_per_unit_hvac, cost_per_unit_power_outlet):
    # Placeholder logic for energy optimization (adjust as needed)
    for zone, columns in zone_data.items():
        occupancy_column = columns['occupancy_column']
        lighting_column = columns['lighting_column']
        power_outlet_column = columns['power_outlet_column']
        hvac_column = columns['hvac_column']

        data = adjust_lighting(data, occupancy_column, lighting_column, cost_per_unit_lighting)
        data = adjust_hvac(data, hvac_column, cost_per_unit_hvac)
        data = adjust_power_outlets(data, occupancy_column, power_outlet_column, cost_per_unit_power_outlet)

    return data

def calculate_energy_cost(data):
    # Placeholder logic to calculate energy cost for each zone (adjust as needed)
    for zone, columns in zone_data.items():
        lighting_column = columns['lighting_column']
        power_outlet_column = columns['power_outlet_column']
        hvac_column = columns['hvac_column']

        data[f'{zone}_cost'] = (
            data[lighting_column] +
            data[power_outlet_column] +
            data[hvac_column]
        )

    return data

# Define your 'zone_data' as you did before

# Define your BMSSENSOR model

# Define other helper functions (e.g., adjust_lighting, adjust_hvac, adjust_power_outlets) as you did before


"""Find the sum of the length of all recordings for each songwriter along with the songwriter's id."""

from pymongo import MongoClient
import sys
from pprint import pprint

client = MongoClient('localhost', int(sys.argv[1]))
db = client["A4dbEmbed"]
songwriters_recordings = db["SongwritersRecordings"]

aggregate = songwriters_recordings.aggregate([{"$unwind" : "$recordings"},
                                              {"$group" : {"_id": "$songwriter_id",
                                                           "total_length" : {"$sum" : "$recordings.length"},
                                                           "songwriter_id" : {"$first" : "$songwriter_id"}}}])

for entry in aggregate:
    pprint(entry)


"""
일렬로 서있는 소 2
"""
import sys

input = sys.stdin.readline

n = int(input())
ls = list(map(int, input().split()))
cnt = 0
for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if ls[i] <= ls[j] <= ls[k]:
                cnt += 1

print(cnt)


from socket import *
from time import time

REQUESTS_SENT = 10

def send_ping(i: int, client_socket: socket, hostname: str, port: int) -> float:
    send_time = time()
    client_socket.sendto(f'Ping {i} {send_time}'.encode(), (hostname, port))

    try:
        message, server_address = client_socket.recvfrom(2048)
        recv_time = time()

        # round trip time
        rtt = round((recv_time - send_time)*1000, 2)
        byte_count = len(message)
        print(f'{byte_count} bytes from {hostname}:{port}: udp_seq={i} time={rtt} ms')
        return rtt
    except timeout:
        print(f'Request timed out for udp_seq {i}')
        return float('inf')

hostname = 'localhost'
port = 3000
client_socket = socket(AF_INET, SOCK_DGRAM)
client_socket.settimeout(1.0)

print(f'PING {hostname}:{port}\n\n')

# keep rolling statistics
minimum = float('inf')
maximum = 0
total = 0
survived = 0

for i in range(1, REQUESTS_SENT + 1):
    rtt = send_ping(i, client_socket, hostname, port)
    if rtt != float('inf'):
        minimum = min(minimum, rtt)
        maximum = max(maximum, rtt)
        total += rtt
        survived += 1

average = round(total / survived, 2) if survived > 0 else float('inf')
packet_loss = round((REQUESTS_SENT - survived) / REQUESTS_SENT * 100, 0)

print(f'\n\n--- {hostname} ping statistics ---')
print(f'{REQUESTS_SENT} packets transmitted, {survived} received, {packet_loss}% packet loss')
if minimum != float('inf'):
    print(f'round-trip min/avg/max = {minimum}/{average}/{maximum} ms')


# -*- coding: utf-8 -*-
# Time       : 2019/2/23 1:43 PM
# Author     : tangdaye
# Description: leetcode solutions 51-60

"""
51. N皇后问题
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上，并且使皇后彼此之间不能相互攻击。
示例:
输入: 4
输出: [
 [".Q..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
"""

def question51(n):
    def queen(A, l, cur=0):
        if cur == n:
            l.append(A.copy())
            return 0
        for col in range(n):
            A[cur], flag = col, True
            for row in range(cur):
                if A[row] == col or abs(col - A[row]) == cur - row:
                    flag = False
                    break
            if flag:
                queen(A, l, cur + 1)

    l = []
    queen([None] * n, l, 0)
    result = []
    for solution in l:
        temp = []
        for t in solution:
            temp.append(t * '.' + 'Q' + (n - 1 - t) * '.')
        result.append(temp)
    return result

def question52(n):
    def queen(A, l, cur=0):
        if cur == n:
            l.append(A.copy())
            return 0
        for col in range(n):
            A[cur], flag = col, True
            for row in range(cur):
                if A[row] == col or abs(col - A[row]) == cur - row:
                    flag = False
                    break
            if flag:
                queen(A, l, cur + 1)

    l = []
    queen([None] * n, l, 0)
    return len(l)

"""
53. 最大子序和
给定一个整数数组 nums ，找到一个具有最大和的连续子数组（子数组最少包含一个元素），返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大，为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法，尝试使用更为精妙的分治法求解。
"""

def question53(nums):
    max_sum = -float("inf")
    last_max = 0
    for i in range(len(nums)):
        this_max = last_max + nums[i] if last_max > 0 else nums[i]
        last_max = this_max
        max_sum = max_sum if max_sum > this_max else this_max
    return max_sum

"""
54. 螺旋矩阵
给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
示例 1:
输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
"""

def question54(matrix):
    if not matrix:
        return []
    m, n = len(matrix), len(matrix[0])
    if m == 1:
        return matrix[0]
    if n == 1:
        return [row[0] for row in matrix]
    result = []
    times = m // 2 if m < n else n // 2
    i, j = 0, -1
    for i in range(times):
        next_i, next_j = 0, 1
        for _ in range(n):
            i, j = i + next_i, j + next_j
            result.append(matrix[i][j])
        next_i, next_j = 1, 0
        for _ in range(m - 1):
            i, j = i + next_i, j + next_j
            result.append(matrix[i][j])
        next_i, next_j = 0, -1
        for _ in range(n - 1):
            i, j = i + next_i, j + next_j
            result.append(matrix[i][j])
        for _ in range(m - 2):
            next_i, next_j = -1, 0
            i, j = i + next_i, j + next_j
            result.append(matrix[i][j])
        m, n = m - 2, n - 2
    if m == 1 and n == 1:
        result.append(matrix[i][j + 1])
    elif m == 1:
        for t in range(n):
            result.append(matrix[i][j + 1 + t])
    elif n == 1:
        for t in range(m):
            result.append(matrix[i + t][j + 1])
    return result

"""
55. 跳跃游戏
给定一个非负整数数组，你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。

示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。

示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样，你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 ， 所以你永远不可能到达最后一个位置。
"""

def question55(nums):
    length = len(nums)
    if length == 1:
        return True

    nums = nums[:-1]
    length -= 1
    i = length - 1
    while i >= 0:
        t = nums[i]
        if i + t >= length:
            nums = nums[:i]
            length = i
        i -= 1
    return len(nums) == 0

"""
56. 合并区间
给出一个区间的集合，请合并所有重叠的区间。

示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].

示例 2:
输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
"""

class Interval:
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

    def __str__(self):
        return '[%d,%d]' % (self.start, self.end)

def question56(intervals):
    def do_merge(result_map, interval, continue_flag=True):
        continue_flag = False
        for k, v in result_map.items():
            if k <= interval[0] <= interval[1] <= v:
                continue_flag = False
                break
            elif k <= interval[0] <= v <= interval[1]:
                result_map.pop(k)
                interval = [k, interval[1]]
                continue_flag = True
                break
            elif interval[0] <= k <= interval[1] <= v:
                result_map.pop(k)
                interval = [interval[0], v]
                continue_flag = True
                break
            elif interval[0] <= k <= v <= interval[1]:
                result_map.pop(k)
                continue_flag = True
                break
        if continue_flag:
            do_merge(result_map, interval, continue_flag)
        else:
            result_map[interval[0]] = interval[1]
            return

    result_map = {}
    result = []
    for interval in intervals:
        merge = 0
        for k, v in result_map.items():
            if k <= interval.start <= interval.end <= v:
                merge = 1
                break
            elif k <= interval.start <= v <= interval.end:
                merge = 2
                # result_map[k] = interval.end
                break
            elif interval.start <= k <= interval.end <= v:
                merge = 2
                # result_map.pop(k)
                # result_map[interval.start] = v
                break
            elif interval.start <= k <= v <= interval.end:
                merge = 2
                break
        if merge == 0:
            result_map[interval.start] = interval.end
        elif merge == 2:
            do_merge(result_map, [interval.start, interval.end])

    for k, v in result_map.items():
        result.append(Interval(k, v))
    return result

"""
57. 插入区间

给出一个无重叠的 ，按照区间起始端点排序的区间列表。
在列表中插入一个新的区间，你需要确保列表中的区间仍然有序且不重叠（如果有必要的话，可以合并区间）。

示例 1:
输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
输出: [[1,5],[6,9]]
"""

def question57(intervals, newInterval):
    def merge(intervals, newInterval):
        continue_index, continue_interval = 0, None
        for i, interval in enumerate(intervals):
            x1, x2, y1, y2 = interval.start, interval.end, newInterval.start, newInterval.end
            if x1 <= x2 < y1 <= y2:
                continue_index = i + 1
                continue_interval = None
            elif y1 <= y2 < x1 <= x2:
                continue_index = i
                continue_interval = None
                break
            elif x1 <= y1 <= y2 <= x2:
                continue_index = -1
                break
            elif x1 <= y1 <= x2 <= y2:
                continue_index = i
                continue_interval = Interval(x1, y2)
                break
            elif y1 <= x1 <= x2 <= y2:
                continue_index = i
                continue_interval = newInterval
                break
            elif y1 <= x1 <= y2 <= x2:
                continue_index = i
                continue_interval = Interval(y1, x2)
                break
        if continue_index >= 0 and continue_interval:
            intervals.pop(continue_index)
            merge(intervals, continue_interval)
        elif continue_index >= 0 and not continue_interval:
            intervals.insert(continue_index, newInterval)

    merge(intervals, newInterval)
    return intervals

"""
58. 最后一个单词的长度
给定一个仅包含大小写字母和空格 ' ' 的字符串，返回其最后一个单词的长度。
如果不存在最后一个单词，请返回 0 。

实例
输入: "Hello World"
输出: 5
"""

def question58(s):
    s = s.strip()
    if not s:
        return 0
    return len(s.split()[-1])

"""
59. 螺旋矩阵II
给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:
输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
"""

def question59(n):
    if not n:
        return []
    k = n - 1
    result = [[0] * n for _ in range(n)]
    num = 1
    while k >= 1:
        start_x, start_y = (n - k) // 2, (n - k) // 2
        end_x, end_y = n - 1 - (n - k) // 2, n - 1 - (n - k) // 2
        for i in range(4 * k):
            if i < k:
                result[start_x][start_y + i] = num
            elif i < 2 * k:
                result[start_x + i - k][end_y] = num
            elif i < 3 * k:
                result[end_x][end_y - (i - 2 * k)] = num
            elif i < 4 * k:
                result[end_x - (i - 3 * k)][start_y] = num
            num += 1
        k -= 2
    if k == 0:
        result[n // 2][n // 2] = num
    return result

"""
60. 第k个排列
给出集合 [1,2,3,…,n]，其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况，并一一标记，当 n = 3 时, 所有排列如下：
"123"
"132"
"213"
"231"
"312"
"321"
给定 n 和 k，返回第 k 个排列。
说明：
给定 n 的范围是 [1, 9]。
给定 k 的范围是[1,  n!]。
示例 1:
输入: n = 3, k = 3
输出: "213"
"""

def question60(n, k):
    if not n:
        return ""
    nums = list(range(1,n + 1))
    fa = [1] * (n + 1)
    s = ''
    for i in range(1, n + 1):
        fa[i] = fa[i - 1] * i
    i = n - 1
    while i >= 0:
        index = (k - 1) // fa[i]
        m = nums[index]
        s += str(m)
        k = k % fa[i]
        nums.remove(m)
        i -= 1
    return s

if __name__ == '__main__':
    x = question60(3, 6)
    print(x)


import argparse
import ast
import logging
logging.getLogger().setLevel(logging.DEBUG)
import io
import os
import pdb
import pprint
import pydoc
import random
import re
import signal
import subprocess
import sys
from time import tzset
import traceback

REAL_PRINT = print
REAL_PPRINT = pprint.pprint

class Flags(object):
    def __init__(self):
        self.parser = argparse.ArgumentParser(
            description='Rewrites a Markdown file by running the Python '
                        'code embedded within it.')
        self.parser.add_argument(
            '--overwrite',
            action='store_true',
            default=False,
            help='Overwrite the file in-place if its contents ran '
                 'successfully.')
        self.parser.add_argument(
            '--timeout_seconds',
            action='store',
            default=5,
            type=float,
            help='Kill the process with an error if the Python code in the '
                 'Markdown file hasn\'t finished executing in this time.')
        self.parser.add_argument(
            'path',
            action='store',
            default=None,
            nargs='+',
            help='Paths to the Markdown files to process.')
        self.parser.add_argument(
            '--root_dir',
            action='store',
            default='.',
            type=str,
            help='Path to the root directory of the book. Used to resolve '
                 '"python-include:" blocks in the source Markdown.')

    def parse(self):
        self.parser.parse_args(namespace=self)

FLAGS = Flags()

class MarkdownExecError(Exception):
    pass

class WrappedException(Exception):
    def __init__(self, output=None):
        super().__init__()
        self.output = output

def exec_source(path, source, context, raise_exceptions=False):
    output = io.StringIO()
    logging_handler = logging.StreamHandler(stream=output)

    def my_print(*args, **kwargs):
        kwargs['file'] = output
        REAL_PRINT(*args, **kwargs)

    def my_pprint(*args, **kwargs):
        kwargs['stream'] = output
        kwargs['width'] = 65  # Max width of monospace code lines in Word
        REAL_PPRINT(*args, **kwargs)

    def my_debug(*args, **kwargs):
        kwargs['file'] = sys.stderr
        REAL_PRINT(*args, **kwargs)

    def my_help(*args, **kwargs):
        helper = pydoc.Helper(output=output)
        return helper(*args, **kwargs)

    def my_pdb():
        # Clear any alarm clocks since we're going interactive.
        signal.alarm(0)

        p = pdb.Pdb(stdin=sys.stdin, stdout=sys.stderr)
        p.use_rawinput = True
        return p

    context['print'] = my_print
    context['pprint'] = my_pprint
    context['debug'] = my_debug
    context['help'] = my_help
    context['Pdb'] = my_pdb
    context['STDOUT'] = output
    logging.getLogger().addHandler(logging_handler)
    try:
        node = ast.parse(source, path)
        code = compile(node, path, 'exec')
        exec(code, context, context)
    except Exception as e:
        # Restore the print functions for other code in this module.
        context['print'] = REAL_PRINT

        # If there's been any output so far, print it out before the
        # error traceback is printed so we have context for debugging.
        output_so_far = output.getvalue()
        if output_so_far:
            print(output_so_far, end='', file=sys.stderr)

        if raise_exceptions:
            raise WrappedException(output_so_far) from e

        format_list = traceback.format_exception(*sys.exc_info())

        # Only show tracebacks for code that was in the target source file.
        # This way calls to parse(), compile(), and exec() are removed.
        cutoff = 0
        for cutoff, line in enumerate(format_list):
            if path in line:
                break

        formatted = ''.join(format_list[cutoff:])
        print('Traceback (most recent call last):', file=sys.stderr)
        print(formatted, end='', file=sys.stderr)
        raise MarkdownExecError(e)
    finally:
        # Restore the print function for other code in this module.
        context['print'] = REAL_PRINT
        # Disable the logging handler.
        logging.getLogger().removeHandler(logging_handler)

    return output.getvalue()

def exec_python2(source):
    source_bytes = source.encode('utf-8')
    output = subprocess.check_output(['python2.7'], input=source_bytes)
    return output.decode('utf-8')

def exec_syntax_error(source):
    source_bytes = source.encode('utf-8')
    child = subprocess.Popen(
        ['python3'],
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE)
    _, output = child.communicate(input=source_bytes)
    output = output.decode('utf-8')
    # Only return the last line. The preceeding lines will be parts of
    # the stack trace that caused the syntax error.
    return output.strip('\n').split('\n')[-1]

filename_re = re.compile('[\\.]{0,2}/[-a-zA-Z0-9_/]+(\\.py|\\.md)')

def exec_exception(path, source, context):
    try:
        exec_source(path, source, context,
                    raise_exceptions=True)
    except WrappedException as e:
        original = e.__context__
        pretty_exception = str(original)
        pretty_exception = filename_re.sub('my_code.py', pretty_exception)
        exception_line = '%s: %s' % (
            original.__class__.__name__, pretty_exception)

        if e.output:
            return '%sTraceback ...\n%s' % (
                e.output, exception_line)
        else:
            return exception_line
    else:
        assert False, 'Exception not raised'

def iterate_blocks(path, text):
    text_start = 0
    source_start = None
    block_suffix = ''
    pending_source = ''
    pending_output = ''

    # Import the __main__ module, which is this file, and run all of the
    # Markdown code as if it's part of that module. This enables modules
    # like pickle to work, which need to use import paths relative to named
    # modules in order to serialized/deserialize functions.
    import __main__
    context = __main__.__dict__

    for blocks_seen, match in enumerate(re.finditer('```', text)):
        start = match.start()
        end = match.end()

        if blocks_seen % 2 == 0:
            # Figure out the language of the opening block.
            suffix_end = text.find('\n', end)
            if suffix_end > 0:
                block_suffix = text[end:suffix_end].lower()
                source_start = end + len(block_suffix)

            # All text until the block start
            yield text[text_start:start]
        else:
            text_start = end
            source = text[source_start:start]

            # Closing block
            if block_suffix in ('python', 'python-exception'):
                # Run any pending source immediately if this is a Python
                # exception block to ensure we re-raise unexpected exceptions
                # back up instead of just printing them into output blocks.
                if block_suffix == 'python-exception':
                    if pending_source:
                        pending_output += exec_source(
                            path, pending_source, context)
                        pending_source = ''

                # Add a bunch of blank lines before the source to get the line
                # numbers to match up during ast.parse. The ast.increment_lineno
                # helper is useful, but only after parsing was successful. If
                # you want helpful error messages during parsing you need to
                # fake it.
                line_offset = text[:source_start].count('\n')
                delta_offset = line_offset - pending_source.count('\n')
                pending_source += '\n' * delta_offset

                # Accumulate all the source code to run until we reach the
                # first output block *or* the end of the file.
                pending_source += source

                yield '```%s' % block_suffix
                yield source
                yield '```'

                if block_suffix == 'python-exception':
                    pending_output += exec_exception(
                        path, pending_source, context)
                    pending_source = ''
            elif block_suffix == 'python2':
                yield '```python2'
                if not source.startswith('\n# Python 2'):
                    yield '\n# Python 2'
                yield source
                yield '```'

                pending_output += exec_python2(source)
            elif block_suffix == 'python-syntax-error':
                yield '```python-syntax-error'
                yield source
                yield '```'

                pending_output += exec_syntax_error(source)
            elif block_suffix.startswith('python-include:'):
                include_path = block_suffix[len('python-include:'):]
                file_basename = os.path.basename(include_path)
                full_path = os.path.join(FLAGS.root_dir, include_path)
                data = open(full_path, 'r').read()

                yield '```%s\n' % block_suffix
                yield '# %s\n' % file_basename
                yield data.strip()
                yield '\n```'
            else:
                if pending_source:
                    pending_output += exec_source(
                        path, pending_source, context)
                    pending_source = ''
                elif not pending_output:
                    # This handles random output blocks in the Markdown file
                    # that do not follow Python blocks. This is helpful when
                    # you're sketching out a rough draft. Just pass through
                    # whatever the field was before.
                    pending_output = source

                # Output block
                yield '```%s\n' % block_suffix
                yield pending_output.strip('\n')
                yield '\n```'

                pending_output = ''

    # What follows the very last block to the end of the file
    yield text[text_start:]

    # Run any remaining pending code to make sure it doesn't have errors.
    if pending_source:
        exec_source(path, pending_source, context)

def print_iter(it, path, overwrite):
    output = sys.stdout
    if overwrite:
        output = io.StringIO()
    try:
        for text in it:
            print(text, end='', file=output)
    except:
        raise
    else:
        if overwrite:
            open(path, 'w', encoding='utf-8').write(output.getvalue())

def main():
    FLAGS.parse()

    for path in FLAGS.path:
        # Always use the same seed so multiple runs of the same Markdown files
        # will always produce the same output results.
        random.seed(1234)

        # Always pretend that we're running in Pacific Time
        os.environ['TZ'] = 'US/Pacific'
        tzset()

        # Kill the process if it's been running for longer than the timeout.
        signal.alarm(FLAGS.timeout_seconds)

        text = open(path, encoding='utf-8').read()
        it = iterate_blocks(path, text)
        try:
            print_iter(it, path, FLAGS.overwrite)
        except MarkdownExecError:
            return 1

    return 0

if __name__ == '__main__':
    sys.exit(main())


def speak(text):
    import win32com.client as wincl
    speak1 = wincl.Dispatch("SAPI.SpVoice")
    if int(text) > 5:
        speak1.speak("Bester Mann hat ")
        speak1.speak(text)
        speak1.speak("eingetragen. ")
    else:
        speak1.speak("Zu wenige... SO EINEN HALS!!!! ")

def suche():
    import pyautogui
    import datetime
    import time
    from selenium.webdriver.chrome.options import Options
    from selenium.common.exceptions import NoSuchElementException
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium import webdriver
    from pymongo import MongoClient
    chrome_options = Options()

    # chrome_options.add_argument("--headless")
    driver = webdriver.Chrome(chrome_options=chrome_options)  # docker port anstatt lokal
    client = MongoClient("192.168.100.5", 27017, maxPoolSize=None)
    db2 = client['gemeinden']
    collection = db2['gemeinden']
    while True:
        cursor = collection.find({'telefon': {"$exists": False}, "zahl":"1"}, no_cursor_timeout=True, limit=1)
        a = collection.count({'telefon': {"$exists": False}, "zahl":"1"})
        print(a)
        for i in cursor:
            suchbegriff = i['Anschrift der Gemeinde']
            suchbegriff2 = i['Ort']
            suchbegriff3 = suchbegriff + " " + suchbegriff2 + " telefon"

            google_url = "https://www.google.de/search?q="
            google_url = google_url + suchbegriff3 + " impressum"
            driver.get(google_url)
            driver.switch_to.window(driver.window_handles[-1])
            print(suchbegriff, suchbegriff2)
            nummer = input("Bitte nummer eingeben\n\n")

            nummer = nummer.strip()
            if nummer:
                collection.update_many({'Anschrift der Gemeinde': i['Anschrift der Gemeinde'], 'Ort': i['Ort']}, {"$set": {'telefon': nummer}})
                ausgefuellt = a - collection.count({'telefon': {"$exists": False}})
                #	03 99 98 - 15 30speak(ausgefuellt)
                print(ausgefuellt, "Eingetragen.\n")
                print(collection.count({'telefon': {"$exists": False}}), "verbleibend.")

suche()


import bpy

from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator

import pathlib
import os
import re

ENUM_Axis = [("X","X","X"),("Y","Y","Y"),("Z","Z","Z"),("NEGATIVE_X","-X","-X"),("NEGATIVE_Y","-Y","-Y"),("NEGATIVE_Z","-Z","-Z")]

def recursive_collect_file_by_format(root_directory, format):

    collected_files = []
    items = os.walk(root_directory)

    for (path, directories, files) in items:
        for file in files:
            if file.endswith(".obj"):
                collected_files.append(path+"/"+file)

    return collected_files

ENUM_Filter_Mode = [("INCLUDE","Include","Include"),("EXCLUDE","Exclude","Exclude"), ("REGEX", "Regex", "Regex")]

class BATCHIMPORT_OT_Recursive_Import_OBJ(Operator):
    """Recursive Import OBJ"""
    bl_idname = "batch_import.recursive_import_obj"  # important since its how bpy.ops.import_test.some_data is constructed
    bl_label = "Batch Import OBJ"

    bl_options = {'UNDO', 'REGISTER'}
    # filename_ext = ".obj"
    # filename_ext = "."

    filter_glob: StringProperty(
        default="*.obj",
        options={'HIDDEN'},
        maxlen=255,  # Max internal buffer length, longer would be clamped.
    )

    directory: bpy.props.StringProperty()
    use_collection: bpy.props.BoolProperty(default=False, name="Use Collection")
    new_collection: bpy.props.BoolProperty(default=True, name="New Collection")
    collection_name: bpy.props.StringProperty(default="Import OBJ", name="Collection Name")
    file_name_as_collection: bpy.props.BoolProperty()

    filter_use: bpy.props.BoolProperty(default=False, name="Use Filter")
    filter_case_sensitive: bpy.props.BoolProperty(default=False, name="Case Sensitive")
    filter_text: bpy.props.StringProperty(name="Filter")
    filter_mode: bpy.props.EnumProperty(items=ENUM_Filter_Mode, name="Filter Mode")

    clamp_size: bpy.props.FloatProperty(default=0.0, min=0.0, name="Clamp Bounding")
    forward_axis: bpy.props.EnumProperty(default="X", items=ENUM_Axis, name="Axis Forward")
    up_axis: bpy.props.EnumProperty(default="Y", items=ENUM_Axis, name="Up")
    import_vertex_groups: bpy.props.BoolProperty(default=False, name="Vertex Groups")
    validate_meshes: bpy.props.BoolProperty(default=False, name="Validate Meshes")

    def invoke(self, context, event):

        if self.directory:
            self.collection_name = pathlib.Path(self.directory).stem
        else:
            self.collection_name = "Collection"

        context.window_manager.fileselect_add(self)
        return {"RUNNING_MODAL"}

    def draw(self, context):
        layout = self.layout

        box = layout.box()
        box.label(text="Batch Options", icon="MOD_ARRAY")

        box.label(text="Collection", icon="OUTLINER_COLLECTION")
        box.prop(self, "use_collection")
        if self.use_collection:
            row = box.row(align=True)
            if self.new_collection:
                row.prop(self, "collection_name", icon="OUTLINER_COLLECTION", text="")
            else:
                row.prop_search(self, "collection_name", bpy.data, "collections", icon="OUTLINER_COLLECTION", text="")

            row.prop(self, "new_collection", text="", icon="PLUS")
            box.prop(self, "file_name_as_collection", text="File Name As Collection", icon="CURRENT_FILE")

        box.separator()

        box.label(text="Filter", icon="FILTER")
        box.prop(self, "filter_use")

        if self.filter_use:
            col = box.column(align=True)
            row = col.row()
            row.prop(self, "filter_mode", expand=True)
            col.prop(self, "filter_text", text="", icon="FILTER")
            if self.filter_mode in ["INCLUDE", "EXCLUDE"]:
                box.prop(self, "filter_case_sensitive")

        box = layout.box()
        box.label(text="Transform", icon="OBJECT_DATA")

        box.prop(self, "clamp_size")
        box.prop(self, "forward_axis")
        box.prop(self, "up_axis")

        box = layout.box()
        box.label(text="Options", icon="EXPORT")
        box.prop(self, "import_vertex_groups")
        box.prop(self, "validate_meshes")

    def execute(self, context):

        files = recursive_collect_file_by_format(self.directory, ".obj")
        filtered_files = files

        original_objects = [object for object in bpy.data.objects]
        collection = None

        if self.filter_use:

            filtered_files = []

            for file in files:
                if self.filter_mode == "INCLUDE":

                    filename = os.path.basename(file)

                    if self.filter_case_sensitive:
                        if self.filter_text in filename:
                            filtered_files.append(file)
                    else:
                        if self.filter_text.lower() in filename.lower():
                            filtered_files.append(file)

                if self.filter_mode == "EXCLUDE":

                    if self.filter_case_sensitive:
                        if not self.filter_text in file:
                            filtered_files.append(file)
                    else:
                        if not self.filter_text.lower() in file.lower():
                            filtered_files.append(file)

                if self.filter_mode == "REGEX":
                    regex_match = bool(re.search(self.filter_text, file))
                    if regex_match:
                        filtered_files.append(file)

        self.report({"INFO"}, "Found " + str(len(filtered_files)) + " files ")
        print("Found " + str(len(filtered_files)) + " files")

        imported_files = {}

        for object in context.selected_objects:
            object.select_set(False)

        if self.use_collection:
            if len(filtered_files) > 0:
                collection = create_collection(self.collection_name, not self.new_collection, context.collection)

        for file in filtered_files:

            # imported_files[file] = list(context.selected_objects)

            print("Importing " + file)
            self.report({"INFO"}, "Importing" + file)
            bpy.ops.wm.obj_import(filepath=file, clamp_size=self.clamp_size, forward_axis=self.forward_axis, up_axis=self.up_axis, import_vertex_groups=self.import_vertex_groups, validate_meshes=self.validate_meshes)

            imported_object = [obj for obj in bpy.data.objects if obj not in original_objects]
            imported_files[file] = imported_object

            original_objects = list(bpy.data.objects)

            if self.use_collection:

                if collection:
                    move_objects_to_collection(imported_object, collection)

                    if self.file_name_as_collection:
                        file_collection = create_collection(os.path.relpath(file, self.directory), True, collection)
                        move_objects_to_collection(imported_object, file_collection)

        print("-----")
        print("Imported Objects: ")
        for file in imported_files:
            print("-----")
            print("    " + file)
            for obj in imported_files[file]:
                print("        " + obj.name)

        return {"FINISHED"}

def move_to_collection(obj, collection):

    for col in obj.users_collection:
        col.objects.unlink(obj)

    collection.objects.link(obj)

def move_objects_to_collection(objs, collection):

    for obj in objs:
        move_to_collection(obj, collection)

def create_collection(name, use_exist, parent_collection):

    context = bpy.context
    collection = None
    isNew = True

    if use_exist:
        collection = bpy.data.collections.get(name)
        isNew = False

    if not collection:
        collection = bpy.data.collections.new(name)
        isNew = True

    if isNew:
        if not parent_collection.get(collection.name):
            parent_collection.children.link(collection)

    return collection

classes = [BATCHIMPORT_OT_Recursive_Import_OBJ]

def register():

    for cls in classes:
        bpy.utils.register_class(cls)

    # bpy.types.TOPBAR_MT_file_import.append(menu_func_import)

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)

    # bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)

if __name__ == "__main__":
    register()


from flask import Flask, render_template, redirect, session, request
from user_model import User

app = Flask(__name__)
app.secret_key = "secret"

@app.route("/")
def root():
    return redirect("/users")

@app.route("/users")
def users():
    all_users = User.all_users() # returns a list of user objects
    return render_template("all.html", all_users = all_users)

@app.route("/users/new")
def users_new():
    return render_template("create.html")

@app.route("/user/create", methods=["post"])
def user_create():
    print(request.form)
    user_id = User.add_user(request.form)
    return redirect("/users")

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


from network_service.nbp_currency import NBPCurrency

class NBPModelMapper:
    def map_models(self, json_data):
        try:
            rates = json_data[0]['rates']
            models = []
            for rate in rates:
                models.append(NBPCurrency(rate['code'], rate['mid'], rate['currency']))

            return models
        except KeyError:
            return []


from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import MLMClient, MLMTransaction, get_or_create_mlm_config
from .utils.base import get_system_client

from django.conf import settings

CREATION_DESCRIPTION = getattr(
    settings, "CREATION_DESCRIPTION", "Client account creation."
)

@receiver(post_save, sender=MLMClient)
def execute_subscription_operation(sender, instance, created, *args, **kwargs):
    # Notice that we're checking for 'created' here. We only want to do this
    # the first time the 'User' instance is created. If the save that caused
    # this signal to be run was an update action, we know the user already
    # has a profile.
    if instance and created:

        # We make transactions only if the client has parent and has been created by an admin
        if instance.parent and instance.created_by:

            if instance.created_by.user.is_mlm_staff:
                instance.is_active = True
                instance.save()

                config = get_or_create_mlm_config()
                # We debit the Client from the subscription amount
                tr1 = MLMTransaction.objects.make_debit(
                    instance,
                    instance.subscription_amount,
                    MLMTransaction.FOR_AFFILIATION,
                    CREATION_DESCRIPTION,
                    initiated_by=instance.created_by,
                )

                # We credit the system from the subscription amount
                system_client = get_system_client()
                tr2 = MLMTransaction.objects.make_credit(
                    system_client,
                    instance.subscription_amount,
                    MLMTransaction.FOR_AFFILIATION,
                    CREATION_DESCRIPTION,
                    initiated_by=instance.created_by,
                )

                ### Here Verify if there is a pair, then credit the parent
                # tr3 = MLMTransaction.objects.make_credit(
                #     instance.parent,
                #     config.upline_commissions,
                #     transaction_type=MLMTransaction.FOR_AFFILIATION,
                #     initiated_by=instance.created_by,
                # )
            else:
                instance.is_active = False
                instance.save()
        elif instance.parent and not instance.created_by:
            instance.is_active = False
            instance.save()
        else:
            instance.is_active = True
            instance.save()


""":
>>> balanced_string('azABaabza')
5
>>> balanced_string('TocoCat')
-1
>>> balanced_string('AcZCbaBz')
8
>>> balanced_string('abcdefghijklmnopqrstuvwxyz')
-1
"""

def check_register(s):
    for i in range(len(s)):
        if s[i].islower() and s[i].upper() not in s:
            return False
        if s[i].isupper() and s[i].lower() not in s:
            return False
    return True

def balanced_string(s):
    min_num = len(s)
    isMin = False
    for i in range(len(s)+1):
        for j in range(i+1, len(s)+1):
            if check_register(s[i:j]) and min_num >= j-i:
                min_num = j-i
                isMin = True
    if isMin:
        return min_num
    return -1

if __name__ == '__main__':
    import doctest
    if doctest.testmod().failed == 0:
        print('\n✨ ROCK STAR! ALL TESTS PASSED!\n')


import os
os.environ['KERAS_BACKEND'] = 'tensorflow'
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction=0.05
session = tf.Session(config=config)

from deep_sort import generate_detections
from vehicle_vgg import vehicle_encoder

from deep_sort.deep_sort import nn_matching
from deep_sort.deep_sort.tracker import Tracker
from deep_sort.application_util import preprocessing as prep
from deep_sort.application_util import visualization
from deep_sort.deep_sort.detection import Detection

import keras
import numpy as np

import matplotlib.pyplot as plt

class deepsort_rbc():
	def __init__(self):
		#loading this encoder is slow, should be done only once.
		#self.encoder = generate_detections.create_box_encoder("deep_sort/resources/networks/mars-small128.ckpt-68577")
		self.encoder = vehicle_encoder('weights/vehicle_vgg.h5')
		self.metric = nn_matching.NearestNeighborDistanceMetric("cosine",.5 , 100)
		self.tracker= Tracker(self.metric)

	def reset_tracker(self):
		self.tracker= Tracker(self.metric)

	#Older yolo used to give y,x,h,w.
	"""
	def format_yolo_output( self,out_boxes):
		out_boxes=np.array([out_boxes[:,1],out_boxes[:,0],\
			out_boxes[:,3]-out_boxes[:,1],out_boxes[:,2]-out_boxes[:,0]])
		out_boxes=out_boxes.T
		return out_boxes
	"""

	#Current Yolo gives x_center,y_center,w,h
	#Deep sort needs the format `top_left_x, top_left_y, width,height

	def format_yolo_output( self,out_boxes):
		for b in range(len(out_boxes)):
			out_boxes[b][0] = out_boxes[b][0] - out_boxes[b][2]/2
			out_boxes[b][1] = out_boxes[b][1] - out_boxes[b][3]/2
		return out_boxes

	def run_deep_sort(self, frame, out_scores, out_boxes, out_classes):
		out_boxes = self.format_yolo_output(out_boxes)

		if out_boxes==[]:
			self.tracker.predict()
			trackers = self.tracker.tracks
			return trackers

		detections = np.array(out_boxes)
		#features = self.encoder(frame, detections.copy())
		features = self.encoder.extract_features(frame,detections)

		#print(frame.shape)

		detections = [Detection(bbox, score, feature,classname) \
					for bbox,score, feature,classname in\
				zip(detections,out_scores, features,out_classes)]

		outboxes = np.array([d.tlwh for d in detections])

		outscores = np.array([d.confidence for d in detections])
		indices = prep.non_max_suppression(outboxes, 0.8,outscores)

		detections = [detections[i] for i in indices]
		self.tracker.predict()
		self.tracker.update(detections)
		trackers = self.tracker.tracks

		return trackers


from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from django.contrib.auth.hashers import make_password
import string
import random
import datetime
import math
from .models import AccountGeneric
from .serializers import AccountGenericSerializer
from ..account.models import LoggInBasic, AccountBasic
from ..account.serializers import AccountSerializer
from ..post.serializers import PostSerializer

@csrf_exempt
@api_view(['POST'])
def get_profile(request, username):
    data = request.data
    if len(data.keys() & {'token'}) >= 1:
        token = request.data['token']
        try:
            my_account = LoggInBasic.objects.get(token=token).account
            account = AccountBasic.objects.get(pk=username)
            account_generic = AccountGeneric.objects.get(pk=account)
            is_followed = account_generic.followers.filter(
                name=my_account.name).exists()
            data = {'name': account.name,
                    'username': username, 'bio': account.bio, 'nfollowers': account_generic.followers.count(), 'nfollowings': account_generic.followings.count(), 'npost': account_generic.posts.count(), 'profile': account.profile, 'isfollowed': is_followed}
            return Response({'msg': data}, status.HTTP_200_OK)
        except LoggInBasic.DoesNotExist:
            return Response({'msg': 'invalid token'}, status.HTTP_406_NOT_ACCEPTABLE)
        except AccountBasic.DoesNotExist:
            return Response({'msg': 'invalid username'}, status.HTTP_406_NOT_ACCEPTABLE)
    return Response({'msg': 'invalid data'}, status.HTTP_406_NOT_ACCEPTABLE)

@csrf_exempt
@api_view(['POST'])
def follow(request):
    data = request.data
    if len(data.keys() & {'token', 'username'}) >= 2:
        token = request.data['token']
        try:
            username = data['username']
            my_account = LoggInBasic.objects.get(token=token).account
            account = AccountBasic.objects.get(pk=username)
            account_generic = AccountGeneric.objects.get(pk=account)
            my_account_generic = AccountGeneric.objects.get(pk=my_account)
            if (account_generic.followers.filter(username=my_account.username).exists()):
                account_generic.followers.remove(my_account)
                my_account_generic.followings.remove(account)
                account_generic.save()
                my_account_generic.save()
                return Response({'msg': 'successfully removed'}, status.HTTP_200_OK)
            my_account_generic.followings.add(account)
            account_generic.followers.add(my_account)
            account_generic.save()
            my_account_generic.save()
            return Response({'msg': 'successfully added'}, status.HTTP_200_OK)
        except LoggInBasic.DoesNotExist:
            return Response({'msg': 'invalid token'}, status.HTTP_406_NOT_ACCEPTABLE)
        except AccountBasic.DoesNotExist:
            return Response({'msg': 'invalid username'}, status.HTTP_406_NOT_ACCEPTABLE)
    return Response({'msg': 'invalid data'}, status.HTTP_406_NOT_ACCEPTABLE)

@csrf_exempt
@api_view(['POST'])
def get_followers_followings(request):
    data = request.data
    if len(data.keys() & {'token', 'username'}) >= 2:
        token = request.data['token']
        try:
            username = data['username']
            my_account = LoggInBasic.objects.get(token=token).account
            account = AccountBasic.objects.get(pk=username)
            account_generic = AccountGeneric.objects.get(pk=account)
            my_account_generic = AccountGeneric.objects.get(pk=my_account)
            followers = AccountSerializer(account_generic.followers, many=True)
            followings = AccountSerializer(
                account_generic.followings, many=True)
            return Response({'msg': {'followers': followers.data, 'followings': followings.data}}, status.HTTP_200_OK)
        except LoggInBasic.DoesNotExist:
            return Response({'msg': 'invalid token'}, status.HTTP_406_NOT_ACCEPTABLE)
        except AccountBasic.DoesNotExist:
            return Response({'msg': 'invalid username'}, status.HTTP_406_NOT_ACCEPTABLE)
    return Response({'msg': 'invalid data'}, status.HTTP_406_NOT_ACCEPTABLE)

@csrf_exempt
@api_view(['POST'])
def get_posts_username(request):
    data = request.data
    if len(data.keys() & {'token', 'username'}) >= 2:
        token = request.data['token']
        try:
            username = data['username']
            my_account = LoggInBasic.objects.get(token=token).account
            account = AccountBasic.objects.get(pk=username)
            account_generic = AccountGeneric.objects.get(pk=account)
            my_account_generic = AccountGeneric.objects.get(pk=my_account)
            posts = account_generic.posts
            dates = []
            for p in posts.all():
                dates.append(get_correct_time(p.date_post))
            return Response({'msg': {'posts': PostSerializer(posts, many=True).data, 'date': dates}}, status.HTTP_200_OK)
        except LoggInBasic.DoesNotExist:
            return Response({'msg': 'invalid token'}, status.HTTP_406_NOT_ACCEPTABLE)
        except AccountBasic.DoesNotExist:
            return Response({'msg': 'invalid username'}, status.HTTP_406_NOT_ACCEPTABLE)
    return Response({'msg': 'invalid data'}, status.HTTP_406_NOT_ACCEPTABLE)

def return_delta_time(time):
    return (datetime.datetime.now(datetime.timezone.utc) - time).seconds

def get_correct_time(time):
    dseconds = return_delta_time(time)
    date = 'Just know'
    if dseconds > 60 and dseconds <= 3600:
        date = str(math.floor(dseconds/60)) + ' mins ago'
    elif dseconds > 3600:
        date = str(math.floor(dseconds / 3600)) + ' hours age'
    return(date)


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D

#creates the coordinate system and items for the solar system
class SolarSystem():
    def __init__(self):
        self.size = 1000
        self.planets = []
        self.fig = plt.figure()
        self.ax = Axes3D(self.fig,auto_add_to_figure=False)#, auto_add_to_figure=False)
        self.fig.add_axes(self.ax)
        self.dT = 1

    def add_planet(self, planet):
        self.planets.append(planet)

    def update_planets(self):
        self.ax.clear() ###Remove the previous drawing
        for planet in self.planets:
            planet.move()
            planet.draw()

    def fix_axes(self):
        self.ax.set_xlim((-self.size/2, self.size/2))
        self.ax.set_ylim((-self.size/2, self.size/2))
        self.ax.set_zlim((-self.size/2, self.size/2))

    def gravity_planets(self):
        for i, first in enumerate(self.planets):
            for second in self.planets[i+1:]:
                first.gravity(second)

class Planet():
    def __init__(self, SolarSys, mass, position=(0,0,0), velocity=(0,0,0)):
        self.SolarSys = SolarSys
        self.mass = mass
        self.position = position
        self.velocity = velocity
        self.SolarSys.add_planet(self)
        self.color = "black"

    def move(self): # updates its position and velocity
        self.position = (
            self.position[0]+self.velocity[0]*SolarSys.dT,
            self.position[1]+self.velocity[1]*SolarSys.dT,
            self.position[2]+self.velocity[2]*SolarSys.dT,
        )

    def draw(self): ###Plot Position
        self.SolarSys.ax.plot(*self.position, marker="o", markersize=10, color=self.color)

    def gravity(self, other): ###evaluate the force
        distance = np.subtract(other.position, self.position)
        distanceMag = np.linalg.norm(distance)
        distanceUnit = np.divide(distance,distanceMag)
        forceMag = self.mass*other.mass/(distanceMag**2)
        force = np.multiply(distanceUnit, forceMag)
        switch = 1
        for body in self, other:
            acceleration = np.divide(force, body.mass)
            acceleration = np.multiply(force, SolarSys.dT*switch)
            body.velocity = np.add(body.velocity, acceleration)
            switch *= -1

class Sun(Planet): ###Sun Class is herited from the Planet class
    def __init__(self, SolarSys, mass=1000, position=(0,0,0), velocity=(0,0,0)):
        super(Sun, self).__init__(SolarSys, mass, position, velocity)
        self.color = "yellow"

    def move(self):
        self.position = self.position

SolarSys = SolarSystem()

#Defining planets
planet1 = Planet(SolarSys, mass=100, position=(-50,-200,0), velocity=(-4,-5,0))
planet2 = Planet(SolarSys, mass=100, position=(50,-200,0), velocity=(-4,5,0))
planet3 = Planet(SolarSys, mass=200, position=(0,500,0), velocity=(4,0,0))
#sun = Sun(SolarSys)

def animate(i):
    print("The frame is:",i)
    SolarSys.gravity_planets()
    SolarSys.update_planets()
    SolarSys.fix_axes()

anim = animation.FuncAnimation(SolarSys.fig, animate, frames=100, interval=1)

writervieo = animation.FFMpegWriter(fps=120)

plt.show()


from flask import abort, jsonify, request

from app import app
from models import User

@app.route("/login", methods=["POST"])
def user_login():
    if not request.is_json:
        abort(400, "The request payload is not in JSON format")
    else:
        try:
            data = request.get_json()
            if "email" in data.keys():
                user = User.query.filter_by(email=data["email"]).first()
                if user is None:
                    abort(404)
                else:
                    return jsonify(user.serialize())
            else:
                abort(422)
        except Exception as e:
            return abort(e.code, e)


import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import time
import numpy as np

from model.models import GRASP
from lib.dataset import Dataset_PeMSD4
from torch.utils.data import DataLoader
from lib.utils import masked_mae, masked_mape, masked_rmse, loss_weight, drop_feature, cl_loss, metric

class Exp_Basic(object):
    def __init__(self, args):
        self.args = args
        self.device = self._acquire_device()
        self.model = self._build_model().to(self.device)

    def _build_model(self):
        raise NotImplementedError
        return None

    def _acquire_device(self):
        if self.args.use_gpu:
            os.environ["CUDA_VISIBLE_DEVICES"] = str(self.args.gpu) if not self.args.use_multi_gpu else self.args.devices
            device = torch.device('cuda:{}'.format(self.args.gpu))
            print('Use GPU: cuda:{}'.format(self.args.gpu))
        else:
            device = torch.device('cpu')
            print('Use CPU')
        return device

    def _get_data(self):
        pass

    def vali(self):
        pass

    def train(self):
        pass

    def test(self):
        pass

class Exp_GRASP(Exp_Basic):
    def __init__(self, args):
        super(Exp_GRASP, self).__init__(args)

    def _build_model(self):
        model = GRASP(device = self.args.device, num_nodes = self.args.num_nodes, dropout = self.args.dropout,
                      supports = self.args.supports, gcn_bool = self.args.gcn_bool, addaptadj = self.args.addaptadj,
                      aptinit = self.args.aptinit, in_dim = self.args.in_dim, out_dim = self.args.seq_len,
                      residual_channels = self.args.nhid, dilation_channels = self.args.nhid, skip_channels= self.args.nhid * 8,
                      end_channels = self.args.nhid * 16)
        return model

    def _get_data(self, flag):
        args = self.args

        data_dict = {
            'PeMSD4':[Dataset_PeMSD4, '/content/drive/MyDrive/对比实验/datax/PEMSD4', 'pems04.npz', self.args.batch_size, True]
        }
        Data = data_dict[self.args.data][0]
        data_root_path = data_dict[self.args.data][1]
        data_file_name = data_dict[self.args.data][2]
        test_batch_size = data_dict[self.args.data][3]
        self.inverse_flag = data_dict[self.args.data][4]
        timeenc = 0 if args.embed!='timeF' else 1

        if flag == 'val':
            shuffle_flag = False; drop_last = True; batch_size = args.batch_size; freq=args.freq
        elif flag=='test':
            shuffle_flag = False; drop_last = False; batch_size = test_batch_size; freq=args.freq
            # Data = Dataset_Pred
        else:
            shuffle_flag = True; drop_last = True; batch_size = args.batch_size; freq=args.freq
        data_set = Data(
            data_root_path = data_root_path,
            data_file_name = data_file_name,
            flag = flag,
            seq_len = self.args.seq_len,
            pred_len = self.args.pred_len,
            inverse=args.inverse,
            timeenc=timeenc,
            freq=freq
        )
        print(flag, len(data_set))
        data_loader = DataLoader(
            data_set,
            batch_size=batch_size,
            shuffle=shuffle_flag,
            num_workers=args.num_workers,
            drop_last=drop_last)

        return data_set, data_loader

    def _select_optimizer(self):
        model_optim = optim.Adam(self.model.parameters(), lr=self.args.learning_rate, weight_decay = self.args.weight_decay)
        return model_optim

    def _select_criterion(self):
        criterion = masked_mae
        return criterion

    def train(self):
        clip = 5
        device = torch.device(self.args.device)

        train_data, train_loader = self._get_data(flag = 'train')
        vali_data, vali_loader = self._get_data(flag = 'val')

        model_optim = self._select_optimizer()
        criterion =  self._select_criterion()

        his_loss =[]
        val_time = []
        train_time = []

        for epoch in range(1, self.args.epochs + 1):
            self.model.train()
            train_loss = []
            train_mape = []
            train_rmse = []
            predx_loss = []
            clx_loss = []
            t1 = time.time()
            alpha, beta = loss_weight(epoch)
            for i, (batch_x, batch_y) in enumerate(train_loader):
                #train
                model_optim.zero_grad()
                train_x = torch.Tensor(batch_x).to(device)
                train_x = train_x.transpose(1, 3)
                train_y = torch.Tensor(batch_y).to(device)
                train_y = train_y.transpose(1, 3)
                real_val = train_y[:,0,:,:]

                batch_x_aug = drop_feature(train_x.transpose(1, 3), 0.05)
                batch_x_aug2 = drop_feature(train_x.transpose(1, 3), 0.05)
                train_x_aug = batch_x_aug.transpose(1, 3)
                train_x_aug2 = batch_x_aug2.transpose(1, 3)

                input_x = nn.functional.pad(train_x, (1,0,0,0))
                input_x_aug = nn.functional.pad(train_x_aug, (1,0,0,0))
                input_x_aug2 = nn.functional.pad(train_x_aug2, (1,0,0,0))
                output_x, _ = self.model(input_x)
                _, neg_node_emb = self.model(input_x_aug)
                _, neg_node_emb2 = self.model(input_x_aug2)
                loss_cl = cl_loss(neg_node_emb, neg_node_emb2)
                predict = output_x.transpose(1,3)
                real = torch.unsqueeze(real_val,dim=1)
                predict = train_data.inverse_transform(predict, self.inverse_flag)
                real = train_data.inverse_transform(real, self.inverse_flag)
                real = F.relu(real)
                loss_pred = criterion(predict, real, 0.0)
                loss = alpha*loss_pred + beta*loss_cl
                loss.backward()
                model_optim.step()

                mape = masked_mape(predict,real,0.0).item()
                rmse = masked_rmse(predict,real,0.0).item()

                train_loss.append(loss.item())
                predx_loss.append(loss_pred.item())
                clx_loss.append(loss_cl.item())
                train_mape.append(mape)
                train_rmse.append(rmse)

                if i % self.args.print_every == 0 :
                    log = 'Iter: {:03d}, Train Loss: {:.4f}, Pred Loss: {:.4f}, CL Loss: {:.4f} Train MAPE: {:.4f}, Train RMSE: {:.4f}'
                    print(log.format(i, train_loss[-1], predx_loss[-1], clx_loss[-1], train_mape[-1], train_rmse[-1]),flush=True)
            t2 = time.time()
            train_time.append(t2-t1)

            #validation
            s1 = time.time()
            valid_loss, valid_mape, valid_rmse = self.vali(vali_data, vali_loader, criterion)
            s2 = time.time()
            log = 'Epoch: {:03d}, Inference Time: {:.4f} secs'
            print(log.format(epoch,(s2-s1)))
            val_time.append(s2-s1)

            mtrain_loss = np.mean(train_loss)
            mpred_loss = np.mean(predx_loss)
            mcl_loss = np.mean(clx_loss)
            mtrain_mape = np.mean(train_mape)
            mtrain_rmse = np.mean(train_rmse)
            mvalid_loss = np.mean(valid_loss)
            mvalid_mape = np.mean(valid_mape)
            mvalid_rmse = np.mean(valid_rmse)

            his_loss.append(mvalid_loss)
            log = 'Epoch: {:03d}, Train Loss: {:.4f}, Pred Loss: {:.4f}, CL Loss: {:.4f}, Train MAPE: {:.4f}, Train RMSE: {:.4f}, Valid Loss: {:.4f}, Valid MAPE: {:.4f}, Valid RMSE: {:.4f}, Training Time: {:.4f}/epoch'
            print(log.format(epoch, mtrain_loss, mpred_loss, mcl_loss, mtrain_mape, mtrain_rmse, mvalid_loss, mvalid_mape, mvalid_rmse, (t2 - t1)),flush=True)
            torch.save(self.model.state_dict(), self.args.save+"_epoch_"+str(epoch)+"_"+str(round(mvalid_loss,2))+".pth")

        print("Average Training Time: {:.4f} secs/epoch".format(np.mean(train_time)))
        print("Average Inference Time: {:.4f} secs".format(np.mean(val_time)))

        return his_loss

    def vali(self, vali_data, vali_loader, criterion):
        device = torch.device(self.args.device)
        valid_loss = []
        valid_mape = []
        valid_rmse = []
        self.model.eval()
        for i, (batch_x, batch_y) in enumerate(vali_loader):
            vali_x = torch.Tensor(batch_x).to(device)
            vali_x = vali_x.transpose(1, 3)
            vali_y = torch.Tensor(batch_y).to(device)
            vali_y = vali_y.transpose(1, 3)
            real_val = vali_y[:,0,:,:]

            input_x = nn.functional.pad(vali_x, (1,0,0,0))
            output_x,_ = self.model(input_x)
            predict = output_x.transpose(1, 3)
            real = torch.unsqueeze(real_val,dim=1)
            predict = vali_data.inverse_transform(predict,self.inverse_flag)
            real = vali_data.inverse_transform(real,self.inverse_flag)
            real = F.relu(real)
            loss = criterion(predict, real, 0.0)
            mape = masked_mape(predict,real,0.0).item()
            rmse = masked_rmse(predict,real,0.0).item()

            valid_loss.append(loss.item())
            valid_mape.append(mape)
            valid_rmse.append(rmse)
        return valid_loss, valid_mape, valid_rmse

    def test(self, his_loss):
        device = torch.device(self.args.device)
        bestid = np.argmin(his_loss)
        self.model.load_state_dict(torch.load(self.args.save+"_epoch_"+str(bestid+1)+"_"+str(round(his_loss[bestid],2))+".pth"))
        test_data, test_loader = self._get_data(flag = 'test')
        self.model.eval()
        outputs = []
        realy = []
        for iter, (x, y) in enumerate(test_loader):
            testx = torch.Tensor(x).to(device)
            testx = testx.transpose(1,3)
            testy = torch.Tensor(y).to(device)
            with torch.no_grad():
                preds,_ = self.model(testx)
            preds = preds.transpose(1, 3)
            outputs.append(preds.squeeze())
            realy.append(testy)
        realy = torch.cat(realy, dim=0)
        yreal = realy.transpose(1,3)[:,0,:,:]
        yhat = torch.cat(outputs,dim=0)
        yhat = yhat[:realy.size(0),...]
        print("Training finished")
        print("The valid loss on best model is", str(round(his_loss[bestid],4)))

        amae = []
        amape = []
        armse = []
        for i in range(12):
            pred = test_data.inverse_transform(yhat[:,:,i],self.inverse_flag).to(device)
            real = test_data.inverse_transform(yreal[:,:,i],self.inverse_flag).to(device)
            real = F.relu(real)
            metrics = metric(pred,real)
            log = 'Evaluate best model on test data for horizon {:d}, Test MAE: {:.4f}, Test MAPE: {:.4f}, Test RMSE: {:.4f}'
            print(log.format(i+1, metrics[0], metrics[1], metrics[2]))
            amae.append(metrics[0])
            amape.append(metrics[1])
            armse.append(metrics[2])

        log = 'On average over 12 horizons, Test MAE: {:.4f}, Test MAPE: {:.4f}, Test RMSE: {:.4f}'
        print(log.format(np.mean(amae),np.mean(amape),np.mean(armse)))
        torch.save(self.model.state_dict(), self.args.save+"_exp"+str(self.args.expid)+"_best_"+str(round(his_loss[bestid],2))+".pth")


__revision__ = "$Rev: 2809 $"
__date__ = "$Date: 2008-05-10 03:15:14 -0300 (sab, 10 mai 2008) $"
__author__ = "$Author: johann $"

import urllib
from datetime import datetime, timedelta
from django.db import transaction
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.utils.text import capfirst
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from shotserver04.common import int_or_none, last_poll_timeout, error_page
from shotserver04.common.object_cache import preload_foreign_keys
from shotserver04.start.models import NewsItem
from shotserver04.start.forms.url import UrlForm
from shotserver04.start.forms.browsers import BrowsersForm
from shotserver04.start.forms.features import FeaturesForm
from shotserver04.start.forms.options import OptionsForm
from shotserver04.start.forms.special import SpecialForm
from shotserver04.platforms.models import Platform
from shotserver04.factories.models import Factory
from shotserver04.browsers.models import BrowserGroup, Browser
from shotserver04.websites.models import Website
from shotserver04.requests.models import RequestGroup, Request
from shotserver04.sponsors.models import Sponsor

BROWSER_COLUMNS = 5
SELECTOR_TEMPLATE = u"""
%s
""".strip()

def start(http_request):
    """
    Front page with URL input, browser chooser, and options.
    """
    if (http_request.user.is_anonymous() and
        hasattr(settings, 'ALLOW_ANONYMOUS_REQUESTS') and
        not settings.ALLOW_ANONYMOUS_REQUESTS):
        url = '/'
        if http_request.META['QUERY_STRING']:
            url += '?' + http_request.META['QUERY_STRING']
        return error_page(http_request, _("login required"),
            _("Anonymous screenshot requests are not allowed."),
            u'%s' % (
                urllib.quote(url.encode('utf-8')),
                _("Please log in with your username and password.")))
    # Initialize forms.
    post = http_request.POST or None
    url_form = UrlForm(post)
    features_form = FeaturesForm(post)
    options_form = OptionsForm(post)
    special_form = SpecialForm(post)
    # Get available choices from database, with correct translations.
    active_factories = Factory.objects.filter(
        last_poll__gte=last_poll_timeout())
    active_browsers = Browser.objects.filter(
        factory__in=active_factories,
        active=True)
    if not active_browsers:
        return error_page(http_request, _("out of service"),
            _("No active screenshot factories."),
            _("Please try again later."))
    features_form.load_choices(active_browsers)
    options_form.load_choices(active_factories)
    # Validate posted data.
    valid_post = (url_form.is_valid() and
                  options_form.is_valid() and
                  features_form.is_valid() and
                  special_form.is_valid())
    # Preload some database entries for browser forms
    preload_foreign_keys(active_browsers,
                         factory=active_factories,
                         factory__operating_system=True,
                         browser_group=True,
                         engine=True)
    # Select browsers according to GET request
    selected_browsers = None
    if 'browsers' in http_request.GET:
        selected_browsers = http_request.GET['browsers'].split()
    # Browser forms for each platform.
    browser_forms = []
    for platform in Platform.objects.all():
        browser_form = BrowsersForm(active_browsers, platform,
                                    post, selected_browsers)
        browser_form.platform_name = \
            unicode(platform).lower().replace(' ', '-')
        if browser_form.is_bound:
            browser_form.full_clean()
        if browser_form.fields:
            browser_forms.append(browser_form)
        valid_post = valid_post and browser_form.is_valid()
    browser_forms[0].is_first = True
    browser_forms[-1].is_last = True
    priority = 0
    if valid_post:
        if (url_form.cleaned_data['shocksite_keywords'] >
            settings.SHOCKSITE_KEYWORDS_ALLOWED):
            # Ignore screenshot requests for shock sites.
            priority = -url_form.cleaned_data['shocksite_keywords']
        elif 'shotserver04.priority' in settings.INSTALLED_APPS:
            # Get priority processing for domain or user.
            from shotserver04.priority import domain_priority, user_priority
            priority = max(domain_priority(url_form.cleaned_data['domain']),
                           user_priority(http_request.user))
        usage_limited = check_usage_limits(
            http_request, priority,
            url_form.cleaned_data['website'],
            url_form.cleaned_data['domain'])
        if usage_limited:
            valid_post = False
    if not valid_post:
        # Show HTML form.
        if 'url' in http_request.GET:
            url_form.fields['url'].initial = http_request.GET['url']
        multi_column(browser_forms)
        selectors = mark_safe(',\n'.join([
            SELECTOR_TEMPLATE % (plus_minus, capfirst(text))
            for text, plus_minus in selector_pairs(browser_forms)]))
        news_list = NewsItem.objects.all()[:10]
        sponsors_list = Sponsor.objects.filter(front_page=True)
        show_special_form = http_request.user.is_authenticated()
        return render_to_response('start/start.html', locals(),
            context_instance=RequestContext(http_request))
    # Create screenshot requests and redirect to website overview.
    expire = datetime.now() + timedelta(minutes=30)
    values = {
        'website': url_form.cleaned_data['website'],
        'ip': http_request.META['REMOTE_ADDR'],
        'user': None,
        }
    if http_request.user.is_authenticated():
        values['user'] = http_request.user
    values.update(options_form.cleaned_data)
    values.update(features_form.cleaned_data)
    values.update(special_form.cleaned_data)
    match_values = {}
    for key in values:
        if values[key] is None:
            match_values[key + '__isnull'] = True
        else:
            match_values[key] = values[key]
    existing = RequestGroup.objects.filter(
        expire__gte=datetime.now(), **match_values).order_by('-submitted')
    if (len(existing) and
        existing[0].request_set.filter(screenshot__isnull=True).count()):
        # Previous request group is still pending, reuse it.
        request_group = existing[0]
        request_group.update_fields(expire=expire)
        if priority > request_group.priority:
            request_group.update_fields(priority=priority)
    else:
        request_group = RequestGroup.objects.create(
            expire=expire, priority=priority, **values)
    for browser_form in browser_forms:
        create_platform_requests(
            request_group, browser_form.platform, browser_form, priority)
    # Make sure that the redirect will show the new request group
    transaction.commit()
    # return render_to_response('debug.html', locals(),
    #     context_instance=RequestContext(http_request))
    return HttpResponseRedirect(values['website'].get_absolute_url())

def previous_websites(requests):
    """
    Show only websites with most requests.
    """
    requests = requests[:200] # Limit sort effort.
    preload_foreign_keys(requests, request_group__website=True)
    websites = set()
    for request in requests:
        website = request.request_group.website
        if hasattr(website, 'request_count'):
            website.request_count += 1
        else:
            website.request_count = 0
        websites.add(website)
    websites = list(websites)
    if len(websites) <= 1:
        return websites
    websites.sort(key=lambda website: -website.request_count)
    return websites[:10] # Show only the most useful results.

def check_usage_limit(result, http_request, message,
                      solution, solution_url, max_requests, **kwargs):
    """
    Check a specific usage limit.
    """
    if not http_request.user.is_anonymous():
        kwargs['request_group__user'] = http_request.user
    if not kwargs:
        kwargs['request_group__ip'] = http_request.META['REMOTE_ADDR']
    yesterday = datetime.now() - timedelta(hours=24)
    kwargs['request_group__submitted__gte'] = yesterday
    requests = Request.objects.filter(**kwargs)
    count = requests.count()
    if count > max_requests:
        if 'request_group__website__domain' in kwargs:
            domain = kwargs['request_group__website__domain']
        result['message'] = message % locals()
        result['solution'] = solution
        result['solution_url'] = solution_url
        result['websites'] = previous_websites(requests)

def check_usage_limits(http_request, priority, website, domain):
    """
    Make sure that the usage limits aren't exceeded.
    """
    website_messages = [
_("There were already %(count)d screenshot requests for this website today."),
_("You have already requested %(count)d screenshots for this website today.")]
    domain_messages = [
_("There were already %(count)d screenshot requests for %(domain)s today."),
_("You have already requested %(count)d screenshots for %(domain)s today.")]
    user_messages = [
_("There were already %(count)d screenshot requests from your IP today."),
_("You have already requested %(count)d screenshots today.")]
    email = settings.ADMINS[0][0]
    solutions = [_("Please create a user account."),
                 _("Please sign up for priority processing."),
                 _("Please write to %(email)s.") % locals()]
    solution_urls = ['/accounts/email/',
                     '/priority/',
                     'mailto:%s' % settings.ADMINS[0][1]]
    index = 1
    if http_request.user.is_anonymous():
        index = 0
    elif priority:
        index = 2
    result = {}
    check_usage_limit(result, http_request,
                      website_messages[min(1, index)],
                      solutions[index], solution_urls[index],
                      settings.MAX_WEBSITE_REQUESTS_PER_DAY[index],
                      request_group__website=website)
    if result:
        return result
    check_usage_limit(result, http_request,
                      domain_messages[min(1, index)],
                      solutions[index], solution_urls[index],
                      settings.MAX_DOMAIN_REQUESTS_PER_DAY[index],
                      request_group__website__domain=domain)
    if result:
        return result
    check_usage_limit(result, http_request,
                      user_messages[min(1, index)],
                      solutions[index], solution_urls[index],
                      settings.MAX_USER_REQUESTS_PER_DAY[index])
    return result

def multi_column(browser_forms):
    """
    Arrange browsers in multiple columns per platform.
    """
    groups = [[form.column_length(), form] for form in browser_forms]
    allow_columns = BROWSER_COLUMNS
    if len(browser_forms) > 3:
        allow_columns += 1
    for total_columns in range(len(browser_forms), allow_columns):
        groups.sort()
        length, form = groups[-1]
        if length <= 4:
            break
        form.columns += 1
        groups[-1][0] = form.column_length()

def selector_pairs(browser_forms):
    """
    Links to select or unselect all browsers.
    """
    total = sum([len(form.fields) for form in browser_forms])
    yield (_('all'), '+' * total)
    yield (_('none'), '-' * total)
    start = 0
    for form in browser_forms:
        length = len(form.fields)
        end = start + length
        yield (form.platform.name,
               '-' * start + '+' * length + '-' * (total - end))
        start = end
    yield ('Gecko', selector_func(browser_forms, lambda field:
        field.browser.engine.name == 'Gecko'))
    yield ('KHTML/WebKit', selector_func(browser_forms, lambda field:
        field.browser.engine.name in ('KHTML', 'AppleWebKit')))

def selector_func(browser_forms, func):
    result = []
    for form in browser_forms:
        for name, field in form.fields.items():
            if func(field):
                result.append('+')
            else:
                result.append('-')
    return ''.join(result)

def create_platform_requests(request_group, platform, browser_form,
                             priority=0):
    """
    Create screenshots requests for selected browsers on one platform.
    """
    platform_lower = platform.name.lower().replace(' ', '-')
    for name in browser_form.fields:
        if not browser_form.cleaned_data[name]:
            continue # Browser not selected
        first_part, browser_name, major, minor = name.split('_')
        if first_part != platform_lower:
            continue # Different platform
        browser_group = BrowserGroup.objects.get(name__iexact=browser_name)
        Request.objects.get_or_create(
            request_group=request_group,
            platform=platform,
            browser_group=browser_group,
            major=int_or_none(major),
            minor=int_or_none(minor),
            priority=priority,
            )


from PIL import Image

# https://pillow.readthedocs.io/en/5.1.x/reference/Image.html

class PNGSplit():
    def __init__(self):
        print("hi")
        get_image("pan.png")

    def get_image(image_path):
        """Get a numpy array of an image so that one can access values[x][y]."""
        image = Image.open(image_path, 'r')
        width, height = image.size
        pixel_values = list(image.getdata())
        if image.mode == 'RGBA':
            channels = 4
        elif image.mode == 'L':
            channels = 1
        else:
            print("Unknown mode: %s" % image.mode)
            return None
        pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
        return pixel_values

PNGSplit()


"""
@Datetime： 2021/6/17 20:00
@Author： Sjh
@IDE： PyCharm
"""
#导入包
from hyperlpr import *
import numpy
from PIL import Image, ImageDraw, ImageFont
#导入OpenCV库
import cv2

#第一种方式:加入中文 https://blog.csdn.net/qq_41895190/article/details/90301459
def image_add_text(img1, text, left, top, text_color, text_size):
    # 判断图片是否为ndarray格式，转为RGB图片
    if isinstance(img1, numpy.ndarray):
        image = Image.fromarray(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(image)
    # 参数依次为 字体、字体大小、编码
    font_style = ImageFont.truetype("font/simsun.ttc", text_size, encoding='utf-8')
    # 参数依次为位置、文本、颜色、字体
    draw.text((left, top), text, text_color, font=font_style)
    # 图片转换为opencv格式
    return cv2.cvtColor(numpy.asarray(image), cv2.COLOR_RGB2BGR)

#定义显示窗口的大小
cv2.namedWindow("enhanced",0)
cv2.resizeWindow("enhanced", 640, 480)

#读入图片
image = cv2.imread(r"D:\Project\Monet_traffic\data\photo\1.png")

# #改变图片大小
# image = cv2.resize(image,None,fx=0.5,fy=0.5)

#识别结果
print(HyperLPR_plate_recognition(image))

#识别信息
xinxi = HyperLPR_plate_recognition(image)[0][0]
conf = HyperLPR_plate_recognition(image)[0][1]
location = HyperLPR_plate_recognition(image)[0][2]
print(xinxi)
print(location)

# opencv添加文字
# font = cv2.FONT_HERSHEY_SIMPLEX
# # print(xinxi.split('J')[0])
# if xinxi.split('J')[0] == "川":
#     xinxi = "川" + xinxi.split('J')[0]
# # cv2.putText(image, xinxi, (600, 500), font, 1, (0, 0, 255), 3, cv2.LINE_AA)

#转换为PIL的image格式,使用PIL绘制文字,再转换为OpenCV的图片格式
image = image_add_text(image, xinxi,location[0], location[1], (255, 0, 0), 50)

#画框
cv2.rectangle(image, (location[0], location[1]), (location[2], location[3]), (0, 255, 0), 2)

#展示
cv2.imshow("image",image)
cv2.waitKey(0)

#方法二:https://blog.csdn.net/qq_44740544/article/details/106177945
# #读入单张图片：加中文
# image = cv2.imread(r"D:\Project\Monet_traffic\data\photo\1.png")
#
# # 判断图片是否为ndarray格式，转为RGB图片
# if (isinstance(image, numpy.ndarray)):
#     img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
#
# draw = ImageDraw.Draw(img)
# # 参数依次为 字体、字体大小、编码
#
# fontStyle = ImageFont.truetype("font/simsun.ttc", 20, encoding="utf-8")
# # 参数依次为位置、文本、颜色、字体
# draw.text((10, (1* 50) + 23), '这是', (255, 255, 255), font=fontStyle)
#
# # 转回BGR图片、ndarray格式
# image = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
#
# cv2.imshow("image",image)
#
# cv2.waitKey(0)

#车牌识别:https://huchenyang.net/py/80.html
#添加中文的思路
"""
因为使用cv2.putText() 只能显示英文字符，中文会出现乱码问题，
因此使用PIL在图片上绘制添加中文，可以指定字体文件。
大体思路：
OpenCV图片格式转换成PIL的图片格式；
"""


import pygame
import constants

class Ball(pygame.sprite.Sprite):

    def __init__(self):

        #https://www.pygame.org/docs/ref/sprite.html
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load('brickblocks/start.png')
        self.rect = self.image.get_rect()

        self.rect.centerx = constants.WIDTH / 2
        self.rect.centery = constants.LARGE / 2

        #add start speed
        self.speed = [3, 3]

    def updateBallPosition(self):

        if self.rect.right >= constants.WIDTH or self.rect.left <= 0:
            self.speed[0] = -self.speed[0]
        if self.rect.top <= 0:
            self.speed[1] = -self.speed[1]

        self.rect.move_ip((self.speed))


##Merge sort algorithm

def count(numbers):
    count = 1
    while numbers.next:
        numbers = numbers.next
        count += 1
    return count

def merge_sort(numbers):
    sorted = merge_node(numbers)
    return sorted

def merge_node(start):
    if start.next == None: #'if start.next' is an statement
        return start # loads nodes into listLeft, listRight

    mid = count(start) // 2
    scanner = start
    for i in range(0, mid-1):
        scanner = scanner.next

    mid_point = scanner.next

    scanner.next = None
    mid_point.last = None

    #sweet sweet recursion
    listLeft = merge_node(start)
    listRight = merge_node(mid_point)

    return merge(listLeft, listRight)

def merge(left, right):
    result = None

    if left is None: return right
    if right is None: return left

    if left.data < right.data:
        result = left
        result.next = merge(left.next, right) #
    else:
        result = right
        result.next = merge(left, right.next)

    result.next.last = result
    return result #where is this being stored?