# -*- coding: utf-8 -*-
"""
Created on Thr Jan 10 09:13:24 2018

@author: Takashi Tokuda
Keigan Inc.
"""

import argparse
import sys
import pathlib
import serial
import msvcrt
import serial.tools.list_ports
from time import sleep

current_dir = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir) + '/../../') # give 1st priority to the directory where pykeigan exists

from pykeigan import usbcontroller
from pykeigan import utils

"""
----------------------
Change Baud Rate
You can check new baud rate by "baudrate_run.py" after executing this sample
Set the current baud rate to current_baud
ボーレートの変更
本サンプル実行後、"baudrate_run.py" で動作確認が可能
以下の current_baud に現在のボーレートを入れること
----------------------

"""
current_baud = 115200

def select_port():
    print('Available COM ports list')

    portlist = serial.tools.list_ports.comports()

    if not portlist:
        print('No available port')
        sys.exit()

    print('i : name')
    print('--------')
    for i, port in enumerate(portlist):
        print(i, ':', port.device)

    print('- Enter the port number (0~)')
    portnum = input()
    portnum = int(portnum)

    portdev = None
    if portnum in range(len(portlist)):
        portdev = portlist[portnum].device

    print('Conncted to', portdev)

    return portdev

def baud_rate_setting():
    print('Select baud rate to set')
    print('--------')
    print('0: 115200')
    print('1: 230400')
    print('2: 250000')
    print('3: 460800')
    print('4: 921600')
    print('5: 1000000 (1M)')
    print('--------')
    num = int(input())
    while num < 0 or num > 5:
        print('Invalid value!')
        num = int(input())
    return num

dev=usbcontroller.USBController(select_port(),baud=current_baud) # Set the current baudrate to communicate
dev.set_baud_rate(baud_rate_setting()) #5: 1Mbps
dev.save_all_registers()
sleep(1)
dev.reboot()


import streamlit as st
import altair as alt
import inspect
from vega_datasets import data

@st.experimental_memo
def get_chart_19705(use_container_width: bool):
    import altair as alt

    source = "https://frdata.wikimedia.org/donationdata-vs-day.csv"

    chart = alt.Chart(source).mark_line().encode(
        alt.X('monthdate(date):T', title='Month', axis=alt.Axis(format='%B')),
        alt.Y('max(ytdsum):Q', title='Cumulative Donations', stack=None),
        alt.Color('year(date):O', legend=alt.Legend(title='Year')),
        alt.Order('year(data):O')
    )

    tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"])

    with tab1:
        st.altair_chart(chart, theme="streamlit", use_container_width=True)
    with tab2:
        st.altair_chart(chart, theme=None, use_container_width=True)

try:
    st.expander("See code").code(inspect.getsource(get_chart_19705))
    get_chart_19705(use_container_width=True)
except Exception as e:
    st.exception(e)


"""
    Author: @sohamroy19
    Date: 16/11/2021

    This script prints the number of messages sent by a WhatsApp user,
    given the exported chat as 'chat.txt'.
"""

import re

# open the file
f = open("chat.txt", encoding="utf8")

# now I know how to use map data structure
stats = {}
total = 0

# read line by line, stripping is always fun
for x in f:
    x = x.strip()

    # check if line is the beginning of a message
    m = re.match("\d+/\d+/\d+, \d+:\d+ - .+:", x)
    if m:
        sender = x.split("-")[1].split(":")[0].strip()  # extract sender

        total += 1  # increment total
        stats[sender] = stats.get(sender, 0) + 1  # increment sender's count

# Print table of senders and counts
print(f"""  #. {"Sender's Name":<24s} : {"Count":>8s}""")
print("------------------------------+----------")

for i, stat in enumerate(sorted(stats.items(), key=lambda x: x[1], reverse=True)):
    print(f"{(i + 1):>3d}. {stat[0]:<24s} : {stat[1]:>8d}")

print("------------------------------+----------")
print(f"     Total                    : {total:>8d}")


import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.animation as ani
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'

def NACA4Camber_line(x, max_camber, pos_camber):
	""" Function to generate camber line for NACA 4 digit serie airfoil
		using explicit function of chord wise station.
	"""
	x0 = x[np.where(x < pos_camber)];
	x1 = x[np.where(x >= pos_camber)];
	x_f = max_camber/pos_camber**2*(2*pos_camber*x0 - x0**2);
	x_b = max_camber/(1 - pos_camber)**2*(1 - 2*pos_camber + 2*pos_camber*x1 - x1**2);
	z = np.concatenate((x_f, x_b));
	return z;

def Generic_single_1D_plot(x, y, xlabel, ylabel, save_plots, name, line_label = None, linewidth = 0.75, ax = None, marker = '-x', marker_size = 5, alpha = 1, xscale = 'linear', yscale = 'linear'):
	if ax == None:	fig = plt.figure(); ax = fig.add_subplot(111);
	ax.plot(x, y, marker, label = line_label, mfc = 'none', linewidth = linewidth, markersize = marker_size, alpha = alpha);
	ax.set_xscale(xscale);
	ax.set_yscale(yscale);
	ax.grid(True);
	ax.minorticks_on();
	ax.grid(b = True, which = 'minor', color = '#999999', linestyle = '-', alpha = 0.2);
	ax.set_xlabel('%s'%(xlabel), fontsize = 13);
	ax.set_ylabel('%s'%(ylabel), fontsize = 13);
	if line_label != None:
		plt.legend(loc = 'best');
	if (save_plots):
		plt.savefig('./Figures/{}.png'.format(name), dpi = 300, bbox_inches = 'tight');
	return ax;

def Animate_Solution(Solution, save_anim):
	idx = 0;
	fig = plt.figure(figsize = (12, 8));
	ax = fig.add_subplot(111);
	im, quv, line, time = Solution.Plot_Flow_Field(idx, fig = fig, ax = ax);
	anim = ani.FuncAnimation(fig, Solution.Animate_flow_field, Solution.Ndt, interval = 50, fargs = (im, quv, line, time));
	if save_anim:
		anim.save('./Flow_field.gif');
	plt.show();
	return 0;

def Genetrate_Steady_Plots(Solution, alpha_qury, save_plots, flap = False, delta = 0):
	alp_idxs = np.where(np.in1d(np.degrees(Solution.alpha_steady), alpha_qury))[0];
	for idx in alp_idxs:
		Solution.Plot_Flow_Field(idx, unsteady = False, save_name = '%s_Flow_Field_steady_aoa_%0.1f_delta_%0.2f'%(Solution.mesh.airfoil, np.degrees(Solution.alpha_steady[idx]), np.degrees(delta)), save_plot = save_plots);
		Solution.Plot_Flow_Field(idx, unsteady = False, plot_pressure = True, save_name = '%s_Flow_Field_steady_pressure_aoa_%0.1f_delta_%0.2f'%(Solution.mesh.airfoil, np.degrees(Solution.alpha_steady[idx]), np.degrees(delta)), save_plot = save_plots);
	if flap == False:
		polar_data = np.genfromtxt('NACA%s.dat'%(Solution.mesh.airfoil));
		exp_data = np.genfromtxt('NACA0012_Exp.csv', delimiter = ',');
		ax = Generic_single_1D_plot(np.degrees(Solution.alpha_steady), Solution.lift_steady, '', '', False, '', marker = '-o', line_label = 'VPM Results', marker_size = 5);
		Generic_single_1D_plot(np.degrees(Solution.alpha_steady), 2*np.pi*Solution.alpha_steady, r'$\alpha \: [^\circ]$', r'$C_l$ [-]', save_plots, '%s_Cl_vs_alpha_steady_lone'%(Solution.mesh.airfoil), marker = '-x', line_label = 'Thin airfoil theory', ax = ax, marker_size = 5);
		ax = Generic_single_1D_plot(np.degrees(Solution.alpha_steady), Solution.lift_steady, '', '', False, '', marker = '-o', line_label = 'VPM Results', marker_size = 5);
		Generic_single_1D_plot(polar_data[:, 0], polar_data[:, 1], '', '', False, '', ax = ax, marker = '-*', line_label = 'XFoil Results', marker_size = 2.5);
		Generic_single_1D_plot(exp_data[:, 0], exp_data[:, 1], r'$\alpha \: [^\circ]$', r'$C_l$ [-]', save_plots, '%s_Cl_vs_alpha_steady'%(Solution.mesh.airfoil), ax = ax, marker = '-^', line_label = 'Experimental Results', marker_size = 5);
	return 0;

def Generate_Unsteady_Plots(Solution, k, save_plots):
	Solution.Plot_Flow_Field(Solution.Ndt - 1, unsteady = True, save_name = '%s_Flow_Field_unsteady_k_%0.3f'%(Solution.mesh.airfoil, k), save_plot = save_plots);

	ax = Generic_single_1D_plot(Solution.alpha*180/np.pi, Solution.lift, '', '', False, '', alpha = 0.75, marker = '--r', marker_size = 4, line_label = 'Unsteady solution', linewidth = 0.85);
	Generic_single_1D_plot(Solution.alpha*180/np.pi, 2*np.pi*(Solution.alpha + Solution.omega/2), '', '', False, '', alpha = 0.75, ax = ax, marker = '--g', marker_size = 5, line_label = 'Quasi-Steady solution', linewidth = 0.85);
	Generic_single_1D_plot(Solution.alpha_steady[2:-2]*180/np.pi, Solution.lift_steady[2:-2], '', '', False, '', ax = ax, marker = '-k^', marker_size = 5, line_label = 'Steady solution', linewidth = 0.85);
	Generic_single_1D_plot(Solution.alpha[0]*180/np.pi, 2*np.pi*(Solution.alpha + Solution.omega/2)[0], '', '', False, '', ax = ax, marker = '^g', marker_size = 8, line_label = 'Start Quasi-Steady');
	Generic_single_1D_plot(Solution.alpha[-1]*180/np.pi, 2*np.pi*(Solution.alpha + Solution.omega/2)[-1], '', '', False, '', ax = ax, marker = 'og', marker_size = 8, line_label = 'End Quasi-Steady');
	Generic_single_1D_plot(Solution.alpha[0]*180/np.pi, Solution.lift[0], '', '', False, '', marker = '^r', marker_size = 8, ax = ax, line_label = 'Start Unsteady');
	Generic_single_1D_plot(Solution.alpha[-1]*180/np.pi, Solution.lift[-1], r'$\alpha \: [^{\circ}]$', r'$C_l$ [-]', save_plots, '%s_Cl_vs_alpha_t_k_%0.3f'%(Solution.mesh.airfoil, k), marker = 'or', marker_size = 8, ax = ax, line_label = 'End Unsteady');

	ax = Generic_single_1D_plot(Solution.t, Solution.theta, '', '', False, '', line_label = r'$\theta(t)$', marker_size = 3);
	Generic_single_1D_plot(Solution.t, Solution.omega, r'$t$ [s]', r'$\theta$ [rad],    $\Omega$ [rad/s]', save_plots, '%s_Omega_theta_vs_t_k_%0.3f'%(Solution.mesh.airfoil, k), ax = ax, marker = '-o', marker_size = 3.5, line_label = r'$\Omega(t)$');

	ax = Generic_single_1D_plot(Solution.t, Solution.lift, r'$t$ [s]', r'$C_l$ [-]', save_plots, '%s_Cl_vs_t_k_%0.3f'%(Solution.mesh.airfoil, k), marker_size = 3.5);

	ax = Generic_single_1D_plot(Solution.t, np.degrees(Solution.alpha), '', '', False, '', line_label = r'$\alpha_{s}$', marker_size = 1);
	Generic_single_1D_plot(Solution.t, np.degrees(Solution.alpha + Solution.omega/2), '', '', False, '', ax = ax, line_label = r'$\alpha_{qs}$', marker = '-o', marker_size = 1);
	Generic_single_1D_plot(Solution.t, np.degrees(Solution.alpha_unsteady), r'$t$ [s]', r'$\alpha \: [^{\circ}]$', save_plots, 'Alpha_sd_unsd_k_%0.3f'%(k), ax = ax, line_label = r'$\alpha_{eq}$', marker = '-^', marker_size = 1);
	return 0;

def Generate_Gust_Plots(Solution, gust_amp, gust_delay, save_plots):
	ax = Generic_single_1D_plot(Solution.t, Solution.lift, '', '', False, '', marker_size = 3.5, line_label = 'Numerical Solution');
	Generic_single_1D_plot(Solution.t, (Solution.t > gust_delay)*2*np.pi*np.sin(gust_amp)*(1 - 0.5*(np.exp(-0.13*2*(Solution.t - gust_delay)) + np.exp(-2*(Solution.t - gust_delay)))), r'$t$ [s]', r'$C_l$ [-]', save_plots, '%s_gust_responce_amp_%0.3f_delay_%0.3f'%(Solution.mesh.airfoil, gust_amp, gust_delay), ax = ax, marker = '-o', marker_size = 3.5, line_label = 'Analytical Solution');
	t_idx = np.where(Solution.t > gust_delay)[0];
	Solution.Plot_Flow_Field(t_idx[0] + 2, unsteady = True, save_name = '%s_Flow_Field_gust_amp_%0.3f_delay_%0.3f'%(Solution.mesh.airfoil, gust_amp, gust_delay), save_plot = save_plots);
	Solution.Plot_Flow_Field(1, unsteady = True, save_name = '%s_Flow_Field_gust_t0_amp_%0.3f_delay_%0.3f'%(Solution.mesh.airfoil, gust_amp, gust_delay), save_plot = save_plots);
	return 0;


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

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        cur = pre = head
        appear = set()
        while cur:
            if cur.val in appear:
                pre.next = cur.next
                cur = cur.next
            else:
                appear.add(cur.val)
                pre = cur
                cur = cur.next
        return head


from botocore.exceptions import ClientError
import services
from .service import Service
from services.response import ServicesApiResponse
from typing import Dict
from boto3.dynamodb.conditions import Key
from services import const
import services.utils as utils

class DynamoDbService(Service):
    """
    This class provides higher-level integration with DynamoDB to facilitate common operations.
    """

    def __init__(self, service_name: str = 'dynamodb', region: str = const.default_region, aws_service_key: str = const.AWS_ACCESS_KEY_ID,
                 aws_secret_key: str = const.AWS_SECRET_ACCESS_KEY):
        """
        Initializes the Service.

        :param region: The region in which the aws service resides.

        :param aws_service_key: Specifies the AWS access key used as part of the credentials to authenticate the user.

        :param aws_secret_key: credentials to authenticate the AWS user.
        manager.
        """
        super().__init__(service_name, region, aws_service_key, aws_secret_key)

    def scan_table(self, table_name: str, filter_name: str, filter_value: str) -> ServicesApiResponse:
        """
        Scan DynamoDB table.

        :param table_name: The DynamoDB table in question.
        :param filter_name: Filter Expression Name.
        :param filter_value: Filter Expression Value.

        https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html
        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#boto3.dynamodb.conditions.Key

        :return: A ServicesApiResponse containing the following attributes:
            items - A list of all the matched items from DynamoDB table in Dict format. If
            there is no match then this value will contain an empty list.
        """
        ddb_table = self.service_resource.Table(table_name)
        if not self.is_ready():
            response = Service.build_unavailable_response(**{'item': None})
        else:
            try:
                if table_name is None:
                    item_from_table = None
                else:
                    filtering_exp = Key(filter_name).eq(filter_value)
                    item_from_table = \
                        ddb_table.scan(FilterExpression=filtering_exp)['Items']
                response = \
                    Service.build_ok_response(**{'items': item_from_table})
            except ClientError as e:
                response = Service.build_error_response(e)
        return response

    def put_item_in_table(self, table_name: str, item_data: Dict) -> ServicesApiResponse:
        """
        Inserts items in Dynamodb tables
        :param table_name: The DynamoDB table in question.
        :param item_data: data in the form of dictionary to be inserted in table

        :return: A ServicesApiResponse containing the following attributes:
        Inserts the values from data provided as input in table.
        Returns exception if data already exists in table
        """
        ddb_table = self.service_resource.Table(table_name)
        if not self.is_ready():
            response = Service.build_unavailable_response(**{'tables': None})
        else:
            try:
                if table_name is None:
                    item_in_table = None
                else:
                    item_in_table = ddb_table.put_item(Item=item_data, Expected={'id': {'Exists': False}})
                response = Service.build_ok_response(**{'item': item_in_table})
            except ClientError as e:
                response = Service.build_error_response(e)
                if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
                    services.logger.info("Entry already exists")
                else:
                    services.logger.info(e.response['Error']['Message'])
        return response

    def get_item_from_table(self, table_name: str, search_key: Dict) -> ServicesApiResponse:
        """
        Gets item values for given dynamodb table based on primary key and sort key.
        :param table_name: The DynamoDB table in question.
        :param search_key: dict representing the primary key of the item to retrieve.

        :return: A ServicesApiResponse containing the following attributes:
        tables - Returns a Dict in key value pair for given search_key value.
        """
        ddb_table = self.service_resource.Table(table_name)
        search_item = None
        if not self.is_ready():
            response = Service.build_unavailable_response(**{'tables': None, 'item': None})
        else:
            try:
                if table_name is None:
                    search_item = None
                else:
                    item_from_table = ddb_table.get_item(Key=search_key)
                    if 'Item' in item_from_table:
                        search_item = item_from_table['Item']
                response = Service.build_ok_response(**{'item': search_item})
            except ClientError as e:
                response = Service.build_error_response(e)
        return response

    def update_item(self, table_name: str, key: Dict, update_values: dict) -> ServicesApiResponse:
        """
        Update an existing attributes or adds a new attributes to the table if it does not already exist.
        :param table_name:  The DynamoDB table in question.
        :param key: dict representing the primary key of the item to retrieve.
        :param update_values: The values to be updated in the mentioned table.
        :return: A ServicesApiResponse containing the following attributes:
        :tables - Returns a updated attributes for the mentioned key.
        """
        ddb_table = self.service_resource.Table(table_name)
        updated_items = None
        if not self.is_ready():
            response = Service.build_unavailable_response(**{'tables': None, 'item': None})
        else:
            try:
                if table_name is None:
                    updated_items = None
                else:
                    update_expression, expression_value = utils.generate_expression(update_values)
                    item_from_table = ddb_table.update_item(Key=key, UpdateExpression=update_expression,
                                                            ExpressionAttributeValues=expression_value, ReturnValues="UPDATED_NEW")
                    if 'Attributes' in item_from_table:
                        updated_items = item_from_table['Attributes']
                response = Service.build_ok_response(**{'item': updated_items})
            except ClientError as e:
                response = Service.build_error_response(e)
        return response


import sys
import load

#Quick framework to load the plugin from the cmd line / pycharm
load.plugin_start('.')
if sys.version_info[0] < 3:
    anyKey = raw_input("Enter command..")
else:
    anyKey = input("Enter command...")
print(anyKey + " isn't the any key, but I'll stop anyway!")
load.plugin_stop()


import os
import json
import zipfile

def zip_files_and_folders(file_paths, zip_name):
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for file_path in file_paths:
            if os.path.isdir(file_path):
                for root, dirs, files in os.walk(file_path):
                    for file in files:
                        zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.dirname(file_path)))
            else:
                zipf.write(file_path, os.path.basename(file_path))

def list_files_and_subdirectories(directory, output_dict):
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.relpath(os.path.join(root, file), directory)
            if not file_path.endswith('png') and not file_path.endswith('gif'):
                output_dict["additionFile"].append('img/' + file_path.replace("\\", "/"))
            else:
                output_dict["imgFileList"].append('img/' + file_path.replace("\\", "/"))

def generate_files_with_text(folder_path, file_list):
    for filename in file_list:
        file_path = os.path.join(folder_path, filename)
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write('[\n]')

if not os.path.exists('clothes'):
    type_list = ['face.json', 'feet.json', 'genitals.json', 'hands.json', 'head.json',
                 'legs.json', 'neck.json', 'upper.json', 'lower.json', 'under_upper.json',
                 'under_lower.json', 'over_upper.json', 'over_lower.json', 'over_head.json']
    os.makedirs('clothes', exist_ok=True)
    generate_files_with_text('clothes', type_list)
os.makedirs('img', exist_ok=True)
output_dict = {}
output_dict['name'] = input('请输入模组名称:')
output_dict['version'] = input('请输入类似于1.0.0的模组版本号:')
print(f'模组生成中请稍等...')
output_dict['styleFileList'] = []
output_dict['scriptFileList'] = []
output_dict['tweeFileList'] = []
output_dict['additionFile'] = []
output_dict['imgFileList'] = []
list_files_and_subdirectories('img', output_dict)
output_dict['addonPlugin'] = [
    {
      "modName": "ModdedClothesAddon",
      "addonName": "ModdedClothesAddon",
      "modVersion": "^1.1.0",
      "params": {
        "clothes": [
          {
            "key": "face",
            "filePath": "clothes/face.json"
          },
          {
            "key": "feet",
            "filePath": "clothes/feet.json"
          },
          {
            "key": "genitals",
            "filePath": "clothes/genitals.json"
          },
          {
            "key": "hands",
            "filePath": "clothes/hands.json"
          },
          {
            "key": "head",
            "filePath": "clothes/head.json"
          },
          {
            "key": "legs",
            "filePath": "clothes/legs.json"
          },
          {
            "key": "neck",
            "filePath": "clothes/neck.json"
          },
          {
            "key": "upper",
            "filePath": "clothes/upper.json"
          },
          {
            "key": "lower",
            "filePath": "clothes/lower.json"
          },
          {
            "key": "under_upper",
            "filePath": "clothes/under_upper.json"
          },
          {
            "key": "under_lower",
            "filePath": "clothes/under_lower.json"
          },
          {
            "key": "over_upper",
            "filePath": "clothes/over_upper.json"
          },
          {
            "key": "over_lower",
            "filePath": "clothes/over_lower.json"
          },
          {
            "key": "over_head",
            "filePath": "clothes/over_head.json"
          }
        ]
      }
    },
    {
      "modName": "ModLoader DoL ImageLoaderHook",
      "addonName": "ImageLoaderAddon",
      "modVersion": "^2.3.0",
      "params": [
      ]
    }
  ]
output_dict['dependenceInfo'] = [
    {
      "modName": "ModdedClothesAddon",
      "version": "^1.1.0"
    },
    {
      "modName": "ModLoader DoL ImageLoaderHook",
      "version": "^2.3.0"
    }
  ]

# 将内容输出到文本文件
with open('boot.json', 'w', encoding='utf-8') as file:
    json.dump(output_dict, file, indent=2, ensure_ascii=False)

# 要压缩的文件和文件夹路径列表
file_paths = ['img', 'boot.json', "clothes"]
# 压缩后的文件名
zip_name = output_dict['name'] + '.zip'

zip_files_and_folders(file_paths, zip_name)
os.remove('boot.json')
print(f'模组生成完成: {zip_name}')

自制衣服模组生成器/dol衣服美化模组自动生成器.py

dol衣服美化模组自动生成器.py


# vip_cleaned_.csv
# vip_cleaned_for_time_perturbed_.csv

if __name__ == '__main__':
    with open('vip_files/vip_sorted_.csv', 'r') as vip:
        with open('vip_files/vip_cleaned_for_time_perturbed_.csv', 'w') as vip_cleaned:
            time = -1
            vip_cleaned.write(vip.readline().strip() + '\n')
            line = vip.readline()
            while line is not '':
                line = line.strip().split(',')
                # if int(line[-1]) != time and int(line[-1]) != 0:
                #     time = int(line[-1])
                #     line[1] = line[1][:-9]
                #     vip_cleaned.write(','.join(line) + '\n')
                line[1] = line[1][:-9]
                vip_cleaned.write(','.join(line) + '\n')
                line = vip.readline()


"""Example configurations."""

from spectralcluster import autotune
from spectralcluster import constraint
from spectralcluster import laplacian
from spectralcluster import refinement
from spectralcluster import spectral_clusterer

AutoTune = autotune.AutoTune
ConstraintName = constraint.ConstraintName
ConstraintOptions = constraint.ConstraintOptions
RefinementName = refinement.RefinementName
RefinementOptions = refinement.RefinementOptions
ThresholdType = refinement.ThresholdType
SymmetrizeType = refinement.SymmetrizeType
LaplacianType = laplacian.LaplacianType
SpectralClusterer = spectral_clusterer.SpectralClusterer

# Configurations that are closest to the ICASSP2018 paper
# "Speaker Diarization with LSTM".
ICASSP2018_REFINEMENT_SEQUENCE = [
    RefinementName.CropDiagonal,
    RefinementName.GaussianBlur,
    RefinementName.RowWiseThreshold,
    RefinementName.Symmetrize,
    RefinementName.Diffuse,
    RefinementName.RowWiseNormalize,
]

icassp2018_refinement_options = RefinementOptions(
    gaussian_blur_sigma=1,
    p_percentile=0.95,
    thresholding_soft_multiplier=0.01,
    thresholding_type=ThresholdType.RowMax,
    refinement_sequence=ICASSP2018_REFINEMENT_SEQUENCE)

icassp2018_clusterer = SpectralClusterer(
    min_clusters=2,
    max_clusters=7,
    autotune=None,
    laplacian_type=None,
    refinement_options=icassp2018_refinement_options,
    custom_dist="cosine")

# Configurations of Turn-to-Diarize system using the
# Turn + Constraint Propagation + AutoTune method described in the paper
# "Turn-to-Diarize: Online Speaker Diarization Constrained by
# Transformer Transducer Speaker Turn Detection".
TURNTODIARIZE_REFINEMENT_SEQUENCE = [
    RefinementName.RowWiseThreshold, RefinementName.Symmetrize
]

turntodiarize_refinement_options = RefinementOptions(
    thresholding_soft_multiplier=0.01,
    thresholding_type=ThresholdType.Percentile,
    thresholding_with_binarization=True,
    thresholding_preserve_diagonal=True,
    symmetrize_type=SymmetrizeType.Average,
    refinement_sequence=TURNTODIARIZE_REFINEMENT_SEQUENCE)

turntodiarize_constraint_options = ConstraintOptions(
    constraint_name=ConstraintName.ConstraintPropagation,
    apply_before_refinement=True,
    constraint_propagation_alpha=0.4)

turntodiarize_auto_tune = AutoTune(
    p_percentile_min=0.40,
    p_percentile_max=0.95,
    init_search_step=0.05,
    search_level=1)

turntodiarize_clusterer = SpectralClusterer(
    min_clusters=2,
    max_clusters=7,
    refinement_options=turntodiarize_refinement_options,
    constraint_options=turntodiarize_constraint_options,
    autotune=turntodiarize_auto_tune,
    laplacian_type=LaplacianType.GraphCut,
    row_wise_renorm=True,
    custom_dist="cosine")


import pyautogui
import time

#-Fail Safe Activated-#
pyautogui.FAILSAFE = True

currentMouseX, currentMouseY = pyautogui.position()
print("X Cordinate is: ", currentMouseX)
print("Y Cordinate is: ", currentMouseY)

#-Set your Y-start point here
yStartPoint = 566

#---INPUT HOW MANY OF YOUR ODERS HERE---#
HowMany = 130
#--------------------------------------#

def autoBot():
    t1 = time.time()

    i=0
    global yStartPoint

    while i<HowMany:
        try:
            pyautogui.moveTo(904,yStartPoint,duration=2)    # Move to title
            pyautogui.click(904,yStartPoint,1,0.1,'left')   # Click at title
            pyautogui.moveTo(1471,155,duration=2)           # Move at the approve button
            time.sleep(1.5)                                 #Wait seconds
            pyautogui.click(1471,155,1,0.1,'left')          #click at the approve button
            pyautogui.moveTo(905,519,duration=1)            #Move to the confimed button
            pyautogui.click(905,519,1,0.1,'left')           #click at the confirmed button
            time.sleep(1.5)                                 #wait seconds
            print(f'The order no.{i+1} has been approved.')
            #yStartPoint=yStartPoint -24
            i+=1

        except BaseException:
            print('Sequence suspended ')
            break
    t2 = time.time()
    print(f'Done, Usage time: {(t2-t1):.2f}s.')

autoBot()


#!/usr/bin/python3
import asyncio
import random
import time
import threading

from quart import Quart, request, jsonify
from servo import Servo
from wheel import Wheel
from broadcast import VideoBroadcastThread

###################################################
# start a thread to broadcast video only
start_video = False
def broadcast_video():
    video_loop = asyncio.new_event_loop()
    video_loop.create_task(broadcast(video_loop))
    video_loop.run_forever()
if start_video:
    threading.Thread(target=broadcast_video).start()
###################################################

app = Quart(__name__)
svo = Servo()
drv = Wheel()

video_broadcast = None

@app.route('/', methods=['GET'])
async def index():
    svo.angle(0, random.randint(0, 180))
    await asyncio.sleep(0)
    return ('', 200)

@app.route('/direction', methods=['POST'])
async def direction():
    content = await request.get_json()
    if content is not None:
        seconds = float(content['duration'])
        direction = int(content['direction'])
        throttle = int(content['throttle'])
        drv.drive(direction, throttle)  # start driving
        if direction != 0:
            await asyncio.sleep(seconds)  # driving time
    return ('', 200)

@app.route('/camera', methods=['POST'])
async def camera():
    content = await request.get_json()
    if content is not None:
        angle = int(content['angle'])
        svo.angle(0, angle)
    return ('', 200)

@app.route('/broadcast', methods=['POST'])
async def broadcast():
    global video_broadcast
    content = await request.get_json()
    if content is not None:
        action = content['action']
        if action == 'start':
            if video_broadcast is None:
                video_broadcast = VideoBroadcastThread()
                video_broadcast.start()
        elif action == 'stop':
            print('stop video')
            if video_broadcast is not None:
                video_broadcast.stop()
                print('exception')
                #video_broadcast.join()
                video_broadcast = None
    return ('', 200)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


import typing as t

"""
Summary: Brute force in the D&C manner consider all possibilities for * OR
a smart way with a couple of passes keeping track of the ( and ) occurrences
_______________________________________________________________________________

https://leetcode.com/problems/valid-parenthesis-string/

Given a string s containing only three types of characters: '(', ')' and '*',
return true if s is valid.

The following rules define a valid string:
- Any left parenthesis '(' must have a corresponding right parenthesis ')'.
- Any right parenthesis ')' must have a corresponding left parenthesis '('.
- Left parenthesis '(' must go before the corresponding right parenthesis ')'.
- '*' could be treated as a single right parenthesis ')' or a single left
  parenthesis '(' or an empty string "".

Example 1:
Input: s = "()"
Output: true

Example 2:
Input: s = "(*)"
Output: true

Example 3:
Input: s = "(*))"
Output: true

"""

class Solution:

    """
    The idea is we first treat all * as left --> ensure left ( is always >= )
    If its the case and left brace + * >= right brace, it means some * could be
    empty strings instead of (, so the string is valid

    Then, we do the same from the right treating all * as ) and making sure
    right brace + * >= left brace, then the string is valid as some * could be
    turned into " "
    """
    def checkValidString(self, s: str) -> bool:
        stack = []
        for char in s:
            if char in "(*":
                stack.append(char)
            else:
                if len(stack) > 0:
                    stack.pop()
                else:
                    return False

        stack = []
        for char in s[::-1]:
            if char in "*)":
                stack.append(char)
            else:
                if len(stack) > 0:
                    stack.pop()
                else:
                    return False
        return True

    # Ugly ass Brutal Solution
    def checkValidString(self, s):
        if not s: return True
        A = list(s)
        self.ans = False

        def solve(i):
            if i == len(A):
                self.ans |= valid()
            elif A[i] == '*':
                for c in '() ':
                    A[i] = c
                    solve(i + 1)
                    if self.ans: return
                A[i] = '*'
            else:
                solve(i + 1)

        def valid():
            bal = 0
            for x in A:
                if x == '(': bal += 1
                if x == ')': bal -= 1
                if bal < 0: break
            return bal == 0

        solve(0)
        return self.ans

    # D & C like brute force approach - CLOSE yet fails. The idea is for each
    # * we consider 3 possibilities: " ", (, ). Like a tree.
    # T: O (N * 3 ^ N); S: O (N)
    def checkValidString(self, s: str) -> bool:

        # TODO: You could just generate a tree and then once you've reached
        #       the end validate the curr_stack, you tried to combine the two
        #       which overcomplicated the shit out of your solution its disgusting,
        #       -> true lmao reading it 4 months later it terrible jesus christ
        def _check_if_valid(
            string: str, curr_index: int, curr_stack: list[str]
        ) -> bool:

            # Base case - processed all string, if its valid, nothing on stack
            if curr_index >= length:
                return not len(curr_stack)

            # If stack's empty (just started), add the first char on it
            if not len(curr_stack):
                curr_char = string[curr_index]
                if curr_char == "*":
                    for char in " ()":
                        if char == " ":
                            is_valid = _check_if_valid(
                                string, curr_index + 1, curr_stack.copy()
                            )
                        else:
                            curr_stack.append(char)
                            is_valid = _check_if_valid(
                                string, curr_index + 1, curr_stack.copy()
                            )
                        if is_valid:
                            return True
                    return False
                else:
                    curr_stack.append(string[curr_index])
                    return _check_if_valid(
                        string, curr_index + 1, curr_stack.copy()
                    )

            # If stack is not empty:
            # If curr char ( -> add to the stack and continue
            # If curr char ) -> needs a closing brace to be valid
            # If curr char * ->
            #   It could be ( or ) or " ". Check whether each results in a
            #   valid string. What to do with " "?
            curr_char = string[curr_index]
            if curr_char == "(":
                curr_stack.append(curr_char)
                return _check_if_valid(
                    string, curr_index + 1, curr_stack.copy()
                )
            elif curr_char == ")":
                prev_char = curr_stack[-1]
                if prev_char == "(":
                    curr_stack.pop()
                    return _check_if_valid(
                        string, curr_index + 1, curr_stack.copy()
                    )
                else:
                    return False
            else:  # Its *
                for char in " ()":
                    if char == " ":
                        is_valid = _check_if_valid(
                            string, curr_index + 1, curr_stack.copy()
                        )
                    elif char == "(":
                        curr_stack.append(char)
                        is_valid = _check_if_valid(
                            string, curr_index + 1, curr_stack.copy()
                        )
                        curr_stack.pop()
                    else:  # )
                        prev = curr_stack[-1]
                        if prev == "(":
                            curr_stack.pop()
                            is_valid = _check_if_valid(
                                string, curr_index + 1, curr_stack.copy()
                            )
                        else:
                            is_valid = False

                    if is_valid:
                        return True
                return False

        length = len(s)
        if length == 0:
            return True  # Is it valid?

        return _check_if_valid(s, 0, [])

def main():
    # s = "((((()(()()()*()(((((*)()*(**(("
    s = "*****"
    print(Solution().checkValidString(s))

if __name__ == "__main__":
    main()


import pandas as pd
import numpy as np
from multiprocessing import cpu_count, Pool

cores = cpu_count()

def parallelize(df, func):
    data_split = np.array_split(df, cores)
    pool = Pool(cores)
    data = pd.concat(pool.map(func, data_split))
    pool.close()
    pool.join()
    return data

if __name__ == '__main__':
    print(cores)


import sys
from typing import Any
# I cant help but wonder how much overhead is added by including QObject, pyqtSignal, and QWidget solely for type hinting
from PyQt5.QtCore import QObject, Qt, pyqtSignal
from PyQt5.QtWidgets import QAction, QLayout, QStyleFactory, QWidget, QApplication, QMainWindow

from utilities.Common import wrapper

def addAllActionsToObject(parent, obj):
	""" Find all QActions whose parent is ``self`` and call ``obj.addAction()`` for each of them. """
	for member in vars(parent).values(): obj.addAction(member) if type(member) == QAction else None

# TODO: stop using such a shoddy method of doing this. Hopefully much of this can be replaced with lambdas
def funcLink(func: Any):
	if isinstance(func, wrapper):
		def link(): func.call()

		return link
	elif callable(func):
		# print(func.__name__ + ' is not a wrapper. It is a ' + type(func).__name__)
		return func
	else:
		return None

def setTriggerResponse(obj: QObject, func: Any, errMsgHead: str = None):
	"""	Set a ``QObject``'s response to being triggered.\\\n
	:param obj: The ``QObject`` for which to set the trigger response
	:param func: The function to call when the ``QObject`` is triggered
	:param errMsgHead: If ``func`` is None, this string will be used for an error message that will print to the console.
	"""
	_func = funcLink(func)
	if _func is not None:
		# obj.triggered.connect(_func, Qt.AutoConnection) #Qt.AutoConnection is the default anyways
		obj.triggered.connect(_func)
	else:
		if errMsgHead is None:
			print('A functionless object has been triggered.')
		else:
			print(errMsgHead + ' has no function')

def setClickedResponse(obj: QObject, func: Any, errMsgHead: str = None):
	"""	Set a ``QObject``'s response to being clicked.\\\n
	:param obj: The ``QObject`` for which to set the click response
	:param func: The function to call when the ``QObject`` is clicked
	:param errMsgHead: If ``func`` is None, this string will be used for an error message that will print to the console.
	"""
	_func = funcLink(func)
	if _func is not None:
		obj.clicked.connect(_func)
	else:
		if errMsgHead is None:
			print('A functionless object has been clicked.')
		else:
			print(errMsgHead + ' has no function')

def setStateChangedResponse(obj: QObject, func: Any, errMsgHead: str = None):
	"""	Set a ``QObject``'s response to a change in its state.\\\n
	:param obj: The ``QObject`` for which to set the response
	:param func: The function to call when the ``QObject`` experiences a state change
	:param errMsgHead: If ``func`` is None, this string will be used for an error message that will print to the console.
	"""
	_func = funcLink(func)
	if _func is not None:
		obj.stateChanged.connect(_func)
	else:
		if errMsgHead is None:
			print('A functionless object has changed states.')
		else:
			print(errMsgHead + ' has no function')

# noinspection PyUnusedLocal
def setSignalResponse(obj: QObject, signal: pyqtSignal, func: Any, errMsgHead: str = None):
	"""	Set a ``QObject``'s response to some signal.\\\n
	:param obj: The ``QObject`` for which to set the signal response
	:param signal: The signal to which the ``QObject`` is responding
	:param func: The function to call when the ``QObject`` is signaled
	:param errMsgHead: If ``func`` is None, this string will be used for an error message that will print to the console.
	"""
	# obj.signal = signal
	_func = funcLink(func)
	if _func is not None:
		obj.signal.connect(_func)
	else:
		if errMsgHead is None:
			print('A functionless object has been signaled.')
		else:
			print(errMsgHead + ' has no function')

def layoutContents(layout: QLayout): return (layout.itemAt(i) for i in range(layout.count()))

def setStyleFromString(widget: QWidget, styleName: str):
	widget.setStyle(QStyleFactory.create(styleName))

def setAppStyleFromString(styleName: str):
	print('styleName: ', styleName)
	try:
		QApplication.instance().setStyle(QStyleFactory.create(styleName))
	except AttributeError:
		print('No QApplication object exists.', file = sys.stderr)

# def stdMainSetup(appName: str, widgetType: QWidget or None, layout: QLayout) -> (QApplication, QWidget):
# 	import sys
# 	app = QApplication(sys.argv)
# 	app.setApplicationName(appName)
#
# 	display = QWidget() if widgetType is None else widgetType  # .__call__()
#
# 	actQuit = QAction('&Quit', display)
# 	actQuit.setShortcut('Ctrl+q')
# 	actQuit.triggered.connect(sys.exit)
# 	display.addAction(actQuit)
#
# 	display.setLayout(layout)
# 	display.show()
# 	return (app, display)

def stdMainSetup(appName: str, widgetType: QWidget or None) -> QMainWindow or QWidget:  # (QApplication, QWidget):
	QApplication.instance().setApplicationName(appName)

	display = QMainWindow() if widgetType is None else widgetType  # .__call__()
	actQuit = QAction('&Quit', display)
	actQuit.setShortcut('Ctrl+q')
	actQuit.triggered.connect(sys.exit)
	display.addAction(actQuit)

	# display.setWindowFlags(Qt.Window)

	#It's unfortunate that none of these seem to account for the space taken up by the Windows taskbar when it's not set to hidden/autohide
	# from PyQt5.QtGui import QGuiApplication
	# print(QGuiApplication.primaryScreen().availableVirtualSize())
	# print(QGuiApplication.primaryScreen().availableSize())
	# print(QGuiApplication.primaryScreen().availableVirtualGeometry())
	# print(QGuiApplication.primaryScreen().availableGeometry())
	# display.setMaximumSize()

	# display.setLayout(layout)
	# display.show()
	# return (_app, display)
	return display


import cs50

print("Height: ", end="")

while True:
    height = cs50.get_int()
    if height >= 0 or height <= 23:
        break
    print("Retry: ", end="")

for i in range(height):
    j = height - 1
    while j > i:
        print(" ", end="")
        j -= 1
    for k in range(i + 2):
        print("#", end="")
    print()


import pickle
import math
import numpy as np

def compress_model(ckpt_path, path="safe_expert.npz", remove_value_network=False):
    with open(ckpt_path, "rb") as f:
        data = f.read()
    unpickled = pickle.loads(data)
    worker = pickle.loads(unpickled.pop("worker"))
    if "_optimizer_variables" in worker["state"]["default_policy"]:
        worker["state"]["default_policy"].pop("_optimizer_variables")
    pickled_worker = pickle.dumps(worker)
    weights = worker["state"]["default_policy"]
    for i in weights.keys():
        print(i)
        print(weights[i].shape)
    if remove_value_network:
        weights = {k: v for k, v in weights.items() if "value" not in k}
    np.savez_compressed(path, **weights)
    print("Numpy agent weight is saved at: {}!".format(path))

if __name__ == "__main__":
    ckpt = "../training_script/PPO/PPO_Walker2dTS2CEnv_0bd33_00000_0_seed=0_2022-11-16_15-26-54/checkpoint_1000/checkpoint-1000"
    compress_model(ckpt, path="saved_expert/mujoco/walker/ppo1000.npz")


#!/user/bin/env python
# coding=utf-8
"""
@project : PythonEx
@ide     : PyCharm
@file    : str_encrypt
@author  : wuhoubo
@desc    :
@create  : 2019/8/4 0:21:49
@update  :
"""

import requests
import re

def is_chinese(char):
    """
    判断是否是中文
    :param char: 要判断的字符
    :return:
    """
    if '\u4e00' <= char <= '\u9fa5':
        return True
    else:
        return False

def encrypt(char):
    """
    加密字符
    :param char: 要判断的字符
    :return:
    """
    if char.isalpha() or is_chinese(char):
        return str(ord(char))
    else:
        return char

def decrypt(char):
    """
    解密字符
    :param char: 要判断的字符
    :return:
    """
    if char.isnumeric() and int(char) > 9:
        return chr(int(char))
    else:
        return char

msg = input("请输入要加密的信息：")

encrypt_list = []
for char in msg:
    encrypt_list.append(encrypt(char))

encrypt_msg = "|".join(encrypt_list)
print("加密的信息为：" + encrypt_msg)

encrypt_list = encrypt_msg.split("|")
decrypt_msg = ""
for char in encrypt_list:
    decrypt_msg += decrypt(char)

print("解密的信息为：" + decrypt_msg)


PATH = 'ex1.txt'

with open(PATH) as f:
	lines = [line.strip() for line in f.readlines()]

N_STEPS = 10

rules = {}
# using a char list to prevent unnecessary string instantiation when we insert chars
polymer = list(lines[0])

for line in lines[2:]:
	toks = line.split('->')

	pair = toks[0].strip()
	middle = toks[1].strip()

	rules[pair] = middle

for step in range(1, N_STEPS + 1):
	i = 1
	while i < len(polymer):
		pair = polymer[i - 1] + polymer[i]
		middle = rules[pair]
		polymer.insert(i, middle)
		i += 2

possible_elements = set()
for c in polymer:
	possible_elements.add(c)

counts = [polymer.count(c) for c in possible_elements]

print(max(counts) - min(counts))


import os
from pathlib import Path

def return_config(factor, mail, private_plugin, uid, tid):
    base_path = Path(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "static/upload",
                     str(uid), str(tid)).as_posix()
    initial_path = base_path + "/initial/"
    predict_out_path = base_path + "/predictout/"
    out_path = base_path + "/output/"
    length_ratio = factor
    area_ratio = factor * factor
    mail = mail
    if mail == "":
        mail = "2020801253@stu.njau.edu.cn"
    os.mkdir(predict_out_path)
    os.mkdir(out_path)
    data = {
        'base_path': base_path,
        'initial_path': initial_path,
        'predict_out_path': predict_out_path,
        'out_path': out_path,
        'length_ratio': length_ratio,
        'area_ratio': area_ratio,
        'mail': mail,
        'uid': str(uid),
        'tid': str(tid),
        'pid': str(private_plugin)
    }
    return data


import socket

# 缓冲区大小
BUFF_SIZE = 1024

"""
UDP发送数据
@parma  data：     数据
@param  ip_addr：  接收方IP地址
@param  port：     接收方端口号
@return 发送数据的字节数
"""
def send(data, ip_addr, port):
    # 创建套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定端口，发送数据时会从绑定的端口发送，不会再生成随机端口
    #udp_socket.bind(("", 8001))
    # 使用套接字进行数据传输
    # (内容，地址）元组
    send_bytes = udp_socket.sendto(data.encode("utf-8"), (ip_addr, port))
    # 关闭套接字
    udp_socket.close()
    return send_bytes

"""
UDP接收数据
@param  port：   监听端口号
@return 元组（数据，元组（发送方IP，端口号））
"""
def recv(port):
    # 创建套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 使用套接字进行数据接收
    # 必须有一个固定的接收端口,只能接受这个端口来的消息
    udp_socket.bind(("", port))
    # 接收数据
    # recv_from的返回值是元组(数据，元组（发送方IP，端口号）)
    recv_data = udp_socket.recvfrom(BUFF_SIZE)
    # 关闭套接字
    udp_socket.close()
    msg = recv_data[0].decode("utf-8")
    send_addr = recv_data[1]
    return (msg, send_addr)


from tkinter import *
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
current_card = {}

try:
    data = pandas.read_csv("./Flashcard_App/data/unknown_words.csv")
except FileNotFoundError:
    original_data = pandas.read_csv("./Flashcard_App/data/french_words.csv")
    to_learn = original_data.to_dict(orient="records")
else:
    to_learn = data.to_dict(orient="records")

# --------------------------- SWITCHING CARDS ------------------------------ #
def switch_cards():
    canvas.itemconfig(card_img, image=card_back_img)
    canvas.itemconfig(card_title, text="English", fill="white" )
    canvas.itemconfig(card_word, text=current_card["English"], fill="white")

#----------------------------BUTTON COMMAND ---------------------------------#
def next_card():
    global current_card, time_switch
    window.after_cancel(time_switch)
    current_card = random.choice(to_learn)
    canvas.itemconfig(card_title, text="French", fill="black" )
    canvas.itemconfig(card_word, text=current_card["French"], fill="black")
    canvas.itemconfig(card_img, image=card_front_img)
    time_switch = window.after(3000, switch_cards)

def is_known():
    to_learn.remove(current_card)
    unknown= pandas.DataFrame(to_learn)
    unknown.to_csv("./Flashcard_App/data/unknown_words.csv",index=False)
    next_card()

# -------------------------------- UI SETUP -----------------------------------#
window = Tk()
window.title("Flascard App")
window.config(padx=50, pady=50, bg=BACKGROUND_COLOR)
time_switch = window.after(3000, switch_cards)

canvas = Canvas(width=800, height=526)
card_front_img = PhotoImage(file="./Flashcard_App/images/card_front.png")
card_back_img = PhotoImage(file="./Flashcard_App/images/card_back.png")
card_img = canvas.create_image(400, 263, image= card_front_img)
canvas.config(bg=BACKGROUND_COLOR, highlightthickness=0)
card_title =canvas.create_text(400, 150, text="Title", font=("Arial", 30, "italic"))
card_word = canvas.create_text(400, 263, text="word",font=("Arial", 40, "bold") )
canvas.grid(row=0, column=0, columnspan=2)

wrong_image = PhotoImage(file="./Flashcard_App/images/wrong.png")
unknown_button = Button(image=wrong_image, command=next_card)
unknown_button.grid(row=1, column=0)

right_image = PhotoImage(file="./Flashcard_App/images/right.png")
known_button = Button(image=right_image, command=is_known)
known_button.grid(row=1, column=1)

#to start with the words

next_card()

window.mainloop()


def dutch_flag_sort(balls):
    start = 0
    end = len(balls)-1

    while balls[start] =="R" and start < end:
        start += 1
    while balls[end] == "B" and start < end:
        end -= 1
    ## now the bounds of the problem begin at start and end at end inclusively.
    i = start
    while i <= end:
        if balls[i] == "R" and start <= i:
            balls[i], balls[start] = balls[start], balls[i]
            start += 1
        elif balls[i] == "B" and i <= end:
            balls[i], balls[end] = balls[end], balls[i]
            end -=1
        else:
            i += 1
    return balls


import sys
import xbmc
import xbmcvfs
import xbmcgui
import json
import hashlib
import xml.etree.ElementTree as ET
from contextlib import contextmanager

XML_HEADER = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'

@contextmanager
def isactive_winprop(name, value='True', windowid=10000):
    xbmcgui.Window(windowid).setProperty(name, value)
    try:
        yield
    finally:
        xbmcgui.Window(windowid).clearProperty(name)

@contextmanager
def busy_dialog():
    xbmc.executebuiltin('ActivateWindow(busydialognocancel)')
    try:
        yield
    finally:
        xbmc.executebuiltin('Dialog.Close(busydialognocancel)')

def get_localized(text):
    if text.startswith('$LOCALIZE'):
        text = text.strip('$LOCALIZE[]')
    if try_parse_int(text):
        text = xbmc.getLocalizedString(try_parse_int(text))
    return text

def get_jsonrpc(method=None, params=None):
    if not method or not params:
        return {}
    query = {
        "jsonrpc": "2.0",
        "params": params,
        "method": method,
        "id": 1}
    try:
        jrpc = xbmc.executeJSONRPC(json.dumps(query))
        response = json.loads(try_decode_string(jrpc, errors='ignore'))
    except Exception as exc:
        kodi_log(u'SkinVariables - JSONRPC Error:\n{}'.format(exc), 1)
        response = {}
    return response

def make_xml_itertxt(xmltree, indent=1, indent_spaces=4, p_dialog=None):
    """
    xmltree = [{'tag': '', 'attrib': {'attrib-name': 'attrib-value'}, 'content': '' or []}]
    <{tag} {attrib-name}="{attrib-value}">{content}</{name}>
    """
    txt = []
    indent_str = ' ' * indent_spaces * indent

    p_total = len(xmltree) if p_dialog else 0
    p_dialog_txt = ''
    for p_count, i in enumerate(xmltree):
        if not i.get('tag', ''):
            continue  # No tag name so ignore

        txt += ['\n', indent_str, '<{}'.format(i.get('tag'))]  # Start our tag

        for k, v in i.get('attrib', {}).items():
            if not k:
                continue
            txt.append(' {}=\"{}\"'.format(k, v))  # Add tag attributes
            p_dialog_txt = v

        if not i.get('content'):
            txt.append('/>')
            continue  # No content so close tag and move onto next line

        txt.append('>')

        if p_dialog:
            p_dialog.update((p_count * 100) // p_total, message=u'{}'.format(p_dialog_txt))

        if isinstance(i.get('content'), list):
            txt.append(make_xml_itertxt(i.get('content'), indent=indent + 1))
            txt += ['\n', indent_str]  # Need to indent before closing tag
        else:
            txt.append(i.get('content'))
        txt.append('</{}>'.format(i.get('tag')))  # Finish
    return ''.join(txt)

def make_xml_includes(lines=[], p_dialog=None):
    txt = [XML_HEADER]
    txt.append('<includes>')
    txt.append(make_xml_itertxt(lines, p_dialog=p_dialog))
    txt.append('</includes>')
    return '\n'.join(txt)

def merge_dicts(org, upd, skipempty=False):
    source = org.copy()
    for k, v in upd.items():
        if not k:
            continue
        if skipempty and not v:
            continue
        if isinstance(v, dict):
            if not isinstance(source.get(k), dict):
                source[k] = {}
            source[k] = merge_dicts(source.get(k), v, skipempty=skipempty)
            continue
        source[k] = v
    return source

def del_empty_keys(d, values=[]):
    my_dict = d.copy()
    for k, v in d.items():
        if not v or v in values:
            del my_dict[k]
    return my_dict

def get_skinfolders():
    """
    Get the various xml folders for skin as defined in addon.xml
    e.g. 21x9 1080i xml etc
    """
    folders = []
    try:
        addonfile = xbmcvfs.File('special://skin/addon.xml')
        addoncontent = addonfile.read()
    finally:
        addonfile.close()
    xmltree = ET.ElementTree(ET.fromstring(addoncontent))
    for child in xmltree.getroot():
        if child.attrib.get('point') == 'xbmc.gui.skin':
            for grandchild in child:
                if grandchild.tag == 'res' and grandchild.attrib.get('folder'):
                    folders.append(grandchild.attrib.get('folder'))
    return folders

def make_hash(content):
    return hashlib.md5(content.encode('utf-8')).hexdigest()

def check_hash(hashname, hashvalue=None):
    last_version = xbmc.getInfoLabel('Skin.String({})'.format(hashname))
    if not last_version:
        return hashvalue
    if hashvalue != last_version:
        return hashvalue

def write_file(filepath=None, content=None):
    if not filepath:
        return
    f = xbmcvfs.File(filepath, 'w')
    f.write(try_encode_string(content))
    f.close()

def write_skinfile(filename=None, folders=None, content=None, hashvalue=None, hashname=None, reloadskin=True, checksum=None):
    if not filename or not folders or not content:
        return

    for folder in folders:
        write_file(filepath='special://skin/{}/{}'.format(folder, filename), content=content)

    if hashvalue and hashname:
        xbmc.executebuiltin('Skin.SetString({},{})'.format(hashname, hashvalue))

    if checksum:
        xbmc.executebuiltin('Skin.SetString({},{})'.format(checksum, make_hash(content)))

    if reloadskin:
        xbmc.executebuiltin('ReloadSkin()')

def join_conditions(org='', new='', operator=' | '):
    return '{}{}{}'.format(org, operator, new) if org else new

def kodi_log(value, level=0):
    try:
        if isinstance(value, bytes):
            value = value.decode('utf-8')
        logvalue = u'{0}{1}'.format('[script.skinvariables]\n', value)
        if sys.version_info < (3, 0):
            logvalue = logvalue.encode('utf-8', 'ignore')
        if level == 1:
            xbmc.log(logvalue, level=xbmc.LOGNOTICE)
        else:
            xbmc.log(logvalue, level=xbmc.LOGDEBUG)
    except Exception as exc:
        xbmc.log(u'Logging Error: {}'.format(exc), level=xbmc.LOGNOTICE)

def load_filecontent(filename=None):
    try:
        vfs_file = xbmcvfs.File(filename)
        content = vfs_file.read()
    finally:
        vfs_file.close()
    return content

def try_parse_int(string):
    '''helper to parse int from string without erroring on empty or misformed string'''
    try:
        return int(string)
    except Exception:
        return 0

def try_decode_string(string, encoding='utf-8', errors=None):
    """helper to decode strings for PY 2 """
    if sys.version_info.major == 3:
        return string
    try:
        return string.decode(encoding, errors) if errors else string.decode(encoding)
    except Exception:
        return string

def try_encode_string(string, encoding='utf-8'):
    """helper to encode strings for PY 2 """
    if sys.version_info.major == 3:
        return string
    try:
        return string.encode(encoding)
    except Exception:
        return string


from re import match

regex_to_have = "....o"
letters_not_have = "c"
not_positions = {
  "a": [0],
  "b": [1]
}

file = open("words.txt", 'r')
parole = [line.rstrip() for line in file.readlines()]

filtered_values = list(filter(lambda v: match("^"+regex_to_have+"$", v), parole))
re_filtered_values = list(filter(lambda v: match(".*" + "".join(['(?=.*{})'.format(elem) for elem in not_positions.keys()]) + ".*", v), filtered_values))
letters_not_have_expect_regex = [letter for letter in letters_not_have if letter not in regex_to_have] if letters_not_have != "" else []
re_re_filtered_values = list(filter(lambda v: not match(".*[" + "|".join(list(letters_not_have_expect_regex)) + "].*", v), re_filtered_values)) if letters_not_have != "" else re_filtered_values

for i, lettera in enumerate(regex_to_have):
    if lettera == ".":
        re_re_filtered_values = [parola for parola in re_re_filtered_values if parola[i] not in letters_not_have]

result = re_re_filtered_values

for key in not_positions:
    for pos in not_positions[key]:
        result = list(filter(lambda v: not match("."*pos + key + "."*(len(regex_to_have)-1-pos), v), result))

for letter in not_positions.keys():
    result = [res for res in result if res.count(letter) > regex_to_have.count(letter)]

print(result)


#---------------------------------------------------
# 21/05/2020 - начато
# программа по переименованию .jpg
# под нужды проги База Эльф
#
#---------------------------------------------------
#
import os, configparser, fnmatch
from shutil import copyfile
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from main_os_form import Ui_MainWindow # главное окно программы

class Main_window(QMainWindow):
    def __init__(self):
        super(Main_window, self).__init__() # super(Main_window, self).__init__()
        print('------class Main_window(QMainWindow) создан------')
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.cs = CopyScans() # определение путей до сканов - откуда и куда скидывать
        self.init_ui_dop_config()

    def closeEvent(self, QCloseEvent):
        '''действия при закрытии приложения'''
        # обновить файл cfg если произошли изменения в настройках путей
        if self.need_to_save_cfg:
            self.cs.save_cfg()

    def init_ui_dop_config(self): # set widgets to default position
        self.ui.pushB_close.clicked.connect(self.close_win)
        self.ui.pushB_new.clicked.connect(self.new_jpg)
        self.ui.pushB_open_jpg.clicked.connect(self.open_jpg)
        self.ui.pushB_rename.clicked.connect(self.new_date_rename)
        self.ui.path_glob.triggered.connect(self.set_path_glob)
        self.ui.path_local.triggered.connect(self.set_path_local)
        self.ui.instruction_pr.triggered.connect(self.instruction_pr)
        self.ui.about_pr.triggered.connect(self.win_about)
        day_1 = QDate.currentDate()
        self.ui.dateE_dost.setDateTime(QDateTime(day_1, QTime(0, 0, 0)))
        self.ui.dateE_dost_new.setDateTime(QDateTime(day_1, QTime(0, 0, 0)))
        self.ui.checkB_north.toggled.connect(self.checkB_north_changed)
        self.ui.checkB_got.toggled.connect(self.checkB_got_changed)
        self.ui.dateE_got.setEnabled(False)
        self.set_label_path_glob()
        self.set_label_path_local()
        self.need_to_save_cfg = False
        self.ui.lineE_number.setInputMask('0000/d') #поле ввода номера (ограничение по маске)
        # МАСКА: 0-числовые необязательные знаки [0-9] / d-необязательный знак [1-9]

    def read_data_from_win(self):
        ''' read data from win forms and translate to logical class CopyScans\n
            date_dost = QDateTime.dateTime() из формы ui.DateEdit\n
            date_got = QDateTime.dateTime() из формы ui.DateEdit\n
        '''
        number = self.format_number(self.ui.lineE_number.text())
        fio = self.ui.lineE_fio.text()
        date_dost = self.ui.dateE_dost.dateTime()
        date_got = None
        if self.ui.checkB_got.checkState(): date_got=self.ui.dateE_got.dateTime()
        north = self.ui.checkB_north.checkState()
        self.cs.data_set(north, date_dost, number, fio, date_got)

    def open_jpg(self):
        '''open file.jpg with number !OR! fio from server/scans'''
        print('зашел в опен джпег')
        # собираем входные данные с окошка...
        if not self.cs.path_to_global_scans:
            QMessageBox.critical(self, 'Ошибка!', 'Не задан путь до сервера!')
            return
        self.read_data_from_win()
        # определить имя файла исходя из данных и открыть...
        file_name_full = self.cs.find_file_name()
        os.system(f'start "" "{file_name_full}"')

    def win_about(self): # вывод инфы о проге
        '''info about prog'''
        QMessageBox.about(self, 'о программе', 'Версия 1.0 (06.2020)\nmatveykenya@gmail.com')

    def instruction_pr(self):
        '''win with instuction and help for work with prog'''
        QMessageBox.about(self, 'справка', 'в разработке')

    def set_label_path_glob(self):
        self.ui.label_path_glob.setText('Путь к серверу сканов '+self.cs.path_to_global_scans)

    def set_label_path_local(self):
        self.ui.label_path_local.setText('Путь к локальной папке '+self.cs.path_to_local_scans)

    def set_path_glob(self):
        path_to_global_scans = QFileDialog.getExistingDirectory(self, caption='Выберите файлы jpg для переноса')
        if path_to_global_scans:
            self.cs.path_to_global_scans = path_to_global_scans
            self.set_label_path_glob()
            self.need_to_save_cfg = True

    def set_path_local(self):
        path_to_local_scans= QFileDialog.getExistingDirectory(self, caption='Выберите файлы jpg для переноса')
        if path_to_local_scans:
            self.cs.path_to_local_scans = path_to_local_scans
            self.set_label_path_local()
            self.need_to_save_cfg = True

    def close_win(self):
        self.close()

    def new_jpg(self):
        '''переименовываем новые файлы jpg, копируем их из path_local в path_global'''
        # собираем входные данные с окошка...
        if self.cs.path_to_global_scans:
            self.read_data_from_win()
            if self.cs.number and self.cs.fio:
                list_files = QFileDialog.getOpenFileNames(self, caption='Выберите файлы jpg для переноса',
                    dir=self.cs.path_to_local_scans, filter='*.jpg')
                files_jpg = list_files[0]
                if files_jpg:
                    # ... и собственно само действо по переносам и переименованиям
                    w = self.cs.new_rename_and_remove(files_jpg)
                    if w[0]: QMessageBox.information(self, 'Успешно', w[1])
                    elif w[1]: QMessageBox.critical(self, 'Копирование отменено!', w[1])# если сообщение W[1]='' пусто то сообщения нет
            else: QMessageBox.critical(self, 'Ошибка!', 'Нет номера или ФИО заказчика')
        else: QMessageBox.critical(self, 'Ошибка!', 'Не задан путь до сервера!')

    def new_date_rename(self):
        '''переименовываем файлы jpg и перносим по новой дате ВНУТРИ path_global'''
        # считывание данных и вызов self.cs.remove_with_new_date_dost
        #
        # собираем входные данные с окошка...
        if not self.cs.path_to_global_scans:
            QMessageBox.critical(self, 'Ошибка!', 'Не задан путь до сервера!')
            return
        self.read_data_from_win()
        # определить имена файлов исходя из данных
        files_jpg = self.cs.find_file_name()

        buttonYesNO = QMessageBox.question(self, 'Найдено', 'Столько-то файлов.\n Преносим?')
        if (buttonYesNO == QMessageBox.StandardButton.Yes):

            print('перемещаем файлы...')

        print('the end')

        #

    def format_number(self, number) -> str:
        '''returns number for name file.jpg in the desired format'''
        razdel = number.find('/')
        num = number[:razdel]
        if num == '': return ''
        doz = number[razdel+1:]

        if doz == '': doz = ''
        elif doz == '1': doz = ' доз'
        else: doz = ' доз' + doz

        print('возвращаемый номер', f'{num}{doz}')
        return f'{num}{doz}'

    def checkB_north_changed(self):
        if self.ui.checkB_north.isChecked():
            self.ui.checkB_got.setChecked(True)
            self.ui.checkB_got.setEnabled(False)
        else:
            self.ui.checkB_got.setChecked(False)
            self.ui.checkB_got.setEnabled(True)

    def checkB_got_changed(self):
        if self.ui.checkB_got.isChecked():
            self.ui.dateE_got.setEnabled(True)
            dateTime_1 = self.ui.dateE_dost.dateTime().addDays(-7)
            #print(day_1)
            self.ui.dateE_got.setDateTime(dateTime_1)
        else: self.ui.dateE_got.setEnabled(False)

class CopyScans(): # здесь реализована логика, а class Main_window отвечает за UI и сбор данных с окошек
    '''copy scans *.jpg from folder1 to folder2 and Rename its'''

    def __init__(self):
        self.path_to_global_scans = ''
        self.path_to_local_scans = ''
        self.file_cfg = self.file_config_name()
        self.open_cfg()
        self.data_set()

    def data_set(self, north=False, date_dost=None, number='', fio='', date_got=None):
        ''' set parameters '''
        self.north=north
        self.date_dost=date_dost
        self.number=number
        self.fio=fio
        self.date_got=date_got

    def file_config_name(self) -> str:
        '''return full path to config.ini in curent dir with prog'''
        file_config_name = 'config.ini'
        base_path = os.path.dirname(os.path.abspath(__file__))
        config_path = os.path.join(base_path, file_config_name)
        return config_path

    def save_cfg(self):
        '''save config.ini in dir with prog'''
        print('просто зашел')
        if os.path.isdir(self.path_to_global_scans) and os.path.isdir(self.path_to_local_scans):
            config = configparser.ConfigParser()
            config.add_section("Settings")
            config.set('Settings', 'path_to_server_with_scans', self.path_to_global_scans)
            config.set('Settings', 'path_to_local_scans', self.path_to_local_scans)
            print('зашел в def save_cfg(self)')
            with open(self.file_cfg, "w") as f:
                config.write(f)
                print('файл cfg создан/перезаписан')

    def open_cfg(self):
        '''Get paths from config.ini'''
        if os.path.isfile(self.file_cfg):
            config = configparser.ConfigParser()
            config.read(self.file_cfg)
            self.path_to_global_scans = config.get('Settings', 'path_to_server_with_scans')
            self.path_to_local_scans = config.get('Settings', 'path_to_local_scans')
            if not os.path.isdir(self.path_to_global_scans): self.path_to_global_scans = ''
            if not os.path.isdir(self.path_to_local_scans): self.path_to_local_scans = ''

    def new_rename_and_remove(self, files_jpg=list(), saveDuplicates=True):
        '''переименовать группу файлов files.jpg и копировать на Сервер path_global\n
        формат хх.хх №№№ fio-1, -2, -3 и т.д. (дата № ФИО)\n
        files_jpg - список выбранных файлов с полными путями\n
        проверка условия корректности данных должна быть проведена до вызова этой подпрогр!
        saveDuplicates=True - оставить копию переименованных файлы в исходном месте
        '''
        # новое имя файлов (без ".jpg") и путь на сервере
        new_file_name = self.file_name()
        path_to_server = self.path_to_server()
        # путь до локальной папки с файлами
        path_to_file = os.path.dirname(files_jpg[0])

        textMessage = f'Файлы jpg будут перенесены по пути:\n{path_to_server}\n\n{new_file_name} - {len(files_jpg)} шт'
        if saveDuplicates: textMessage += f'\n\nДубликаты сохранены в {path_to_file}'
        buttonYesNO = QMessageBox.question(application, 'Проверь правильность данных', textMessage)
        if (buttonYesNO == QMessageBox.StandardButton.Yes):

            if not os.path.isdir(path_to_server):
                try: os.makedirs(path_to_server)
                except: return False, 'Создание папки на сервер не удалось!\nКопирование отменилось'

            for i in range(len(files_jpg)):
                ii_str = str(i+1)
                if len(ii_str)<2: ii_str = '0'+ii_str

                #Защита от дурака епта - чтобы ранее скопированные файлы не перезаписались
                file_name_to_sever = path_to_server +'/'+ new_file_name +'-'+ ii_str + '.jpg'
                if os.path.isfile(file_name_to_sever):
                    return False, f'файл {file_name_to_sever} уже есть на сервере'
                file_name = path_to_file +'/'+ new_file_name +'-'+ ii_str + '.jpg'
                if os.path.isfile(file_name):
                    return False, f'файл {file_name} уже есть здесь'

                try:
                    copyfile(files_jpg[i], file_name_to_sever) # копия файлов на сервер
                except: return False, 'Копирование файлов на сервер не удалось!'

                if saveDuplicates:
                    try:
                        os.rename(files_jpg[i], file_name) # переименование в текущую директорию
                    except: return False, 'Переименование файлов в локал дир не удалось!'
                else:
                    try:
                        os.remove(files_jpg[i]) # удаление исходных файлов в текущей директории
                    except: return False, 'Удаление исходных файлов в локал дир не удалось!'

            return True, f'Перенесено на сервер {path_to_server}\n\n{len(files_jpg)} файлов'

        return False, f''

    def file_name(self) -> str:
        '''local name(s) file.jpg on server (no dir path and without-".jpg")'''
        if self.north:
            return self.date_got.toString('dd.MM') + ' (c) ' + self.number + ' ' + self.fio
        else:
            return self.date_dost.toString('dd.MM') +' '+ self.number +' '+ self.fio

    def file_name_mask(self) -> str:
        ''' возвращает маску имени файла по неполным параметрам '''
        return '*' + self.number + '*' + self.fio+ '*'

    def path_to_server(self) -> str:
        '''dir path to scan server for curent file(s)'''
        year = self.date_dost.toString('yyyy')
        month = self.date_dost.toString('MM')
        day_month = self.date_dost.toString('dd.MM')
        if self.north:
            return self.path_to_global_scans + '/' + year +\
            '/СЕВЕР/(' + month + ') отгруз ' + day_month
        else:
            day = self.date_dost.toString('dd')
            return self.path_to_global_scans+'/'+year+'/'+self.name_month(month)+'/'+day

    def remove_with_new_date_dost(self):
        '''по пути path_global перенести файлы .jpg из 1 в 2 папки с переименованием даты в имени файла'''

    def name_month(self, mm='00'):
        if mm=='01': mm='(01) январь'
        if mm=='02': mm='(02) февраль'
        if mm=='03': mm='(03) март'
        if mm=='04': mm='(04) апрель'
        if mm=='05': mm='(05) май'
        if mm=='06': mm='(06) июнь'
        if mm=='07': mm='(07) июль'
        if mm=='08': mm='(08) август'
        if mm=='09': mm='(09) сентябрь'
        if mm=='10': mm='(10) октябрь'
        if mm=='11': mm='(11) ноябрь'
        if mm=='12': mm='(12) декабрь'
        return mm

    def find_file_name(self) -> str:
        ''' Возвращает полное имя файла на сервере по заданным параметрам.
            Проверяет его, и если не может найти, то передает
            путь до папки с date_dost
        '''
        file_path = self.path_to_server()
        if not(self.number or self.fio): return file_path # если нет номера и фио то открыть папку
        file_name = self.file_name_mask()
        file_name_full = os.path.join(file_path, file_name)
        print(file_name_full)
        if os.path.isdir(file_path):
            for file in os.listdir(file_path):
                if fnmatch.fnmatch(file, file_name):
                    print (os.path.join(file_path, file))
                    return os.path.join(file_path, file)
            return file_path
        else: return ''

if __name__=='__main__':
    app = QApplication([])
    application = Main_window()
    application.show()
    app.exec_()


import json
import requests
import time
from apscheduler.schedulers.blocking import BlockingScheduler  # 引入后台
import os
from utils.file import FileUtil
# from utils.requst import postres
# from detect import run,main,parse_opt
from detect import run,main,parse_opt
SPATH = './testfile/input'
TPATH = './testfile/output'

Source = './testfile/input/test1.mp4'
Weight = './runs/train/exp3/weights/best.pt'

def postres(time,dsc,site,img_name,img_path):
    print("准备提交数据")
    url = 'http://113.250.49.15:8084/smartPlant/portal/drone/video/droneInfo'
    data = {"order_time": time, "dsc": dsc, "site": site}
    files = {"files":(img_name, open(img_path, 'rb'), "image/png", {})}
    # print(files)

    print(data)
    print(files)
    res = requests.request("POST", url, data=data, files=files)
    print(res.text)
    # print("请求发送完毕")

def autodetect(srcpath = SPATH, tarpath = TPATH):
    futi = FileUtil(srcpath,tarpath)
    fname = futi.containfile()
    print("fname is ",fname)
    if fname!= "":
        print('检测到新视频')
        print('执行检测算法')
    # 调用检测算法
        filepath = os.path.join(srcpath,fname)
        # 获取检测结果，并打印

        res = main(Source = filepath,Weight =Weight)
        # {'time': '2022-10-18 13:30:54.342617', 'path': 'runs/tmp/exp10', 'class': 'water_leakage', 'frame': '0'}
        if res:
            print()
            print('检测完成，检测结果为', res)
            order_time = res['time']
            desc = res['desc']
            site = res['site']
            img_name = res['img_name']
            img_path = os.path.join(res['path'], res['img_name'])

            # 发送http请求
            #    (time, dsc, site, img_name, img_path)
            print("准备发送请求")
            postres(time=order_time, dsc=desc, site=site, img_name=img_name, img_path=img_path)
            print("发送请求成功")
            # 清理文件夹
            # 检测完成后移动文件
            print()
            print("检测完成后，开始移动文件")
            futi.mvfile()
        else:
            print('检测完成，检测结果为', res)
            print("检测完成后，开始移动文件")
            futi.mvfile()

    else:
        print('没有新视频')

sched = BlockingScheduler()
autodetect()
sched.add_job(autodetect, 'interval', seconds=60, max_instances=1)
sched.start()


import random

def choose_serie():
    netflix_series = ["MONEY HEIST", "DARK", "ELITE", "UNORTHODOX", "SEX EDUCATION", "NARCOS", "THE LAST KINGDOM", "MAKING A MURDERER", "STRANGER THINGS", "YOU", "PEAKY BLINDERS", "TIGER KING", "MODERN FAMILY", "BLACKLIST", "BABIES", "BREAKING BAD", "PRISON BREAK"]
    word = random.choice(netflix_series)
    return word

def greetings():
    print("Welcome to the Hangman game - Netflix Series version.")

def ask_character():
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    character = input("Which character do you want to type?: ")
    while character.upper() not in alphabet:
        character = input("Only letters allowed: ")
    return character.upper()

def print_gaps(serie, hits):
    gaps = ""
    for i in range(len(serie)):
        if serie[i] != " " and hits[i] == False:
            gaps += "_ "
        elif serie[i] == " ":
            gaps += "   "
        else:
            gaps += serie[i]
    print(gaps)

def generate_word_hits(str):
    hits = []
    for i in str:
        if i == " ":
            hits.append(True)
        else:
            hits.append(False)
    return hits

def user_succeed(serie, hits, character):
    succeed = False
    for i in range(len(serie)):
        if serie[i] == character:
            hits[i] = True
            succeed = True
    return succeed

def print_hangman(fails_count, fails_allowed):
    if fails_count == 1:
        print(
            '''
            ______
            |	  |
            |     O
            |
            |
            |
            |
            |
            '''
        )
    if fails_count == 2:
        print(
            '''
            ______
            |	  |
            |     O
            |    /
            |
            |
            |
            |
            '''
        )
    if fails_count == 3:
        print(
            '''
            ______
            |	  |
            |     O
            |    /|
            |
            |
            |
            |
            '''
        )
    if fails_count == 4:
        print(
            '''
            ______
            |	  |
            |     O
            |    /|\\
            |
            |
            |
            |
            '''
        )
    if fails_count == 5:
        print(
            '''
            ______
            |	  |
            |     O
            |    /|\\
            |     |
            |
            |
            |
            '''
        )
    if fails_count == 6:
        print(
            '''
            ______
            |	  |
            |     O
            |    /|\\
            |     |
            |     /
            |
            |
            '''
        )
    if fails_count == 7:
        print(
            '''
            ______
            |	  |
            |     O
            |    /|\\
            |     |
            |     /\\
            |
            |
            '''
        )
    print("You have made ", fails_count, " fails of an overall of ", fails_allowed)

def game():
    greetings()
    serie = choose_serie()
    max_fails_allowed = 7
    fails_count = 0
    word_hits = generate_word_hits(serie)
    while fails_count < max_fails_allowed and False in word_hits:
        print_gaps(serie, word_hits)
        character = ask_character()
        if user_succeed(serie, word_hits, character) == False:
            fails_count += 1
            print_hangman(fails_count, max_fails_allowed)
    print("The serie was ", serie)

game()


from dotenv import load_dotenv
import json
from utils import *
from db import *
import jwt
import time

load_dotenv()

def handle_post(c, request: HttpRequest):
    filename_type = request.path[len("/api/files/?file=") :].split("&type=")
    filename = filename_type[0]
    file_type = filename_type[1]
    size = int(request.headers["Content-Length"])
    cur = len(request.data)
    print(cur, len(request.data), size)
    data = request.data
    while cur < size:
        left = c.recv(1000000)
        cur += len(left)
        data += left
        print(cur, len(left), len(data), size)
    print(size, len(data))
    print(file_type)
    file_meta = create_file(filename, data, file_type, size)

    return wrap_response(
        request.version,
        200,
        {
            "Content-Type": "application/json",
            "Connection": "close",
            "Access-Control-Allow-Origin": "https://cnfinal2022.herokuapp.com",
            "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
            "Access-Control-Request-Headers": "Access-Control-Allow-Headers, Content-Type, X-Requested-With, content-type, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers",
            "Access-Control-Allow-Credentials": "true",
        },
        json.dumps({"id": file_meta}),
    )

def handle_get(request: HttpRequest):
    file_id = request.path[len("/api/files/") :]
    file_type, size, data = get_file(file_id)
    print(len(data), size)
    if data != None:
        return wrap_response(
            request.version,
            200,
            {
                "Content-Type": file_type,
                "Content-Length": size,
                "Connection": "close",
                "Access-Control-Allow-Origin": "https://cnfinal2022.herokuapp.com",
                "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
                "Access-Control-Request-Headers": "Access-Control-Allow-Headers, Content-Type, X-Requested-With, content-type, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers",
                "Access-Control-Allow-Credentials": "true",
            },
            data,
        )
    else:
        return wrap_response(
            request.version,
            404,
            {
                "Content-Type": "application/json",
                "Connection": "close",
                "Access-Control-Allow-Origin": "https://cnfinal2022.herokuapp.com",
                "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
                "Access-Control-Request-Headers": "Access-Control-Allow-Headers, Content-Type, X-Requested-With, content-type, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers",
                "Access-Control-Allow-Credentials": "true",
            },
        )


from fastapi import APIRouter, Depends, HTTPException

router = APIRouter(
    prefix="/companies",
    tags=["Companies"],
    responses={
        404: {"description": "Company or companies not found"},
        403: {"description": "Operation not allowed"}
    }
)

fake_companies_db = [
    {
        "id": 1,
        "id_company_group": 1,
        "name": "COMPANY A"
    },
    {
        "id": 2,
        "id_company_group": 1,
        "name": "COMPANY B"
    },
    {
        "id": 3,
        "id_company_group": 1,
        "name": "COMPANY C"
    }
]

@router.get("/")
async def read_companies():
    return fake_companies_db

@router.get("/{id}")
async def read_company(id: int):
    for company in fake_companies_db:
        if company["id"] == id:
            return company
    return HTTPException(404)


from django.urls import path
app_label='api'
from .views import *
urlpatterns=[
    path('books',BookApiViewAll.as_view(),name='book-list'),
    path('books/<slug:slug>',BookApiView.as_view(),name='book-detail'),
    path('books/book/create',BookCreateApiView.as_view(),name='book-create'),
    path('books/<slug:slug>',BookUpdateApiView.as_view(),name='book-update'),
    path('books/<slug:slug>/delete',BookDestroyApiView.as_view(),name='book-delete'),

    path('categories',CategoryApiViewAll.as_view(),name='category-list'),
    path('categories/<slug:slug>',CategoryApiView.as_view(),name='category-detail'),
    path('categories/category/create',CategoryCreateApiView.as_view(),name='category-create'),
    path('categories/<slug:slug>',CategoryUpdateApiView.as_view(),name='category-update'),
    path('categories/<slug:slug>/delete',CategoryDestroyApiView.as_view(),name='category-delete'),
]