import cv2
import numpy as np

# 读取图片，彩色模式
img_color = cv2.imread('faces.jpg',cv2.IMREAD_COLOR)
# 读取图片，灰度模式
img_gray = cv2.imread('faces.jpg',cv2.IMREAD_GRAYSCALE)
# 读取人脸模板图片，灰度模式
template = cv2.imread('face_template1.jpg',cv2.IMREAD_GRAYSCALE)
# 获取模板尺寸
w, h = template.shape[::-1]
# 模板匹配方法数组
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
# 遍历匹配方法
for meth in methods:
    # 拷贝图片
    img_color2 = img_color.copy()
    img_gray2 = img_gray.copy()
    # 把字符串转换成代码
    method = eval(meth)
    # 模板匹配
    res = cv2.matchTemplate(img_gray2,template,method)
    # 获取匹配结果的最大、最小值，及其位置
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # TM_SQDIFF 和 TM_SQDIFF_NORMED匹配方法：值越小，越相似
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        # 取最小值位置，作为矩形框左上角位置
        top_left = min_loc
    else:
        # 取最大值位置，作为矩形框左上角位置
        top_left = max_loc
    # 根据模板尺寸计算出：矩形框右下角位置
    bottom_right = (top_left[0] + w, top_left[1] + h)
    # 画矩形框
    cv2.rectangle(img_color2,top_left, bottom_right, 255, 2)
    # 显示画好矩形框的图片
    cv2.namedWindow(meth, cv2.WINDOW_AUTOSIZE)
    cv2.imshow(meth,img_color2)
    # 等待退出键
    cv2.waitKey(0)
# 销毁显示窗口
cv2.destroyAllWindows()


import functools

import time
from flask import request, Response, make_response, jsonify, current_app
from flask_classy import FlaskView
from tigereye.helper.code import Code

# 我们自己写aipview
class ApiView(FlaskView):
    # 使用钩子函数来测试接口的响应时间
    def before_request(self):
        self.request_start_time = time.time()
    def after_request(self):
        current_app.logger.info('%s response time: %s' %(request))
    #     ——————————————————————————————————

    # 重写方法，这个方法是一个装饰器，装饰的是我们再view里面写的方法比如 get index play hosts
    @classmethod
    def make_proxy_method(cls, name):
        """Creates a proxy function that can be used by Flasks routing. The
        proxy instantiates the FlaskView subclass and calls the appropriate
        method.

        :param name: the name of the method to create a proxy for
        """

        i = cls()
        view = getattr(i, name)

        if cls.decorators:
            for decorator in cls.decorators:
                view = decorator(view)

        @functools.wraps(view)
        def proxy(**forgettable_view_args):
            # Always use the global request object's view_args, because they
            # can be modified by intervening function before an endpoint or
            # wrapper gets called. This matches Flask's behavior.
            del forgettable_view_args

            if hasattr(i, "before_request"):
                response = i.before_request(name, **request.view_args)
                if response is not None:
                    return response

            before_view_name = "before_" + name
            if hasattr(i, before_view_name):
                before_view = getattr(i, before_view_name)
                response = before_view(**request.view_args)
                if response is not None:
                    return response

            # 这里的view就是我们要装饰的方法，这里还不算一种response类型。
            response = view(**request.view_args)

            #判断是否是一个Response对象
            if not isinstance(response,Response):
                # 如果不是，则先获取它的类型
                response_type = type(response)
                #如果是tuple类型
                if  response_type == tuple and len(response)> 1:
                    # 不成功的话，我们走这里，我们api里面返回的两个参数就是请求失败
                    rc,_data = response
                    #     加上我们的自己APi接口的信息
                    #  jsonify源码逻辑是先dumps然后再makeresponse
                    # return jsonify(rc = rc.value,msg = rc.name,data = _data)
                    response =  jsonify(rc=rc.value, msg=rc.name, data=_data)
                else:
                    # 这些Code.succ.name 都是再helper里面定义一个继承eum类的方法
                    # 写死的代码，出现rc = 1 就是硬编码
                    # 其实即使我们再view里面调用的jsonify 统一到这里了。我们就不用再每个方法里加了
                    # return jsonify(rc=Code.succ.value,msg=Code.succ.name,data = response)
                    response =  jsonify(rc=Code.succ.value,msg=Code.succ.name,data = response)

            # if not isinstance(response, Response):
            #     response = make_response(response)

            after_view_name = "after_" + name
            if hasattr(i, after_view_name):
                after_view = getattr(i, after_view_name)
                response = after_view(response)

            if hasattr(i, "after_request"):
                response = i.after_request(name, response)

            return response

        return proxy


# -*- coding: utf-8 -*-
# !/usr/bin/env python
import uuid

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import codecs
import socket

from rd_util.tokenize import Tokenizer
from rd_util.detokenize import Detokenizer
from rd_util.sentence_spliter import split_function
#from rd_util.ph_number import Generizer

from regex import Regex, UNICODE

END_PUNCTUATION=['.','!','?']
DOUBLE_END_PUNCTUATION=[
        (',.',','),
        ('..','.'),
        ('!.','!'),
        ('?.','?')
           ]

#CALL_SMT_THRESHOLD = 1

def _backward_transform(result, dodetok):
    """Transform the produced output structure to old format.
    Soon to be deprecated."""
    translation = []
    min_nbest_length = min([len(s['translated']) for s in result['sentences']])
    #print "\n"
    #print "min_nbest:%d" % min_nbest_length

    #print "###################\nresult"
    #print result

    for index,sent in enumerate(result['sentences']):
        #assign first one
        one_sentence = {}
        if dodetok:
            one_sentence['src-tokenized'] = sent['src-tokenized']
            #one_sentence['src-tokenized'] = "ABC"
        one_sentence['src_text'] = sent['translated'][0]['src_text']
        one_sentence['ret_code'] = sent['translated'][0]['ret_code']
        one_sentence['line_num'] = sent['translated'][0]['line_num']
        #
        translated = []
        for sent_data in sent['translated']:
            oldformat = {}
            #if dodetok:
            #    oldformat['src-tokenized'] = sent['src-tokenized']
            #print "sent_data"
            #print sent_data
            #print "=========="
            oldformat['text'] = sent_data['text']
            oldformat['rank'] = sent_data['rank']
            oldformat['score'] = sent_data['score']
            if sent_data["alignment"]:
                oldformat['alignment'] = sent_data["alignment"]
            translated.append(oldformat)
        if min_nbest_length == 1:
            one_sentence['text'] = sent['translated'][0]['text']
            one_sentence['rank'] = 0
            one_sentence['score'] = 666
        else:
            one_sentence['n_best'] = translated
        #print translated
        translation.append(one_sentence)

    '''for rank in range(0, min_nbest_length):
        translated = []
        for sent in result['sentences']:
            oldformat = {}
            if dodetok:
                oldformat['src-tokenized'] = sent['src-tokenized']

            oldformat['text'] = sent['translated'][rank]['text']

            #liangss add for support nmtserver
            oldformat['src_text'] = sent['translated'][rank]['src_text']
            oldformat['ret_code'] = sent['translated'][rank]['ret_code']

            oldformat['rank'] = rank
            oldformat['score'] = sent['translated'][rank]['score']

            translated.append(oldformat)

        translation.append({'translated': translated, 'translationId': result['translationId']})'''

    return {'translation': [{'translated':translation,'translationId': result['translationId']}]}

class Translator:

    def __init__(self, SPLIT_SENTENCES_LEN, source_lang, target_lang):
        self.source_lang = source_lang
        self.splitter = split_function(source_lang)
        # this is added on 11/21 2015
        if source_lang == 'zh' or source_lang== 'nzh' or source_lang=='ru' or source_lang=='nru':
            self.tokenizer = Tokenizer({'lowercase': False, 'moses_escape': True})
        else:
            self.tokenizer = Tokenizer({'lowercase': True, 'moses_escape': True})

        #self.detokenizer_src = Detokenizer({'moses_deescape': True, 'capitalize_sents': True, 'language': source_lang})
        self.detokenizer = Detokenizer({'moses_deescape': True, 'capitalize_sents': True, 'language': target_lang})

        q2b = codecs.open('rd_util/q2b','r','utf8').readlines();
        self.q2b = []
        self.q2b_dict = {}
        for line in q2b:
            temp = line.strip('\n').split('/')
            self.q2b.append([temp[0],temp[1]])
            self.q2b_dict[temp[0]] = temp[1]

        self.split_sentence_len = SPLIT_SENTENCES_LEN

        #self.generizer = Generizer()

    def pre_process(self, task):
        #text = task["text"].decode('utf-8')
        text = task["text"]
        task["original_sentences"] = []
        copy_text = text[:]
        #parse q2b
        #if task['srcl'] == 'zh' or task['srcl'] == 'nzh' or \
        #        task['srcl']=='ja' or task['srcl']=='nja' \
        #        or task['srcl'] == 'nru':
        #copy_text = copy_text.replace(" ","")
        #for ele in self.q2b:
        #    text = text.replace(ele[0],ele[1])
        #import re
        #text = 'Allowed Hello Hollow'
        #for m in re.finditer('ll', text):
        #    print('ll found', m.start() - m.end())
        for i,j in self.q2b_dict.iteritems():
            text = text.replace(i,j)
            #for m in re.finditer(i, text):
            #    tmp = m.end() - 1
            #    print(i+' found', tmp)
            #    text[tmp] = j

        sentences = self.splitter(text, max_len=self.split_sentence_len)
        #searching backward to find the last letter
        for x in sentences[:-1]:
            cut_pos = len(x)

            #print "cut_pos_",cut_pos
            last_word = x[-4:-2]
            #print "last_word3_",last_word,"*END"
            real_pos = copy_text[:cut_pos].rfind(last_word)
            #handle CJK
            current_pos = -4
            runner = 0
            while(real_pos == -1):
                #can't find,fucked CJK
                last_word = x[current_pos]
                current_pos-=1
                #runner += 1
                if last_word == " ":
                    continue

                #print "%last_word3_",last_word,
                #print "*END"
                real_pos = copy_text[:cut_pos].rfind(last_word)
                #print "@real_pos,",real_pos
                if real_pos == -1:
                    #again!
                    runner +=1
            #else:
            #    real_pos+=runner
            real_pos += 3+runner
            #print "real_pos,",real_pos
            #print "--"
            task["original_sentences"].append(copy_text[:real_pos])
            copy_text = copy_text[real_pos:]
        task["original_sentences"].append(copy_text)

        #splitter_num = []
        #for x in sentences:
        #    splitter_num.append(len(x.replace(" ","")))
        '''for x in sentences:
            if len(x) < 3:
                continue
            last_3word = str(x[-4])
            #end_word = x[-1]
            end_pos = copy_text.find(last_3word)
            task["original_sentences"].append(copy_text[:end_pos+3])
            copy_text = copy_text[end_pos+3:]
            #splitter_num.append(end_pos+3)'''
        '''    if task['srcl'] == 'zh' or task['srcl'] == 'nzh' or \
                    task['srcl']=='ja' or task['srcl']=='nja' \
                    or task['srcl'] == 'nru':
                splitter_num.append(len(x.replace(" ","")))
            else:
                #print "---"
                #print x
                #print len(x)
                splitter_num.append(len(x))
        '''

        #reverse q2b

        #for num in splitter_num:
        #    task["original_sentences"].append(copy_text[:num])
        #    copy_text = copy_text[num:]
        #for x in sentences:
        #    for ele in self.b2q:
        #        task["original_sentences"].append(x.replace(ele[0],ele[1]))
        #task["original_sentences"]  =  [x for x in sentences]
        #task["original_sentences"]  =  [self.detokenizer_src.detokenize(x) for x in sentences]
        #task["tokenized_sentences"] = [self.generizer.tokenize(self.tokenizer.tokenize(sentence, self.source_lang)) for sentence in sentences]
        task["tokenized_sentences"] = [self.tokenizer.tokenize(sentence, self.source_lang) for sentence in sentences]
        #print task["tokenized_sentences"]

    def post_process(self, task):

        translations = task["translations"]
        results = []
        for index, translation in enumerate(translations):
            hypos = []
            for rank, option in enumerate(translation["nbest"]):
                hyp = option["hyp"]
                score = option["totalScore"]
                line_num = option["line_num"]
                hypo = {
                    "rank": rank,
                    "score": score,
                    "text": self.detokenizer.detokenize(hyp) if task["detoken"] else hyp,
                    "src_text": translation["src_text"] if translation.has_key("src_text") else None,
                    "ret_code": translation["ret_code"] if translation.has_key("ret_code") else 0,
                    "alignment" : option["alignment"] if option.has_key("alignment") else None,
                    "line_num" : line_num,
                }
                for char, repl in DOUBLE_END_PUNCTUATION:
                    hypo['text'] = hypo['text'].replace(char, repl)

                hypos.append(hypo)
            result = {
                'src': task["original_sentences"][index],
                'translated': hypos,
            }

            if task["detoken"]:
                result['src-tokenized'] = task["tokenized_sentences"][index]

            results.append(result)
        return results


# Tutorial at https://www.youtube.com/watch?v=8DvywoWv6fI&t=13580s

#open the file and put it in a handle named "file"
file = open('mbox.txt')
#read each line in the file and print it out
for line in file:
    print(line)

#counting lines in the file
cfile = open('mbox.txt')
count = 0
for line in cfile:
    count = count + 1
print('Line Count:', count)

#read in an entire file at once (instead of by line)
wfile = open('mbox-short.txt')
inp = wfile.read()
print(len(inp))  #print out the legth of the file, in number of characters

#print the first 20 characters of the file
print(inp[:20]) #same as [0:20]

#search through a file
sfile = open('mbox-short.txt')
for line in sfile:
    line = line.rstrip()  #strips the white space (or extra /n) at the end of the lines
    if line.startswith('From:') :
        print(line)

#another way to do it:
sfile2 = open('mbox-short.txt')
for line in sfile2:
    line = line.rstrip()  #strips the white space (or extra /n) at the end of the lines
    if not line.startswith('From:') :
        continue
    print(line)

#and to search for a string in the middle of the line, instead of at the start, use the 'in' operator:
sfile3 = open('mbox-short.txt')
for line in sfile3:
    line = line.rstrip()  #strips the white space (or extra /n) at the end of the lines
    if not '@uct.ac.za' in line :
        continue
    print(line)

#Prompt for a file name:
pfilename = input('Enter a file name: ')
try:                           #The try and except functions make sure that we do not get a traceback if the file is not found
    pfile = open(pfilename)
except:
    print('File ', pfilename, ' cannot be opened or not found.')
    quit ()                     #If the file is not found, the program quits naturally, instead of giving a traceback.  Otherwise the file is opened.
count=0
for line in pfile:
    if line.startswith('Subject:'):
        count = count + 1
print('There are ', count, 'subject lines in ', pfilename)


from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range

image_size = 28
num_labels = 10
train_subset = 10000

batch_size = 128
num_steps = 3001

def accuracy(predictions, labels):
	return (100.0*np.sum(np.argmax(predictions, 1) == np.argmax(labels,1))/predictions.shape[0])

def graphRun(graph, optimizer, loss, tf_train_dataset, tf_train_labels, train_dataset, train_labels, train_prediction, valid_prediction, valid_labels, test_prediction, test_labels):
	with tf.Session(graph = graph) as session:
		tf.global_variables_initializer().run()
		print("Initialized")
		for step in range(num_steps):
			# Pick an offset within the training data, which has been randomized.
			# Note: we could use better randomization across epochs.
			offset = (step*batch_size) % (train_labels.shape[0] - batch_size)
			#offset is not in ascending order. You move around the whole train_dataset. Adv: add more variation in a train data. Remark: it is even better if offset is chosen randomly.

			# Generate a minibatch.
			batch_data = train_dataset[offset:(offset + batch_size), :]
			batch_labels = train_labels[offset:(offset + batch_size),:]

			# Prepare a dictionary telling the session where to feed the minibatch
			# The key of the dictionary is the placeholder node of the graph to be fed,
			# and the value is the numpy array to feed to it.

			feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}

			_,l,predictions = session.run([optimizer, loss, train_prediction], feed_dict = feed_dict)
			if ( step % 500 == 0):
				print("offset %d" % offset);
				print("Minibatch loss at step %d: %f" % (step, l))
				print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
				print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))

		print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))


from itertools import product

from binary_values import binary_values

def main():
    vals = range(- 2 ** 7, 2 ** 7)
    binvals = binary_values(vals, 8)
    ops = list(product(vals, vals))
    binops = list(product(binvals, binvals))
    products = []
    for o in ops:
        products.append(o[0] * o[1])
    binproducts = binary_values(products, 16)
    with open('rx4boothmult_in.txt', 'w') as file:
        file.writelines([f"{o[0]} {o[1]}\n" for o in binops])
    with open('rx4boothmult_out.txt', 'w') as file:
        file.writelines([f"{p}\n" for p in binproducts])

if __name__ == '__main__':
    main()


import random
import strings_manager as sm
import classifier as cl
from data import knowledge_base as kb
from data import keywords as kw
FLAG = "fast"

# given a key, it returns randomly one of its value
def find_value(key):
    values = kb.dictionary[key]
    return values[random.randint(0, (len(values)-1))]

# given a value, it returns its key
def get_key(val):
    for key, values in kw.keywords_use.items():
        for value in values:
            if val == value:
                return key
    return "key doesn't exist"

# given a sentence, it finds the keywords in it
def find_keywords(sentence):
    keywords_list = []
    for keyword in kb.keywords:
        if keyword[0] in sentence:
            keywords_list.append(keyword)
    return keywords_list

# given a sentence, it finds the rate in it
def find_rate(sentence):
    final_rate = None
    for rate in kb.rates:
        if rate in sentence.lower():
            final_rate = rate
            break  # if the user writes 9 out of 10, LEO saves 9
    return final_rate

# it asks the user to give a rate and it saves it
def ask_for_rate(reaction):
    question = sm.choose_sentence("rating")
    if "*" in question:
        question = sm.replace_a_star(question, reaction)
    sm.my_print_string(question, FLAG)
    rate_answer = input()
    rate = find_rate(rate_answer)
    while not rate:
        output = find_value("wrong rating")
        sm.my_print_string(output, FLAG)
        rate_answer = input()
        rate = find_rate(rate_answer)
    return rate

# it finds the typology of the keyword (the number) to know which particle use
def find_typology(keyword):
    typology = None
    for keyword_tuple in kb.keywords:
        if keyword == keyword_tuple[0]:
            typology = keyword_tuple[1]
            break
    return typology

# it saves all the keywords in the argument messages
def update_messages(messages):
    messages.clear()
    messages_list = list(kw.keywords_use.values())
    # message_list is a list of list of values from the dictionary
    for mes_list in messages_list:
        for elem in mes_list:
            messages.append(elem)
    return messages

# it prints what has been saved from user's answers
def print_db(concerns, situations):
    print("Concern: ", concerns[0].get_concern())
    print("Situation: ", situations[0].get_situation())
    print("Thought: ", situations[0].get_thought_tuples())
    print("Physical symptoms: ", situations[0].get_phy_sym_tuples())
    print("Safety behaviours: ", situations[0].get_safety_behaviours())
    print("Self focus: ", situations[0].get_self_focus())


import requests

from http import HTTPStatus
from pprint import pprint
from urllib.parse import urljoin

from django.conf import settings

if getattr(settings, 'DISABLE_URLLIB3_WARNINGS', False):
    import urllib3
    urllib3.disable_warnings()

class BearerAuth(requests.auth.AuthBase):

    def __init__(self, token):
        self.token = token

    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

class HTTPAPIClient(object):
    base_url = None

    def __init__(self, base_url):
        self.base_url = base_url

    def build_url(self, path):
        # return urljoin(self.base_url, path)
        url = ''.join([self.base_url, path])  # quick fix for base urls with relative paths
        return url

    def get_auth(self):
        return None

    def get_default_headers(self):
        return None

    def post(self, path, data=None, json=None,  headers=None, **kwargs):
        r = requests.post(
            self.build_url(path),
            json=json,
            data=data,
            headers={
                **(self.get_default_headers() or {}),
                **(headers or {})
            } or None,
            auth=self.get_auth(),
            **kwargs
        )
        return r

    def get(self, path, data=None, headers=None, **kwargs):
        r = requests.get(
            self.build_url(path),
            data=data,
            headers={
                **(self.get_default_headers() or {}),
                **(headers or {})
            } or None,
            auth=self.get_auth(),
            **kwargs
        )
        return r


import numpy as np
from mscf.lib.tools import load_library
import ctypes
from mscf.mole.mole import Mole

def c_T_ij(I, J, Ax, Bx, ai, bi):
    Sij = np.zeros((I + 1, J + 1)).astype(np.double)
    Sij_c = Sij.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p*((I + 1)*(J + 1))))
    Tij = np.zeros((I + 1, J + 1)).astype(np.double)
    Tij_c = Tij.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p * ((I + 1) * (J + 1))))
    lib = load_library("libckin")
    f = getattr(lib, "T_ij")
    I_c = ctypes.c_int(I)
    J_c = ctypes.c_int(J)
    Ax_c = ctypes.c_double(Ax)
    Bx_c = ctypes.c_double(Bx)
    ai_c = ctypes.c_double(ai)
    bi_c = ctypes.c_double(bi)
    f(Tij_c, Sij_c, I_c, J_c, Ax_c, Bx_c, ai_c, bi_c)
    return Tij

def c_cont_Tij(basis_a, basis_b):
    Ra, I, a, da = basis_a
    Rb, J, b, db = basis_b
    Tab = np.zeros((I+1, J+1, I+1, J+1))
    Tab_c = (ctypes.c_void_p*((I+1)*(J+1)*(I+1)*(J+1)))()
    Tab_c = Tab.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p*((I+1)*(J+1)*(I+1)*(J+1))))
    lib = load_library("libckin")
    f = getattr(lib, "cont_Tij")
    a = np.array(a).astype(np.double)
    b = np.array(b).astype(np.double)
    a_c = a.ctypes.data_as(ctypes.c_void_p)
    b_c = b.ctypes.data_as(ctypes.c_void_p)
    P = ctypes.c_int(len(a))
    Q = ctypes.c_int(len(b))
    Ra = np.array(Ra).astype(np.double)
    Rb = np.array(Rb).astype(np.double)
    Ra_c = Ra.ctypes.data_as(ctypes.c_void_p)
    Rb_c = Rb.ctypes.data_as(ctypes.c_void_p)
    da = np.array(da).astype(np.double)
    db = np.array(db).astype(np.double)
    da_c = da.ctypes.data_as(ctypes.c_void_p)
    db_c = db.ctypes.data_as(ctypes.c_void_p)

    f(Tab_c, ctypes.c_int(I), ctypes.c_int(J), P, Q, Ra_c, Rb_c, a_c, b_c, da_c, db_c)
    return Tab

def c_T_lm(basis_a, basis_b):
    Ra, la, a, da = basis_a
    Rb, lb, b, db = basis_b
    T_mamb = np.zeros((2 * la + 1, 2 * lb + 1))
    T_mamb_c = T_mamb.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p * ((2 * la + 1) * (2 * lb + 1))))
    lib = load_library("libckin")
    f = getattr(lib, "T_lm")
    a = np.array(a).astype(np.double)
    b = np.array(b).astype(np.double)
    a_c = a.ctypes.data_as(ctypes.c_void_p)
    b_c = b.ctypes.data_as(ctypes.c_void_p)
    P = ctypes.c_int(len(a))
    Q = ctypes.c_int(len(b))
    Ra = np.array(Ra).astype(np.double)
    Rb = np.array(Rb).astype(np.double)
    Ra_c = Ra.ctypes.data_as(ctypes.c_void_p)
    Rb_c = Rb.ctypes.data_as(ctypes.c_void_p)
    da = np.array(da).astype(np.double)
    db = np.array(db).astype(np.double)
    da_c = da.ctypes.data_as(ctypes.c_void_p)
    db_c = db.ctypes.data_as(ctypes.c_void_p)
    f(T_mamb_c, ctypes.c_int(la), ctypes.c_int(lb), P, Q, Ra_c, Rb_c, a_c, b_c, da_c, db_c)
    return T_mamb

def c_get_kin(mol: Mole):
    T = np.zeros((mol.basis_num, mol.basis_num))
    c_T = T.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p * (mol.basis_num * mol.basis_num)))
    basis = mol.basis
    basis_len = len(basis)
    c_R = (ctypes.c_void_p*basis_len)()
    c_l = (ctypes.c_int*basis_len)()
    c_a = (ctypes.c_void_p*basis_len)()
    c_da = (ctypes.c_void_p*basis_len)()
    c_P = (ctypes.c_int*basis_len)()
    for i in range(basis_len):
        c_l[i] = basis[i][1]
        c_P[i] = len(basis[i][2])
    R_ = np.array([basis[i][0] for i in range(basis_len)]).astype(np.double)
    a_ = np.array([basis[i][2] for i in range(basis_len)]).astype(np.double)
    da_ = np.array([basis[i][3] for i in range(basis_len)]).astype(np.double)
    for i in range(basis_len):
        c_R[i] = R_[i].ctypes.data_as(ctypes.c_void_p)
        c_a[i] = a_[i].ctypes.data_as(ctypes.c_void_p)
        c_da[i] = da_[i].ctypes.data_as(ctypes.c_void_p)
    c_basis_len = ctypes.c_int(basis_len)
    c_basis_num = ctypes.c_int(mol.basis_num)
    lib = load_library("libckin")
    f = getattr(lib, "get_kin")
    f(c_T, c_R, c_l, c_a, c_da, c_P, c_basis_len, c_basis_num)
    return T


# -*- coding: UTF-8 -*-
import wx

from CommandInterface import CommandInterface

_metaclass_ = type
class ChoseFileCmd(CommandInterface,object):
    def __init__(self,view):
        super(ChoseFileCmd,self).__init__(view)

    def Excute(self):
        dlg = wx.FileDialog(None,
                            message="请选择一个文件",
                            wildcard="*" ,
                            style=wx.OPEN
                            )
        if dlg.ShowModal() == wx.ID_OK:
            self.view.filename = dlg.GetPath()
            from GlobalData import CommonData
            showmsg = "选择文件：" + self.view.filename.encode("utf8")
            self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT,showmsg,True)
        dlg.Destroy()


import sys
file = sys.argv[1]
output = sys.argv[2]
f = open(file, "rt")
gdict = dict()
while True:
    txt = f.readline()
    if len(txt) == 0: break
    arr = txt.split("::")
    garr = arr[2].split("|")
    for g in garr:
        if g.strip() not in gdict:
            gdict[g.strip()] = 0
        else:
            gdict[g.strip()] += 1
f.close()
f = open(output, "wt")
keyList = list(gdict.keys())
for key in keyList:
    f.write(key + " " + str(gdict[key]) + "\n")
f.close()


data = []

with open("inputs/day9.txt", "r") as f:
#with open("test/day9.txt", "r") as f:
    data = f.read().split("\n")  # This part may change

preamble_size = 25

preamble_start = 0

first_invalid = 0

for i in range(preamble_start + preamble_size, len(data)):
    num = int(data[i])

    has_valid = False
    for px in range(preamble_start, preamble_start + preamble_size):
        if has_valid:
            break
        for py in range(preamble_start, preamble_start + preamble_size):
            x = int(data[px])
            y = int(data[py])

            if x == y:
                continue

            if num == x + y:
                has_valid = True
                break  # Tiny speed up

    if not has_valid:
        print(num)
        first_invalid = num
        break

    preamble_start += 1

for i in range(0, len(data)):  # All starting numbers
    min_range = first_invalid
    max_range = 0

    ii = i
    sum = 0
    while sum < first_invalid and ii < len(data):
        num = int(data[ii])
        if num == first_invalid:
            ii += 1
            continue

        if num > max_range:
            max_range = num
        if num < min_range:
            min_range = num

        sum += num
        ii += 1

    if sum == first_invalid:
        print(min_range)
        print(max_range)
        print(min_range+max_range)
        break


import requests
from requests.exceptions import RequestException
import re
import json
import time

def get_page(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'
        }
        rsp = requests.get(url=url, headers=headers)
        if rsp.status_code == requests.codes.ok:
            return rsp.text
    except RequestException:
        return None

def parse_one_page(html):
    pattern = re.compile(
        '
.*?board-index.*?>(.*?).*?data-src="(.*?)".*?name.*?a.*?>(.*?).*?star.*?>(.*?)
.'
        '*?releasetime.*?>(.*?)
.*?integer.*?>(.*?).*?fraction.*?>(.*?).*?
',
        re.S)
    items = re.findall(pattern, html)
    for item in items:
        yield {
            'index': item[0],
            'image': item[1],
            'title': item[2],
            'actor': item[3].strip()[3:],
            'time': item[4].strip()[5:],
            'score': item[5] + item[6],
        }

def main(offset=0):
    url = 'http://maoyan.com/board/4?offset=' + str(offset)
    html = get_page(url)
    for item in parse_one_page(html):
        print(item)

if __name__ == '__main__':
    for i in range(5):
        main(offset=i * 10)
        time.sleep(1)


# https://leetcode.com/problems/intersection-of-two-linked-lists/
# tags: #must_do_easy_questions, #top_interview_questions
#
# Solution: Length difference
# Calculate lengths of both lists and evaluate difference.
# Make this number of steps for the longest list, pointer p1 and pointer p2 put to start of short list.
# Move pointers p1 and p2 one by one until we have the same value:
# it will be either common element or it will be None element.
# Time complexity: O(m + n), Space complexity: O(1)
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __str__(self):
        return self.val

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        def get_length(list_node: ListNode) -> int:
            if not list_node:
                return 0

            current = list_node
            count = 1

            while current:
                count += 1
                current = current.next

            return count

        length_a = get_length(headA)
        length_b = get_length(headB)
        delta = abs(length_a - length_b)

        shortest = headA if length_a < length_b else headB
        current_shortest = shortest
        longest = headA if current_shortest == headB else headB
        current_longest = longest

        for _ in range(delta):
            current_longest = current_longest.next

        while current_shortest and current_shortest is not current_longest:
            current_shortest = current_shortest.next
            current_longest = current_longest.next

        return current_shortest

if __name__ == "__main__":
    headA = ListNode(1)
    headA.next = ListNode(9)
    headA.next.next = ListNode(1)

    headB = ListNode(3)

    headC = ListNode(2)
    headC.next = ListNode(4)

    headA.next.next.next = headC
    headB.next = headC

    sol = Solution()
    print(sol.getIntersectionNode(headA, headB))


from abc import ABC, abstractmethod
from typing import Dict, Optional, Tuple

import tensorflow as tf
import tensorflow_datasets as tfds

class Dataset(ABC):
    """
    An abstract base class to encapsulate a dataset. Concrete sub-classes must
    implement the `train` method, and optionally the `validation` method.
    """

    @abstractmethod
    def train(self, decoders=None) -> Tuple[tf.data.Dataset, int]:
        """
        Return a tuple of the training dataset and the number of training
        examples in the dataset.
        """

        raise NotImplementedError

    def validation(self, decoders=None) -> Tuple[tf.data.Dataset, int]:
        """
        Return a tuple of the validation dataset and the number of validation
        examples in the dataset. By default, raises an error that no validation
        data is provided.
        """

        raise ValueError(
            f"Dataset '{self.__class__.__name__}' is not configured with validation "
            "data."
        )

def base_splits(split):
    """
    Splits can be merged, e.g. `tfds.Split.TRAIN + tfds.Split.Validation` or
    `"train+validation"`. For such composite splits, find and return a list of
    'base splits'.
    """

    if "+" in split:
        return split.split("+")
    elif isinstance(split, tfds.core.splits._SplitMerged):
        return base_splits(split._split1) + base_splits(split._split2)  # type: ignore
    return [split]

class TFDSDataset(Dataset):
    """
    A wrapper around a TensorFlowDatasets dataset.
    """

    # The TensorFlowDatasets name, which may specify a builder config and/or
    # version, e.g. "imagenet2012:4.0.0"
    name: str

    # The directory that the dataset is stored in.
    data_dir: Optional[str] = None

    # Train and validation splits. A validation split is not required.
    train_split: str
    validation_split: Optional[str] = None

    @property
    def info(self):
        if not hasattr(self, "_info"):
            self._info = tfds.builder(self.name, data_dir=self.data_dir).info
        return self._info

    @property
    def splits(self):
        return self.info.splits

    @property
    def num_classes(self) -> int:
        try:
            features = self.info.features
            if "label" in features:
                return features["label"].num_classes
            if "labels" in features:
                return features["labels"].feature.num_classes
            if "objects" in features and "label" in features["objects"]:
                return features["objects"]["label"].num_classes
        except Exception:
            pass
        raise ValueError("Unable to determine the number of classes.")

    def num_examples(self, split) -> int:
        """Compute the number of examples in a given split."""

        return sum(self.splits[s].num_examples for s in base_splits(split))

    def load(self, split, decoders, shuffle) -> tf.data.Dataset:
        """Return a `tf.data.Dataset` object representing the requested split."""

        return tfds.load(
            name=self.name,
            split=split,
            data_dir=self.data_dir,
            decoders=decoders,
            as_dataset_kwargs={"shuffle_files": shuffle},
        )

    def train(self, decoders=None) -> Tuple[tf.data.Dataset, int]:
        return (
            self.load(self.train_split, decoders=decoders, shuffle=True),
            self.num_examples(self.train_split),
        )

    def validation(self, decoders=None) -> Tuple[tf.data.Dataset, int]:
        if self.validation_split is None:
            raise ValueError(
                f"Dataset {self.__class__.__name__} is not configured with a "
                "validation split."
            )
        return (
            self.load(self.validation_split, decoders=decoders, shuffle=False),
            self.num_examples(self.validation_split),
        )

class MultiTFDSDataset(Dataset):
    """
    A wrapper around multiple TensorFlowDatasets datasets. This allows a model
    to be trained on data that is combined from multiple datasets.
    """

    # A non-empty mapping from dataset names as keys to splits as values. The
    # training data will be the concatenation of the datasets loaded from each
    # (key, value) pair.
    train_split: Dict[str, str]

    # As above, a mapping from dataset names as keys to splits as values. May be
    # empty, indicating no validation data.
    validation_split: Dict[str, str] = {}

    # The directory that the dataset is stored in.
    data_dir: Optional[str] = None

    def num_examples(self, splits) -> int:
        """
        Compute the total number of examples in the splits specified by the
        dictionary `splits`.
        """

        return sum(
            tfds.builder(name, data_dir=self.data_dir).info.splits[s].num_examples
            for name, split in splits.items()
            for s in base_splits(split)
        )

    def load(self, splits, decoders, shuffle) -> tf.data.Dataset:
        result = None
        for name, split in splits.items():
            dataset = tfds.load(
                name=name,
                split=split,
                data_dir=self.data_dir,
                decoders=decoders,
                as_dataset_kwargs={"shuffle_files": shuffle},
            )
            result = result.concatenate(dataset) if result is not None else dataset
        return result

    def train(self, decoders=None):
        return (
            self.load(self.train_split, decoders=decoders, shuffle=True),
            self.num_examples(self.train_split),
        )

    def validation(self, decoders=None):
        return (
            self.load(self.validation_split, decoders=decoders, shuffle=False),
            self.num_examples(self.validation_split),
        )


from os import *
from sys import *
from collections import *
from math import *

cnt = 0

def mergesort(arr):
    global cnt
    if len(arr)==1:
        return arr

    elif len(arr)==2:
        if arr[0]>arr[1]:
            cnt+=1
            return [arr[1],arr[0]]
        else:
            return arr
    else:
        left = mergesort(arr[:len(arr)//2])[::-1]
        right = mergesort(arr[len(arr)//2:])[::-1]

        l = []
        while left and right:
            if left[-1]<right[-1]:
                l.append(left.pop())
            else:
                cnt+=len(left)
                l.append(right.pop())
        while left:
            l.append(left.pop())
        while right:
            l.append(right.pop())
        return l

def getInversions(arr, n) :
	mergesort(arr)
	return cnt

# Taking inpit using fast I/O.
def takeInput() :
    n = int(input())
    arr = list(map(int, stdin.readline().strip().split(" ")))
    return arr, n

# Main.
arr, n = takeInput()
print(getInversions(arr, n))


import sys
input = sys.stdin.readline

def do():
  A, B = input().split()
  A = A[::-1]
  B = int(B)
  res = 0
  for i in range(len(A) - 1, -1, -1):
    e = (ord(A[i]) - 55) if (A[i].isalpha()) else int(A[i])
    res += e*(B**i)
  print(res)

do()


import sys

accum = 0
with open(sys.argv[1], "rt") as fd:
    for line in fd:
        line = line.strip()
        a, b = [ [int(x) for x in y.split("-")] for y in line.split(",")]

        if not ((a[0] > b[1] or a[1] < b[0])):
            accum += 1
print(accum)


"""
Created on Fri Nov  4 12:53:02 2022
"""

import pandas as pd
df = pd.read_csv("Sales.csv")
df.shape
df.head()

df.dtypes
# Label encode
from sklearn.preprocessing import LabelEncoder
LE = LabelEncoder()
df['ShelveLoc'] = LE.fit_transform(df['ShelveLoc'])
df['Urban'] = LE.fit_transform(df['Urban'])
df['US'] = LE.fit_transform(df['US'])

df.head()

X = df.iloc[:,1:11]
Y = df['high']

# data partition
from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.30)

# model fitting #
#from sklearn.tree import DecisionTreeRegressor

from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion='entropy', max_depth=5)
classifier.fit(X_train, Y_train)

print("Node counts:",classifier.tree_.node_count)
print("max depth:",classifier.tree_.max_depth)

Y_pred_train = classifier.predict(X_train)
Y_pred_test = classifier.predict(X_test)

from sklearn.metrics import accuracy_score
Training_acc = accuracy_score(Y_train,Y_pred_train).round(2)
Test_acc = accuracy_score(Y_test,Y_pred_test).round(2)

print("Training_accuracy: ",Training_acc.round(2))
print("Test_accuracy: ",Test_acc.round(2))

# 10  -->100,69
# 9   -->99,72
# 8   -->98,71
# 7   -->96,72
# 6   -->93,72
# 5   -->89,72
# 4   -->81,61


import sqlite3
def category_dishwasher(price):
    max = 1649
    return((price*6)/max)

def category_electric_stovetop(price):
    max = 3999
    return((price*6)/max)

def category_gas_stovetop(price):
    max = 4049
    return((price*6)/max)

def category_microwave(price):
    max = 619
    return((price*6)/max)

def category_radiator(price):
    max = 2599
    return((price*6)/max)

def category_oven(price):
    max = 3402
    return((price*6)/max)

def category_refrigerator(price):
    max = 6744
    return((price*6)/max)

def category_range_hood(price):
    max = 749
    return((price*6)/max)

def do_script(c,q):
    c.execute("INSERT INTO appliance(type, name, price, category) VALUES(?,?,?,?)", q)

con = sqlite3.connect('recomm-ai.db')

cur = con.cursor()

# Create table
try:
    cur.execute("CREATE TABLE appliance(id INTEGER PRIMARY KEY AutoIncrement, type TEXT NOT NULL, name TEXT NOT NULL, price FLOAT NOT NULL, category FLOAT NOT NULL);")
except:
    cur.execute("DROP TABLE appliance;")
    cur.execute("CREATE TABLE appliance(id INTEGER PRIMARY KEY AutoIncrement, type TEXT NOT NULL, name TEXT NOT NULL, price FLOAT NOT NULL, category FLOAT NOT NULL);")

# appliance: dishwasher
lang_list = [
    "dishwasher",#tipo
    "Samsung DW60M6050FS", #marca
    599,#price
    category_dishwasher(599),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "Beko DFN28430X", #marca
    479,#price
    category_dishwasher(479),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "Beko DFN16420X", #marca
    394,#price
    category_dishwasher(394),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "OK ODW 131 F", #marca
    249,#price
    category_dishwasher(249),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "AEG FSE73727P", #marca
    799,#price
    category_dishwasher(799),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "Miele G 5210 SC EDST", #marca
    1019,#price
    category_dishwasher(1019),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "Bosch KAD93VIFP", #marca
    1943,#price
    category_dishwasher(1943),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "Infiniton DIW-4510W", #marca
    349,#price
    category_dishwasher(349),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "AEG FFB83806PM", #marca
    990,#price
    category_dishwasher(990),#category
]
do_script(cur, lang_list)

lang_list = [
    "dishwasher",#tipo
    "Miele G 5000 SCI", #marca
    1099,#price
    category_dishwasher(1099),#category
]
do_script(cur, lang_list)

# appliance: electric_stovetop
lang_list = [
    "electric_stovetop",
    "UNIVERSALBLUE URAM1000-18",
    44.99,
    category_electric_stovetop(44.99),
]
do_script(cur, lang_list)

lang_list = [
    "electric_stovetop",
    "Haverland XTAL4B",
    386.0,
    category_electric_stovetop(386.0),
]
do_script(cur, lang_list)

lang_list = [
    "electric_stovetop",
    "Siemens ET475FYB1E",
    1779,
    category_electric_stovetop(1779),
]
do_script(cur, lang_list)

# appliance: gas_stovetop
lang_list = [
    "gas_stovetop",
    "OUTSUNNY",
    359.99,
    category_gas_stovetop(300),
]
do_script(cur, lang_list)

lang_list = [
    "gas_stovetop",
    "OUTSUNNY",
    69.99,
    category_gas_stovetop(69.99),
]
do_script(cur, lang_list)

lang_list = [
    "gas_stovetop",
    "Orbegozo H55",
    123,
    category_gas_stovetop(123),
]
do_script(cur, lang_list)

# appliance: microwave
lang_list = [
    "microwave",
    "Cecotec ProClean 5120",
    99.99,
    category_microwave(99.99),
]
do_script(cur, lang_list)

lang_list = [
    "microwave",
    "Taurus Ready",
    66.99,
    category_microwave(66.99),
]
do_script(cur, lang_list)

lang_list = [
    "microwave",
    "Teka MLC 844",
    780,
    category_microwave(780),
]
do_script(cur, lang_list)

# appliance: oven
lang_list = [
    "oven",
    "Balay 3HB4331X0",
    299,
    category_oven(299),
]
do_script(cur, lang_list)

lang_list = [
    "oven",
    "BASTILIPO Pisa",
    44.95,
    category_oven(44.95),
]
do_script(cur, lang_list)

lang_list = [
    "oven",
    "Smeg A1PY-9",
    3402,  # price
    category_oven(3402),  # category
]
do_script(cur, lang_list)

# appliance: radiator
lang_list = [
    "radiator",
    "Supra Orphée 12 FR9010800B",
    2599,
    category_radiator(2599),
]
do_script(cur, lang_list)

lang_list = [
    "radiator",
    "PURLINE MUSIA",
    499.95,
    category_radiator(499.95),
]
do_script(cur, lang_list)

lang_list = [
    "radiator",
    "BASTILIPO 2765 ET-EcoFluid-4",
    195.79,
    category_radiator(195.79),
]
do_script(cur, lang_list)

# appliance: refrigerator
lang_list = [
    "refrigerator",
    "SOGO",
    64.99,
    category_refrigerator(64.99),
]
do_script(cur, lang_list)

lang_list = [
    "refrigerator",
    "LG LSR200B",
    6744,
    category_refrigerator(6744),
]
do_script(cur, lang_list)

lang_list = [
    "refrigerator",
    "Haier F+ Series 9 HFF-750CGBJ",
    3380,
    category_refrigerator(3380),
]
do_script(cur, lang_list)

# appliance: range_hood
lang_list = [
    "range_hood",
    "Siemens LZ20JXP00",
    772.50,
    category_range_hood(772.50),
]
do_script(cur, lang_list)

lang_list = [
    "range_hood",
    "SCHNEIDER SCHB98EX",
    264.90,
    category_range_hood(264.90),
]
do_script(cur, lang_list)

lang_list = [
    "range_hood",
    "SCHNEIDER SCHC6018WH",
    74.90,
    category_range_hood(74.90),
]
do_script(cur, lang_list)

# Save (commit) the changes
con.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
con.close()


class Page:
    class Field:
        content     = "content"
        first       = "first"
        last        = "last"
        sort        = "sort"
        size        = "size"
        total_pages = "totalPages"
        total_elems = "totalElements"
        num_elems   = "numberOfElements"
        curr_page   = "number"

class Service:
    class Field:
        id           = "_id"
        service_id   = "serviceId"
        service_name = "serviceName"
        description  = "description"
        thumbnail    = "thumbnail"
        swagger      = "swagger"
        sameple_data = "sampleData"
        app_link     = "appLink"
        video_link   = "videoLink"
        owner        = "owner"
        endpoint     = "endpoint"
        created_at   = "createdAt"
        updated_at   = "updatedAt"
        code         = "code"
        kind         = "kind"
        keyword      = "keyword"

class User:
    class Field:
        user_id = "userId"
        username = "userName"
        fname = "firstName"
        lname = "lastName"
        email = "email"
        token = "accessToken"


from threading import Thread

from tests_main import AllowedConn
from tests_abs import Sender

class SenderConn(Sender):

    def __init__(self):
        super().__init__()
        self._process = Thread

    def start_process(self, target: str, port: int):
        try:
            _socket, addr = self.conn_info(target, port)
            _allower = AllowedConn()
            threads = [self._process(target=_allower._allowed, args=(_socket, self, addr[0], addr[1]))]
            [thread.start() for thread in threads]
            print("")
            msg = input()
            while True:
                self.put(msg)
                msg = input()

            [thread.join() for thread in threads]
            print(threads.result)
            _socket.close()
            exit()

        except Exception as err:
            print("## Error\t:: %s" % err)

if __name__ == '__main__':
    _task = SenderConn()
    _task.start_process(target=input("::\tINPUT TARGET: "), port=int(input("::\tINPUT PORT FROM LOCAL: ")))


#!/usr/bin/env python3
"""
Primary module for generating release notes from Jira

@author Martin Proffitt <martin.proffitt@hpe.com>
@package pyccata.core

"""
from datetime import datetime
from pyccata.core.document import DocumentController

class ReleaseNote(object):
    """
    Contains the structure for generating release notes
    by collating the issue ID, release note text and business
    representative for all issues assigned to the current
    fix version which are in state done but not in state
    rejected.
    """

    CONFIGURATION = 'releasenote.json'
    _document_controller = None
    _document_ready = False
    _document_title = 'MSS Platform Release'

    def __init__(self):
        """ initialise the ReleaseNote object """
        self._document_controller = DocumentController(self.CONFIGURATION)

    def build_document(self):
        """ Creates the document structure """
        try:
            self._document_controller.build()
            self._document_ready = True
        except:
            self._document_ready = False
            raise

    def publish(self):
        """ publish the document """
        if not self._document_ready:
            self.build_document()

        date = datetime.strftime(datetime.now(), '%Y-%m-%d')
        self._document_controller.format_for_email()
        self._document_controller.save(self._document_title + ' ' + date + '.docx')

if __name__ == "__main__":
    release_note = ReleaseNote()
    release_note.build_document()
    release_note.publish()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Shutter module
#
# Thiebolt  aug.19  updated
# Francois  apr.16  initial release
#

import time
import json
import threading
import paho.mqtt.client as mqtt_client
import os
import sys
from connection import Objet
import RPi.GPIO as GPIO

#GREEN/UP LED
PIN_UP = 6
#RED/DOWN LED
PIN_DOWN = 12
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_UP,GPIO.OUT)
GPIO.output(PIN_UP,GPIO.LOW)
GPIO.setup(PIN_DOWN,GPIO.OUT)
GPIO.output(PIN_DOWN,GPIO.LOW)

class Shutter(Objet):

    # class attributes
    SHUTTER_POS_CLOSED  = 0
    SHUTTER_POS_OPEN    = 1
    SHUTTER_POS_BETWEEN = 2

    SHUTTER_ACTION_CLOSE    = 0
    SHUTTER_ACTION_OPEN     = 1
    SHUTTER_ACTION_STOP     = 2
    SHUTTER_ACTION_IDLE     = 3
    SHUTTER_ACTION_UNKNOWN  = 4

    SHUTTER_TYPE_WIRED = 0
    SHUTTER_TYPE_WIRELESS = 1

    MQTT_TYPE_TOPIC = "shutter"

    # Min. and max. values for shutter course time
    MIN_COURSE_TIME         = 5
    MAX_COURSE_TIME         = 60

    # attributes
    _status = None
    shutterType = SHUTTER_TYPE_WIRED
    courseTime  = 30;       # (seconds) max. time for shutter to get fully open / close

    _backend    = None      # current backends
    _upOutput   = None
    _downOutput = None
    _stopOutput = None

    _curCmd     = None
    _condition  = None      # threading condition
    _thread     = None      # thread to handle shutter's course

    def __init__(self, unitID, MQTT_PUB_TOPIC,MQTT_SUB_TOPIC,MQTT_SERVER,MQTT_PORT, shutterType="wired", courseTime=30, io_backend=None, upOutput=None, downOutput=None, stopOutput=None, shutdown_event=None, *args, **kwargs):

        ''' Initialize object '''
        self._status = self.SHUTTER_POS_CLOSED
        self._curCmd = self.SHUTTER_ACTION_IDLE
        self.courseTime = courseTime
        super().__init__(unitID,MQTT_PUB_TOPIC,MQTT_SUB_TOPIC,MQTT_SERVER,MQTT_PORT)

    def set_status(self):
        # end of command execution
        self._status = self.SHUTTER_POS_OPEN if self._curCmd == self.SHUTTER_ACTION_OPEN else self.SHUTTER_POS_CLOSED
        self.curCmd = self.SHUTTER_ACTION_IDLE
        GPIO.output(PIN_UP,GPIO.LOW)
        GPIO.output(PIN_DOWN,GPIO.LOW)
        # on completion send status
        data = {
                    "unitID": self.unitID,
                    "status": self._status,
                    "order": "UP" if self._curCmd == self.SHUTTER_ACTION_OPEN else "DOWN"
                }
        data_out = json.dumps(data)
        self.connection.publish(self.mqtt_pub_topic, data_out)

    def on_message(self, client, userdata, msg):

        payload = json.loads(msg.payload)
        if( self.unitID is not None and ( payload['dest'] == "all" or payload['dest'] == str(self.unitID) )):
            data = {
                    "unitID": self.unitID,
                    "status": self._status,
                    "order": payload['order']
                }
            print(data)
            data_out = json.dumps(data)

            # send current status
            self.connection.publish(self.mqtt_pub_topic, data_out)

            #execute the commande
            if payload['order'] == "UP":
               if(self._curCmd != self.SHUTTER_ACTION_OPEN and self._status != self.SHUTTER_POS_OPEN):
                   self._curCmd = self.SHUTTER_ACTION_OPEN
                   # turn on the up led and set new status to between
                   GPIO.output(PIN_UP,GPIO.HIGH)
                   GPIO.output(PIN_DOWN,GPIO.LOW)
                   self._status = self.SHUTTER_POS_BETWEEN
                   # start a timer to courseTime seconds
                   self._thread = threading.Timer( self.courseTime, self.set_status)
                   self._thread.start()
                   print("timer started")

            elif payload['order'] =="DOWN":
                # change the current cmd and execute close order
                if(self._curCmd != self.SHUTTER_ACTION_CLOSE and self._status != self.SHUTTER_POS_CLOSED):
                   self._curCmd = self.SHUTTER_ACTION_CLOSE
                   # turn on the up led and set new status to between
                   GPIO.output(PIN_UP,GPIO.LOW)
                   GPIO.output(PIN_DOWN,GPIO.HIGH)
                   self._status = self.SHUTTER_POS_BETWEEN
                   # start a timer to courseTime seconds
                   self._thread = threading.Timer( self.courseTime, self.set_status)
                   self._thread.start()
                   print("timer started")

            elif payload['order'] =="STOP":
                # cancel the current command end set the status to between if not on idle status
                if (self._curCmd != self.SHUTTER_ACTION_IDLE):
                    self._thread.cancel()
                    self._status = self.SHUTTER_POS_BETWEEN
                    self.curCmd = self.SHUTTER_ACTION_IDLE
                    GPIO.output(PIN_UP,GPIO.LOW)
                    GPIO.output(PIN_DOWN,GPIO.LOW)
                    # on completion send status
                    data = {
                                "unitID": self.unitID,
                                "status": self._status,
                                "order": payload['order']
                            }
                    data_out = json.dumps(data)
                    self.connection.publish(self.mqtt_pub_topic, data_out)

            elif payload['order'] =="STATUS":
                # already sent the status
                return

            else:
                print("invalid command")

#
# MAIN
#

def main():

    #TODO: implement simple tests of your module
    return

# Execution or import
if __name__ == "__main__":

    # Logging setup
    '''logging.basicConfig(format="[%(asctime)s][%(module)s:%(funcName)s:%(lineno)d][%(levelname)s] %(message)s", stream=sys.stdout)
    log = logging.getLogger()

    print("\n[DBG] DEBUG mode activated ... ")
    log.setLevel(logging.DEBUG)'''
    #log.setLevel(logging.INFO)

    # Start executing
    main()

# The END - Jim Morrison 1943 - 1971
#sys.exit(0)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Curtis Yu
@contact: cuyu@splunk.com
@since: 8/23/17
"""
class XrangeIterator(object):
    def __init__(self, start, stop=None, step=1):
        if stop:
            self.start = start
            self.stop = stop
        else:
            self.start = 0
            self.stop = start
        self.step = step
        self.current = self.start

    def __iter__(self):
        self.current = self.start
        return self

    def next(self):
        if self.step > 0:
            condition = self.current < self.stop
        else:
            condition = self.current > self.stop
        if condition:
            value = self.current
            self.current += self.step
            return value
        else:
            raise StopIteration

def xrange(start, stop=None, step=1):
    """
    Return a iterator containing an arithmetic progression of integers.
    xrange(i, j) returns i, i+1, i+2, ..., j-1 on demand; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns 0, 1, 2, 3. The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

    Usage and test:
    assert list(xrange(4)) == [0,1,2,3]
    assert list(xrange(1,4)) == [1,2,3]
    assert list(xrange(2,10,2)) == [2,4,6,8]
    assert list(xrange(10,6,-1)) == [10,9,8,7]
    assert list(xrange(10,6,-2)) == [10,8]

    Memory usage:
    please use memory at O(1) complexity.

    Plus if support:
    c = xrange(4)
    assert list(c) == [0,1,2,3]
    assert list(c) == [0,1,2,3]
    """
    return XrangeIterator(start, stop, step)

if __name__ == '__main__':
    assert list(xrange(4)) == [0, 1, 2, 3]
    assert list(xrange(1,4)) == [1,2,3]
    assert list(xrange(2,10,2)) == [2,4,6,8]
    assert list(xrange(10,6,-1)) == [10,9,8,7]
    assert list(xrange(10,6,-2)) == [10,8]
    c = xrange(4)
    assert list(c) == [0,1,2,3]
    assert list(c) == [0,1,2,3]


#!/usr/bin/env python3
import argparse
import os
from timeit import default_timer as timer
import wave
from pydub import AudioSegment, effects
import json

# Arguments
parser = argparse.ArgumentParser(description="Running Vosk speaker ID test.")
parser.add_argument("-f", "--folder", default="../test-files/", help="""Folder with speaker test WAV files.
Please name your files ref-[ID]-[n].wav and test-[ID]-[n].wav, e.g.: ref-S1-1.wav etc..""")
parser.add_argument("-m", "--model", default="models/vosk-model-small-en-us-0.15", help="Path to model")
parser.add_argument("-c", "--chunk-size-ms", default=1000, help="Chunk size for streaming in ms (default: 1000)")
args = parser.parse_args()

import numpy as np
from vosk import Model, KaldiRecognizer, SpkModel, SetLogLevel

# Vosk log level - -1: off, 0: normal, 1: more verbose
SetLogLevel(-2)

print("Loading model and recognizer ...")
model_path = args.model
spk_model = "models/vosk-model-spk-0.4"
model_load_start = timer()
model = Model(model_path)
rec = KaldiRecognizer(model, 16000)
rec.SetSpkModel(SpkModel(spk_model))
print(f"Took {(timer() - model_load_start):.2f}s.")

chunk_size_ms = int(args.chunk_size_ms)
print(f"Chunk size for streaming: {chunk_size_ms}ms = {(chunk_size_ms*16)} samples")

speakers = []
speaker_ids = []
wrong_ids = 0
correct_ids = 0

def cosine_dist(x, y):
    nx = np.array(x)
    ny = np.array(y)
    return 1 - np.dot(nx, ny) / np.linalg.norm(nx) / np.linalg.norm(ny)

def analyze_speaker(file_name, res):
    global correct_ids, wrong_ids
    this_id = file_name.split('-')[1]
    print(f"This ID: {this_id}")
    best_dist = 2
    best_id = None
    for id, spkr in enumerate(speakers):
        dist = cosine_dist(spkr, res["spk"])
        if dist < best_dist:
            best_dist = dist
            best_id = speaker_ids[id]
        print(f"Speaker distance: {speaker_ids[id]} = {dist:.2f}")
    if best_id is not None:
        print(f"Best match: {best_id} = {best_dist:.2f}")
        if this_id == best_id:
            print("CORRECT")
            correct_ids += 1
        elif this_id not in speaker_ids:
            print("UNKNOWN")
        else:
            print("WRONG")
            wrong_ids += 1

def store_speaker(file_name, res):
    speakers.append(res['spk'])
    speaker_ids.append(file_name.split("-")[1])

def transcribe(audio_file_name, do_store_speaker):
    audio_file = args.folder + audio_file_name
    print(f'\n---- Loading audio file: {audio_file}')
    audio = AudioSegment.from_file(audio_file, format="wav")
    sample_rate_orig = audio.frame_rate
    audio_length = audio.duration_seconds
    if (audio.channels != 1 or audio.sample_width != 2
        or sample_rate_orig != 16000):
        print("Audio file must be WAV format mono PCM.")
        exit (1)
    #print(f"Max audio amp.: {(audio.max/32768):.2f}")
    print(f"Max audio amp.: {audio.max_dBFS:.2f} dB")
    #audio = effects.normalize(audio)
    #print(f"Max audio amp. after norm.: {audio.max}")
    print(f'Samplerate: {sample_rate_orig}, length: {audio_length}s')

    print("Running chunked inference ...")
    start_time = timer()

    #chunk_size = 25000  # 250ms = 4000 samples
    for i in range(0, len(audio), chunk_size_ms):
        chunk = audio[i:i+chunk_size_ms]
        if rec.AcceptWaveform(chunk.raw_data):
            res = json.loads(rec.Result())
            print(f"Out: {res['text']}")
            if "spk" in res:
                if do_store_speaker:
                    store_speaker(audio_file_name, res)
                else:
                    analyze_speaker(audio_file_name, res)

    res = json.loads(rec.FinalResult())
    print(f"Out: {res['text']}")
    if "spk" in res:
        if do_store_speaker:
            store_speaker(audio_file_name, res)
        else:
            analyze_speaker(audio_file_name, res)
    print(f"Took: {(timer() - start_time):.2f}s")

test_files = os.listdir(args.folder)

print("\n---- Get reference speakers ...")
for file in test_files:
    if file.startswith("ref") and file.endswith(".wav"):
        transcribe(file, True)

print("\n---- Test speakers ...")
for file in test_files:
    if file.startswith("test") and file.endswith(".wav"):
#    if file.endswith(".wav"):
        transcribe(file, False)

print(f"\nDetected correct: {correct_ids}")
print(f"Detected wrong: {wrong_ids}")


# Run a term query against UberEats
# External dependencies:
# yab https://code.uberinternal.com/w/rpc/yab
# jq  https://stedolan.github.io/jq/

import os, sys, getopt, tempfile, time
import datetime

helpstr = 'eatsQuery.py --lat=37.77493 --long=-122.41942 --cityID=1 --starttime=1582722000 --endtime=1582729200 --query="pizza" --limit=10'
browser = "Google Chrome.app"

def main(argv):
   peer = "--peer-list /etc/uber/hyperbahn/hosts.json"
   latitude = 37.77493
   longitude = -122.41942
   cityID = 1
   starttime = 1582722000
   endtime= 1582729200
   query = "pizza"
   limit = 10

   try:
      opts, args = getopt.getopt(argv,"ha:o:c:st:et:q:l:",["help","lat=","long=","cityID=","starttime=","endtime=","query=","limit="])
   except getopt.GetoptError:
      print("Cmdline parsing error:")
      print(helpstr)
      sys.exit(1)
   for opt, arg in opts:
      if opt in ('-h', '--help'):
         print("Usage:")
         print(helpstr)
         sys.exit(0)
      elif opt in ("-a", "--lat"):
         latitude = arg
      elif opt in ("-o", "--long"):
         longitude = arg
      elif opt in ("-c", "--cityID"):
         cityID = arg
      elif opt in ("-st", "--starttime"):
         starttime = arg
      elif opt in ("-st", "--endtime"):
         endtime= arg
      elif opt in ("-q", "--query"):
         query = arg
      elif opt in ("-l", "--limit"):
         limit = arg

   #print 'Peer ', peer
   #print 'Lat ', latitude
   #print 'Long ', longitude
   #print 'City ', cityID
   #print 'starttime' , starttime
   #print 'endtime' , endtime
   #print 'Query ', query

   if latitude==0 or longitude==0 or cityID==0 or starttime==0 or endtime==0 or query=="":
      print("Missing arguments:")
      print(helpstr)
      sys.exit(2)

   host = "adhoc01-dca8"
   yabcmdline='yab  '+peer+'  --thrift /usr/share/uber-idl/code.uber.internal/everything/monostore/storeindex.thrift  --service storeindex  --method StoreIndexService::termSearchQuery  -r \'\\\'\'{"request": { "radiusKm": 16, "maxTotalETASec": 7200, "location": { "latitude": '+str(latitude)+', "longitude": '+str(longitude)+', "cityId": '+str(cityID)+'}, "targetDeliveryTimeRange": {"starttime": '+str(starttime)+', "endtime":'+str(endtime)+' }, userQuery": "'+str(query)+'","queryConfig":{"enableFeedResponse":true,"useRichTextMarkup":true,"includeAccessibilityText":false,"isMenuV2Enabled":true}},"offset": 0,"limit": '+str(limit)+'}\' --headers=\'{"x-uber-uuid":"61c6a40a-c2f3-4c3d-aaa3-1d6237582eac", "x-uber-client-name":eats, "x-uber-client-version":"1.145.10001", "x-uber-device":iphone}\'\\\'\'  --timeout=5000 |  jq  "del(.body.result.feed.feedItems[].payload.storePayload.stateMapDisplayInfo) | del(.body.result.feed.storesMap) | del(.body.result.stores[].heroImage)"'
   print(yabcmdline)
   #print("ssh "+host+" \'"+yabcmdline+"\'")

   # Show output in terminal
   #os.system("ssh "+host+" \'"+yabcmdline+"\'")

   # Show output in browser
   jsonoutput = os.popen("ssh "+host+" \'"+yabcmdline+"\'").read()
   fd, fname = tempfile.mkstemp()
   os.write(fd, jsonoutput)
   os.close(fd)
   os.system("open -a \'"+browser+"\' "+fname)
   os.system("datetime.datetime.now()")
   time.sleep(1)
   os.unlink(fname)

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


import sys
import platform
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QIcon, QKeySequence, QLinearGradient, QPalette, QPainter, QPixmap, QRadialGradient)
from PySide2.QtWidgets import *
from login import Ui_LoginWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from Main import Ui_MainWindow

counter = 0

# SPLASH SCREEN
class SplashScreen(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.progress)
        # TIMER IN MILLISECONDS
        self.timer.start(40)
        QtCore.QTimer.singleShot(3400, lambda: self.ui.label_description.setText("LOADING DATABASE"))
        QtCore.QTimer.singleShot(4500, lambda: self.ui.label_description.setText("LOADING USER INTERFACE"))

        self.setWindowFlag(Qt.FramelessWindowHint)

        self.show()

    ########################################################################

    def progress(self):

        global counter

        # SET VALUE TO PROGRESS BAR
        self.ui.progressBar.setValue(counter)

        # CLOSE SPLASH SCREE AND OPEN APP
        if counter > 100:
            # STOP TIMER
            self.timer.stop()
            self.window = QMainWindow()
            self.ui = Ui_LoginWindow()
            self.ui.setupUi(self.window)
            self.window.show()
            self.close()

        # INCREASE COUNTER
        counter += 1

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SplashScreen()
    sys.exit(app.exec_())


import SpotifyPlaylist, converter, SpotifyCredentials, concurrent.futures
from googleapiclient.discovery import build

api_key = SpotifyCredentials.youtube_api_key
api_name = "youtube"
api_version = "v3"
youtube_prefix_link = "https://www.youtube.com/watch?v="

def returnURL(name: str) -> str:
    '''input search term, returns first youtube link'''
    with build(api_name,api_version,developerKey=api_key) as ytService:
        searchList = ytService.search().list(part="id",q=str(name),maxResults=1,type="video")
        # print(searchList.execute()["items"][0]["id"]["videoId"])
    print("found youtube URL for",name)
    return youtube_prefix_link+searchList.execute()["items"][0]["id"]["videoId"]

def returnURL_List(spotifyPlaylistURL: str) -> list:
    output = []
    spotifyobj = SpotifyPlaylist.SpotifyClass(SpotifyPlaylist.credentials_manager)
    tracks = spotifyobj.getPlaylistTracks(spotifyPlaylistURL)
    if (len(tracks)<10):
        for i in tracks:
            output.append(returnURL(i))
    else:
        with concurrent.futures.ThreadPoolExecutor() as executor:
            for i in tracks:
                output.append(executor.submit(returnURL,i).result())

    return output

if __name__ == "__main__":
    print(len(returnURL_List("https://open.spotify.com/playlist/2Xzh3AUllumMIUpoSP4pUg?si=3326b064ae624009")))


from __future__ import annotations

import inspect

import numpy as np

from manimlib.animation.animation import Animation
from manimlib.constants import DEGREES
from manimlib.constants import OUT
from manimlib.mobject.mobject import Group
from manimlib.mobject.mobject import Mobject
from manimlib.utils.paths import path_along_arc
from manimlib.utils.paths import straight_path

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import Callable
    import numpy.typing as npt
    from manimlib.scene.scene import Scene
    from manimlib.typing import ManimColor

class Transform(Animation):
    replace_mobject_with_target_in_scene: bool = False

    def __init__(
        self,
        mobject: Mobject,
        target_mobject: Mobject | None = None,
        path_arc: float = 0.0,
        path_arc_axis: np.ndarray = OUT,
        path_func: Callable | None = None,
        **kwargs
    ):
        self.target_mobject = target_mobject
        self.path_arc = path_arc
        self.path_arc_axis = path_arc_axis
        self.path_func = path_func
        super().__init__(mobject, **kwargs)
        self.init_path_func()

    def init_path_func(self) -> None:
        if self.path_func is not None:
            return
        elif self.path_arc == 0:
            self.path_func = straight_path
        else:
            self.path_func = path_along_arc(
                self.path_arc,
                self.path_arc_axis,
            )

    def begin(self) -> None:
        self.target_mobject = self.create_target()
        self.check_target_mobject_validity()

        if self.mobject.is_aligned_with(self.target_mobject):
            self.target_copy = self.target_mobject
        else:
            # Use a copy of target_mobject for the align_data_and_family
            # call so that the actual target_mobject stays
            # preserved, since calling align_data will potentially
            # change the structure of both arguments
            # 对齐操作会改变两个mobject的结构
            self.target_copy = self.target_mobject.copy()
        """
        以前有一个很大的疑问：如何对circle和square进行插值？
        它们的点集的数目是不一样的
        现在看来，这个问题的关键在于，如何对两个mobject进行对齐
        """
        self.mobject.align_data_and_family(self.target_copy)
        super().begin()
        if not self.mobject.has_updaters:
            self.mobject.lock_matching_data(
                self.starting_mobject,
                self.target_copy,
            )

    def finish(self) -> None:
        super().finish()
        self.mobject.unlock_data()
        #print("-"*100)
        #print("transform class finish method ===>")

    def create_target(self) -> Mobject:
        # Has no meaningful effect here, but may be useful
        # in subclasses
        return self.target_mobject

    def check_target_mobject_validity(self) -> None:
        if self.target_mobject is None:
            raise Exception(
                f"{self.__class__.__name__}.create_target not properly implemented"
            )

    def clean_up_from_scene(self, scene: Scene) -> None:
        """
        play函数真是黑箱啊
        这个clean_up_from_scene函数是在play的哪一个阶段执行的？
        应该是alpha = 1之后才执行

        通过print语句，发现这个函数是在finish函数之后执行的
        """
        #print("-"*100)
        #print("transform class clean_up_from_scene method ===>")
        super().clean_up_from_scene(scene)
        # 一个疑问：动画结束之后，self.mobject和self.target_mobject是不是相等的？
        # 如果相等，这里的remove和add操作是不是多余的？
        if self.replace_mobject_with_target_in_scene:
            scene.remove(self.mobject)
            scene.add(self.target_mobject)

    def update_config(self, **kwargs) -> None:
        Animation.update_config(self, **kwargs)
        if "path_arc" in kwargs:
            self.path_func = path_along_arc(
                kwargs["path_arc"],
                kwargs.get("path_arc_axis", OUT)
            )

    def get_all_mobjects(self) -> list[Mobject]:
        return [
            self.mobject,
            self.starting_mobject,
            self.target_mobject,
            self.target_copy,
        ]

    def get_all_families_zipped(self) -> zip[tuple[Mobject]]:
        return zip(*[
            mob.get_family()
            for mob in [
                self.mobject,
                self.starting_mobject,
                self.target_copy,
            ]
        ])

    # 特别注意，这个函数和父类的同名函数，参数个数不一致
    def interpolate_submobject(
        self,
        submob: Mobject,
        start: Mobject,
        target_copy: Mobject,
        alpha: float
    ):
        # 想知道这一行代码有没有被执行
        # print("linus"*5)
        # 经过测试，这一行确实被执行了
        # 进一步查看函数的参数
        # print(submob, start, target_copy, alpha)
        # 打印的参数也符合预期
        # 但我直接调用却会报错
        """
        终于找到了原因：因为没有alignment
        begin函数中有对齐操作
        只有对齐了之后的mob之间才能进行插值
        """

        # 这一行代码是没有返回值的，然而，我可以给它加一个
        """
        animation一般有self.mobject和self.target_mobject
        在animation开始的时候，会设置self.starting_mobject = self.mobject.copy()

        然后，在后续所有的插值过程中，都是通过self.starting_mobject和self.target_mobject
        来更新self.mobject的属性
        """
        submob.interpolate(start, target_copy, alpha, self.path_func)
        # mm = submob.interpolate(start, target_copy, alpha, self.path_func)
        # print(start.get_points())
        # print(mm.get_points())
        # mm和submob的points是变化的，start和target_copy的points是不变的
        return self

class ReplacementTransform(Transform):
    """
    经过实际测试，ReplacementTransform和Transform的效果是一样的
    """
    replace_mobject_with_target_in_scene: bool = True

class TransformFromCopy(Transform):
    """
    经过实际测试，TransformFromCopy和Transform的效果是一样的
    """
    replace_mobject_with_target_in_scene: bool = True

    def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs):
        super().__init__(mobject.copy(), target_mobject, **kwargs)

"""
frame = self.frame
frame.target = frame.generate_target()
frame.target.scale(1.75, about_edge=LEFT)
self.play(
    LaggedStartMap(
        FadeIn, VGroup(*blocks[10:30]),
        lag_ratio=0.9, # 将lag_ratio设置为0，所有的block同时出现
    ),
    MoveToTarget(frame, rate_func=rush_into),
    run_time=12,
    )
"""
"""
MoveToTarget这个类名字起得不好，容易让人误解
直观的印象就是将mobect移动到target的位置
但实际上，这个类的作用是将mobject的属性变成target的属性
包括点集，颜色，透明度等等

MoveToTarget这个类初始化需要一个mobject
给人的感觉是这个transform只需要一个对象
但实际上，这个类还需要一个target
只是这个target是通过拷贝mobject得到的
"""
"""
MoveToTarget这个类的作用是将mobject的属性变成target的属性
是现在的自己和过去的自己之间的一次变化
"""
class MoveToTarget(Transform):
    def __init__(self, mobject: Mobject, **kwargs):
        # 检查mobject是否有target属性
        self.check_validity_of_input(mobject)
        super().__init__(mobject, mobject.target, **kwargs)

    def check_validity_of_input(self, mobject: Mobject) -> None:
        if not hasattr(mobject, "target"):
            raise Exception(
                "MoveToTarget called on mobject without attribute 'target'"
            )

class _MethodAnimation(MoveToTarget):
    def __init__(self, mobject: Mobject, methods: list[Callable], **kwargs):
        self.methods = methods
        super().__init__(mobject, **kwargs)

"""
x = ValueTracker(0)
self.play(ApplyMethod(x.increment_value, 3, run_time=5))

self.play(ApplyMethod(sine.shift, 4*LEFT, **kwargs))

self.play(*[
            ApplyMethod(mob.scale, 0.5*random.random(), **kwargs)
            for mob in self.intervals
        ])

ApplyMethod类隐含了插值么？没搞懂

感觉用updater实现同样的效果更加简单
"""
class ApplyMethod(Transform):
    def __init__(self, method: Callable, *args, **kwargs):
        """
        method is a method of Mobject, *args are arguments for
        that method.  Key word arguments should be passed in
        as the last arg, as a dict, since **kwargs is for
        configuration of the transform itself

        Relies on the fact that mobject methods return the mobject
        """
        self.check_validity_of_input(method)
        self.method = method
        self.method_args = args
        # 需要注意，这里的参数method是mob.func这种格式
        # 所以，method.__self__是mob
        super().__init__(method.__self__, **kwargs)

    def check_validity_of_input(self, method: Callable) -> None:
        if not inspect.ismethod(method):
            raise Exception(
                "Whoops, looks like you accidentally invoked "
                "the method you want to animate"
            )
        assert(isinstance(method.__self__, Mobject))

    def create_target(self) -> Mobject:
        """
        这个函数会在begin函数中被调用
        但是在整个动画过程中，只会被调用一次

        而这个方法中
        method.__func__(target, *args, **method_kwargs)
        被调用了
        那么，这次的ApplyMethod不就一步到位了么？
        也就是说，动画在begin函数中就结束了

        困惑...
        搞错了，上述函数是设置了target的属性

        实际print后发现，执行method.__func__(target, *args, **method_kwargs)之后
        self.method.__self__.get_value()仍然是初始值
        """
        method = self.method
        # Make sure it's a list so that args.pop() works
        args = list(self.method_args)

        if len(args) > 0 and isinstance(args[-1], dict):
            method_kwargs = args.pop()
        else:
            method_kwargs = {}
        target = method.__self__.copy()
        # 函数被调用，为target设置属性
        # 这样target就准备好了，后续就可以插值了
        method.__func__(target, *args, **method_kwargs)

        #print("&"*100)
        #print(self.method.__self__.get_value())
        # 这里打印的是self.mobject的value值
        return target

class ApplyPointwiseFunction(ApplyMethod):
    """
    将function作用于mobject的每一个点

    本可以直接调用mob.apply_function(function)
    但是这样做的话，就没有动画效果了
    """
    def __init__(
        self,
        function: Callable[[np.ndarray], np.ndarray],
        mobject: Mobject,
        run_time: float = 3.0,
        **kwargs
    ):
        super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs)

class ApplyPointwiseFunctionToCenter(Transform):
    def __init__(
        self,
        function: Callable[[np.ndarray], np.ndarray],
        mobject: Mobject,
        **kwargs
    ):
        self.function = function
        super().__init__(mobject, **kwargs)

    def create_target(self) -> Mobject:
        return self.mobject.copy().move_to(self.function(self.mobject.get_center()))

class FadeToColor(ApplyMethod):
    def __init__(
        self,
        mobject: Mobject,
        color: ManimColor,
        **kwargs
    ):
        super().__init__(mobject.set_color, color, **kwargs)

class ScaleInPlace(ApplyMethod):
    def __init__(
        self,
        mobject: Mobject,
        scale_factor: npt.ArrayLike,
        **kwargs
    ):
        super().__init__(mobject.scale, scale_factor, **kwargs)

class ShrinkToCenter(ScaleInPlace):
    def __init__(self, mobject: Mobject, **kwargs):
        super().__init__(mobject, 0, **kwargs)

class Restore(Transform):
    def __init__(self, mobject: Mobject, **kwargs):
        if not hasattr(mobject, "saved_state") or mobject.saved_state is None:
            raise Exception("Trying to restore without having saved")
        super().__init__(mobject, mobject.saved_state, **kwargs)

class ApplyFunction(Transform):
    """
    和ApplyMethod类进行对比

    通过function对mobject进行变换，得到target
    然后执行插值操作
    """
    def __init__(
        self,
        function: Callable[[Mobject], Mobject],
        mobject: Mobject,
        **kwargs
    ):
        self.function = function
        super().__init__(mobject, **kwargs)

    def create_target(self) -> Mobject:
        target = self.function(self.mobject.copy())
        if not isinstance(target, Mobject):
            raise Exception("Functions passed to ApplyFunction must return object of type Mobject")
        return target

class ApplyMatrix(ApplyPointwiseFunction):
    def __init__(
        self,
        matrix: npt.ArrayLike,
        mobject: Mobject,
        **kwargs
    ):
        matrix = self.initialize_matrix(matrix)

        def func(p):
            return np.dot(p, matrix.T)

        super().__init__(func, mobject, **kwargs)

    def initialize_matrix(self, matrix: npt.ArrayLike) -> np.ndarray:
        matrix = np.array(matrix)
        if matrix.shape == (2, 2):
            new_matrix = np.identity(3)
            new_matrix[:2, :2] = matrix
            matrix = new_matrix
        elif matrix.shape != (3, 3):
            raise Exception("Matrix has bad dimensions")
        return matrix

class ApplyComplexFunction(ApplyMethod):
    def __init__(
        self,
        function: Callable[[complex], complex],
        mobject: Mobject,
        **kwargs
    ):
        self.function = function
        method = mobject.apply_complex_function
        super().__init__(method, function, **kwargs)

    def init_path_func(self) -> None:
        func1 = self.function(complex(1))
        self.path_arc = np.log(func1).imag
        super().init_path_func()

###

class CyclicReplace(Transform):
    def __init__(self, *mobjects: Mobject, path_arc=90 * DEGREES, **kwargs):
        super().__init__(Group(*mobjects), path_arc=path_arc, **kwargs)

    def create_target(self) -> Mobject:
        group = self.mobject
        target = group.copy()
        cycled_targets = [target[-1], *target[:-1]]
        for m1, m2 in zip(cycled_targets, group):
            m1.move_to(m2)
        return target

class Swap(CyclicReplace):
    """Alternate name for CyclicReplace"""
    pass


# Using Operators with Lists and Strings

hello = "hello"
world = "world"

helloworld = hello + " " + world
print(helloworld)

lotsofhellos = "hello" * 10
print(lotsofhellos)

even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)

print([1,2,3] * 3)

Other/Using Operators with Strings and Lists.py


from django.urls import path
from . import views

urlpatterns = [
    path('',views.test_prog,name='test_prog'),
    path('tasklist/',views.TaskList.as_view(),name='tasklist/'),
    path('taskdetail/<int:question_id>',views.taskdetail,name='taskdetail'),
    path('taskcreator/',views.TaskCreator.as_view(),name='taskcreator'),
    path('taskupdate/<int:question_id>/',views.taskupdate,name='taskupdate'),
    path('taskdelete/<int:question_id>/',views.taskdelete,name='taskdelete')
]