from PyQt6 import QtCore, QtGui, QtWidgets

progress_bar_style = """
QSlider::groove:horizontal {
background: rgba(0, 0, 0, 0);
height: 10px;
border-radius: 5px;
}

QSlider::sub-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(40, 113, 250, 150), stop:1 rgba(103, 23, 205, 150));
height: 10px;
border-radius: 5px;
}

QSlider::add-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(56, 56, 56, 150), stop:1 rgba(40, 40, 40, 150));
height: 10px;
}

QSlider::sub-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::add-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::handle:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border: 1px solid #aaa;
border-radius: 5px;
}
"""
controlled_progress_bar_style = """
QSlider::groove:horizontal {
background: rgba(0, 0, 0, 0);
height: 10px;
border-radius: 5px;
}

QSlider::sub-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(210, 90, 70, 0), stop:1 rgba(5, 240, 25, 0));
height: 10px;
border-radius: 5px;
}

QSlider::add-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(56, 56, 56, 0), stop:1 rgba(40, 40, 40, 0));
height: 10px;
}

QSlider::sub-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::add-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::handle:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border: 1px solid #aaa;
border-radius: 5px;
}
"""
volume_slider_style = """
QSlider::groove:horizontal {
background: rgba(0, 0, 0, 0);
height: 10px;
border-radius: 5px;
}

QSlider::sub-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(40, 113, 250, 150), stop:1 rgba(103, 23, 205, 150));
height: 10px;
border-radius: 5px;
}

QSlider::add-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(56, 56, 56, 150), stop:1 rgba(40, 40, 40, 150));
height: 10px;
}

QSlider::handle:horizontal {
background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
    stop:0 #eee, stop:1 #ccc);
border: 1px solid #777;
width: 13px;
margin-top: -2px;
margin-bottom: -2px;
border-radius: 6px;
}
QSlider::handle:horizontal:hover {
background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
    stop:0 #fff, stop:1 #ddd);
border: 1px solid #444;
border-radius: 6px;
}
QSlider::sub-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::add-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::handle:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border: 1px solid #aaa;
border-radius: 5px;
}"""
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.background = QtWidgets.QLabel(self.centralwidget)
        self.background.setGeometry(QtCore.QRect(0, 0, 801, 601))
        self.background.setText("")
        self.background.setPixmap(QtGui.QPixmap("music-player/src/BackGround-v5.png"))
        self.background.setScaledContents(True)
        self.cur_time = QtWidgets.QLabel(self.centralwidget)
        self.cur_time.setGeometry(QtCore.QRect(400, 180, 60, 20))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.cur_time.setFont(font)
        self.cur_time.setObjectName("cur_time")
        self.song_name = QtWidgets.QLabel(self.centralwidget)
        self.song_name.setGeometry(QtCore.QRect(400, 110, 380, 32))
        font = QtGui.QFont()
        font.setPointSize(24)
        self.song_name.setFont(font)
        self.song_name.setObjectName("song_name")
        self.total_time = QtWidgets.QLabel(self.centralwidget)
        self.total_time.setGeometry(QtCore.QRect(710, 180, 60, 20))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.total_time.setFont(font)
        self.total_time.setObjectName("total_time")
        self.volume_slider = QtWidgets.QSlider(self.centralwidget)
        self.volume_slider.setGeometry(QtCore.QRect(320, 550, 160, 25))
        self.volume_slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.volume_slider.setValue(88)
        self.volume_slider.setStyleSheet(volume_slider_style)
        self.volume_slider.setObjectName("volume_slider")
        self.progress_slider = QtWidgets.QSlider(self.centralwidget)
        self.progress_slider.setGeometry(QtCore.QRect(453, 185, 250, 10))
        self.progress_slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.progress_slider.setStyleSheet(progress_bar_style)
        self.progress_slider.setRange(0, 99)
        self.progress_slider.setValue(0)
        self.progress_slider.setTracking(False)
        self.progress_slider_controlled = QtWidgets.QSlider(self.centralwidget)
        self.progress_slider_controlled.setGeometry(QtCore.QRect(453, 185, 250, 10))
        self.progress_slider_controlled.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.progress_slider_controlled.setStyleSheet(controlled_progress_bar_style)
        self.progress_slider.setRange(0, 99)
        self.progress_slider_controlled.setValue(0)
        self.volume_button = QtWidgets.QPushButton(self.centralwidget)
        self.volume_button.setGeometry(QtCore.QRect(270, 540, 42, 42))
        self.volume_button.setAutoFillBackground(False)
        self.volume_button.setText("")
        iconV = QtGui.QIcon()
        iconV.addPixmap(QtGui.QPixmap("music-player/src/sound.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.volume_button.setIcon(iconV)
        self.volume_button.setIconSize(QtCore.QSize(42, 42))
        self.volume_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.loop_button = QtWidgets.QPushButton(self.centralwidget)
        self.loop_button.setGeometry(QtCore.QRect(200, 540, 42, 42))
        self.loop_button.setAutoFillBackground(False)
        self.loop_button.setText("")
        iconR = QtGui.QIcon()
        iconR.addPixmap(QtGui.QPixmap("music-player/src/loop.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.loop_button.setIcon(iconR)
        self.loop_button.setIconSize(QtCore.QSize(42, 42))
        self.loop_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.pause_button = QtWidgets.QPushButton(self.centralwidget)
        self.pause_button.setGeometry(QtCore.QRect(20, 540, 42, 42))
        self.pause_button.setAutoFillBackground(False)
        self.pause_button.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("music-player/src/pause.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.pause_button.setIcon(icon)
        self.pause_button.setIconSize(QtCore.QSize(32, 32))
        self.pause_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.pause_button.setObjectName("pause")
        self.hidenButton = QtWidgets.QPushButton(self.centralwidget)
        self.hidenButton.setGeometry(QtCore.QRect(20, 540, 42, 42))
        self.hidenButton.setAutoFillBackground(False)
        self.hidenButton.setText("")
        iconk = QtGui.QIcon()
        iconk.addPixmap(QtGui.QPixmap("music-player/src/pause.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.hidenButton.setIcon(iconk)
        self.hidenButton.setIconSize(QtCore.QSize(32, 32))
        self.hidenButton.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.hidenButton.hide()
        self.prev_button = QtWidgets.QPushButton(self.centralwidget)
        self.prev_button.setGeometry(QtCore.QRect(80, 540, 42, 42))
        self.prev_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.prev_button.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("music-player/src/prev.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.prev_button.setIcon(icon1)
        self.prev_button.setIconSize(QtCore.QSize(32, 32))
        self.prev_button.setCheckable(False)
        self.prev_button.setObjectName("prev")
        self.next_button = QtWidgets.QPushButton(self.centralwidget)
        self.next_button.setGeometry(QtCore.QRect(130, 540, 42, 42))
        self.next_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.next_button.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("music-player/src/next.png"), QtGui.QIcon.Mode.Active, QtGui.QIcon.State.Off)
        self.next_button.setIcon(icon2)
        self.next_button.setIconSize(QtCore.QSize(32, 32))
        self.next_button.setObjectName("next")
        self.settings_button = QtWidgets.QPushButton(self.centralwidget)
        self.settings_button.setGeometry(QtCore.QRect(718, 535, 45, 45))
        self.settings_button.setAutoFillBackground(False)
        self.settings_button.setText("")
        self.icon3 = QtGui.QIcon()
        self.icon3.addPixmap(QtGui.QPixmap("music-player/src/settings.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.settings_button.setIcon(self.icon3)
        self.settings_button.setIconSize(QtCore.QSize(42, 42))
        self.settings_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.add_song_button = QtWidgets.QPushButton(self.centralwidget)
        self.add_song_button.setGeometry(QtCore.QRect(720, 535, 42, 42))
        self.add_song_button.setAutoFillBackground(False)
        self.add_song_button.setText("")
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("music-player/src/folder.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.add_song_button.setIcon(icon4)
        self.add_song_button.setIconSize(QtCore.QSize(32, 32))
        self.add_song_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.add_song_button.hide()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", ""))
        self.cur_time.setText(_translate("MainWindow", "00:00"))
        self.song_name.setText(_translate("MainWindow", "Add music to folder"))
        self.total_time.setText(_translate("MainWindow", "03:00"))

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setFixedSize(320, 240)
        self.warning_background = QtWidgets.QLabel(Dialog)
        self.warning_background.setGeometry(QtCore.QRect(0, 0, 321, 241))
        self.warning_background.setText("")
        self.warning_background.setScaledContents(True)
        self.warning_background.setObjectName("warning_background")
        self.warning_background.setPixmap(QtGui.QPixmap("music-player/src/WarningBackGround.png"))
        self.warning_background.setScaledContents(True)
        self.info_label = QtWidgets.QLabel(Dialog)
        self.info_label.setGeometry(QtCore.QRect(70, 50, 180, 90))
        font = QtGui.QFont()
        font.setPointSize(22)
        font.setBold(False)
        font.setWeight(50)
        self.info_label.setFont(font)
        self.info_label.setScaledContents(False)
        self.info_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.info_label.setWordWrap(True)
        self.info_label.setObjectName("label")
        self.okey_button = QtWidgets.QPushButton(Dialog)
        self.okey_button.setGeometry(QtCore.QRect(105, 160, 110, 32))
        self.okey_button.setObjectName("pushButton")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", ""))
        self.info_label.setText(_translate("Dialog", "Добавьте музыку в папку"))
        self.okey_button.setText(_translate("Dialog", "Окей"))


import argparse
import os
import sys

import kernelci
from kernelci import print_color, shell_cmd

def add_date_commit(path, msg, fname):
    with open(os.path.join(path, fname), 'w') as f:
        f.write(msg)
    shell_cmd("""
cd {path}
git add {fname}
git commit --author='"kernelci.org bot" <bot@kernelci.org>' -am {msg}
""".format(path=path, fname=fname, msg=msg))

def main(args):
    path = os.path.join('checkout', args.project)
    print("path: {}".format(path))
    repo_name = '/'.join([args.namespace, args.project])
    print("repo: {}".format(repo_name))
    repo = kernelci.GITHUB.get_repo(repo_name)
    print("checking out {} {}".format(args.from_url, args.from_branch))
    kernelci.checkout_repository(path, repo, args.from_url, args.from_branch)
    patches_path = os.path.join('patches', args.project, args.branch)
    print("patches: {}".format(patches_path))
    if not kernelci.apply_patches(path, patches_path):
        print_color('red', "Aborting, all patches must apply.")
        return False
    tag = args.tag or kernelci.date_tag(path, args.tag_prefix)
    print("tag: {}".format(tag))
    add_date_commit(path, tag, args.branch)
    kernelci.create_tag(path, tag)
    if args.push:
        print("\nPushing tag ({}) and branch ({})".format(tag, args.branch))
        ssh_key = kernelci.default_ssh_key(args.ssh_key, args.branch)
        if not ssh_key:
            print_color('red', "No SSH key provided.")
            return False
        kernelci.push_tag_and_branch(path, ssh_key, args.branch, tag)
        if args.tag_limit:
            kernelci.delete_old_tags(args, path, ssh_key)
    return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser("\
Create a kernel branch to test KernelCI")
    parser.add_argument("--tag",
                        help="Tag to create, default is to use current date")
    parser.add_argument("--tag-prefix", default="staging-",
                        help="Prefix to create date with current date")
    parser.add_argument("--tag-limit", default="20", type=int,
                        help="Number of previous tags to keep, 0 for all")
    parser.add_argument("--branch", default="staging.kernelci.org",
                        help="Name of the branch to force-push to")
    parser.add_argument("--from-url", default=kernelci.TORVALDS_GIT_URL,
                        help="URL to pull from")
    parser.add_argument("--from-branch", default="master",
                        help="Branch to pull from")
    parser.add_argument("--namespace", default='kernelci',
                        help="Github project namespace")
    parser.add_argument("--project", default='linux',
                        help="Name of the Github project")
    parser.add_argument("--ssh-key",
                        help="Path to SSH key to push branches and tags")
    parser.add_argument("--push", action="store_true",
                        help="Push the resulting branch and tag")
    args = parser.parse_args(sys.argv[1:])
    ret = main(args)
    sys.exit(0 if ret is True else 1)


import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
clientSocket.connect(("127.0.0.1",9090));

minuladata = ""

# Print to the console
def sendsoc():
    global minuladata
    while(True):
        data = input()
        if data == "exit":
            break
        if (data == "") and (minuladata == ""):
            data = "b"
        clientSocket.send(data.encode())
        minuladata = data
        try:
            dataFromServer = clientSocket.recv(1024)
            readsoc(dataFromServer)
        except:
            pass

def readsoc(dataFromServer):
    if dataFromServer != "":
        print(dataFromServer.decode())
        dataFromServer = ""
        sendsoc()
    else:
        sendsoc()

sendsoc()


# getting types

# string
x = "Hello world"
print(type(x))

# int
x = 10
print(type(x))

# float
x = 20.5
print(type(x))

# list
x = ["apple", "banana", "orange"]
print(type(x))

# dictionary
x = {"name": "John", "age": 34}
print(type(x))

# set
x = {"apple", "banana", "orange"}
print(type(x))

# bool
x = True
print(type(x))

# bytearray
x = bytearray(5)
print(type(x))

# memoryview
x = memoryview(bytes(5))
print(type(x))

# Setting type
x = str("Hello World")
x = int(20)
x = float(20.5)
x = list(("apple", "banana", "orange"))
x = tuple(("apple", "banana", "orange"))
x = dict(name="Jason", age=41)
x = set(("apple", "banana", "orange"))
x = frozenset(("apple", "banana", "orange"))
x = bool(5)

# Convert
x = 1 # Int
y = 2.3 # Float

# int2float
a = float(x)

# float2int
b = int(y)

# Casting
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")

print(x, type(x), y, type(y), z, type(z), w, type(w))

x = str("s1")
y = str(2)
z = str(3.0)

print(x, type(x), y, type(y), z, type(z))

Learning Python 3 Programming for the Absolute Beginner/Classwork/data-types.py


import requests

def handle_no_ban():
    print('No bans detected')

def handle_ban(body_json):
    ban_count = len(body_json['bans'])
    can_appeal = body_json['canAppeal']
    ban_info = body_json['bans']
    print('Ban count: ' + str(ban_count))
    print('Can appeal: ' + str(can_appeal))
    print('Ban info: ' + str(ban_info))

if __name__ == '__main__':
    SSO_TOKEN = '' # SET SSO TOKEN HERE

    response = requests.get('https://prod-psapi.infra-ext.activision.com/api/bans/appeal', cookies={'ACT_SSO_COOKIE': SSO_TOKEN})

    if response.status_code != 200:
        raise Exception('Non-200 status returned: ' + str(response.status_code))

    body = response.json()
    ban_count = len(body['bans'])
    if (ban_count == 0):
        handle_ban(body)
    else:
        handle_no_ban()


# -*- coding: UTF-8 -*-
import time, os, sys, re
from WebUITestLight.Utils.writeReport import CreateHtmlReport

class UnitTestRultAct(object):
    var = None # unittest 运行后生成的测试结果
    # iTestSuite: [{'errors': 0, 'run': 5, 'title': 'title test case', 'successes': 3, 'start_time': 1465701759.936, 'skipped_str': [(<xmlrunner.result._TestInfo object at 0x00000000027EE4E0>, 'demonstrating skipping')], 'failures_str': [(<xmlrunner.result._TestInfo object at 0x00000000027EE278>, 'Traceback (most recent call last):\n  File "D:\\PythonWorks\\MyPyTestOne\\stu_unitest\\junitreport.py", line 35, in test_failed\n    self.assertEqual(1,2)\nAssertionError: 1 != 2\n')], 'errors_str': [], 'skipped': 1, 'details': 'test case details', 'failures': 1, 'time_consuming': 0.0, 'stop_time': 1465701759.936},
    #              {'errors': 0, 'run': 3, 'title': 'title test case', 'successes': 3, 'start_time': 1465701759.947, 'skipped_str': [], 'failures_str': [], 'errors_str': [], 'skipped': 0, 'details': 'test case details', 'failures': 0, 'time_consuming': 2.0, 'stop_time': 1465701761.947}
    #             ]

    def get_TestCase(self, var,case_num='', title='测试类标题', details='测试内容详情', img=''):
        iTestCase = {}
        # 更新测试结果集，生成各种版本的测试报告
        if case_num == '':
            iTestCase['case_num'] = str(var._previousTestClass)  # 测试类class对象
        else:
            iTestCase['case_num'] = case_num  # 测试类class对象
        iTestCase['environment'] = '-'
        iTestCase['subsystem'] = '-'
        iTestCase['title'] = title
        iTestCase['details'] = details
        iTestCase['run'] = len(var.successes) + len(var.errors) + len(var.failures) + len(var.skipped)
        iTestCase['successes'] = len(var.successes)
        iTestCase['successes_str'] = var.successes
        iTestCase['errors'] = len(var.errors)
        iTestCase['errors_str'] = var.errors
        iTestCase['failures'] = len(var.failures)
        iTestCase['failures_str'] = var.failures
        iTestCase['skipped'] = len(var.skipped)
        iTestCase['skipped_str'] = var.skipped
        iTestCase['img'] = img  # 图片地址 imgname  # imgpath
        iTestCase['start_time'] = var.start_time
        iTestCase['stop_time'] = var.stop_time
        iTestCase['time_consuming'] = var.stop_time - var.start_time
        return iTestCase

    def CreateReport(self,iTestSuite,strcode = 'utf-8'):#, propath='WebUITestLight'
        whtml = CreateHtmlReport()  # 生成测试报告
        # 设置html测试报告输出位置
        whtml.reportfile = sys.path[0] + '/output/HtmlReport.html'
        # 设置html测试报告模板文件位置
        #programpath = sys.path[0][:sys.path[0].find(propath)]
        #print programpath
        #whtml.templatefile = programpath +propath+'/Utils/ReportTemplate.html'
        whtml.templatefile = os.path.dirname(os.path.realpath(__file__))+'/ReportTemplate.html'
        # 设置报告的内容集合
        whtml.iTestSuite = iTestSuite
        # 生成html报告
        whtml.create_html_report()
        # 屏幕打印测试报告
        consoleReport = whtml.print_report()
        print (consoleReport.encode(strcode))
        # 生成文本格式简易测试报告
        whtml.write_txt(sys.path[0] + '/output/TxtReport.txt', consoleReport)

if __name__ == '__main__':
    pass


import docx

file = docx.Document()

# 添加段落
file.add_paragraph('Hello World', 'Title')  # add_paragraph 方法可以用于写入一段文段，第一个参数接受写入的内容，第二段参数接受样式。返回的是 Paragraph 对象

para_obj1 = file.add_paragraph('This is a second paragraph.')
para_obj2 = file.add_paragraph('This is a yet another paragraph.')
para_obj1.add_run("This text is being added to the second paragraph")  # para_obj1 是一个新的自然段，可以在该自然段后通过 add_run 方法，在此自然段后添加句子。 add_run 返回的是 Run 对象

# 添加标题
# add_heading 方法可以添加标题，标题层次为0-4，add_heading 接受两个参数，第一个参数是标题内容，第二个参数是标题层次。返回的是 Paragraph 对象
file.add_heading('Header 0', 0)
file.add_heading('Header 1', 1)
file.add_heading('Header 2', 2)
file.add_heading('Header 3', 3)
file.add_heading('Header 4', 4)

# 添加换页符/换行符
# file.add_break()  # 添加换行符
file.paragraphs[-1].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)  # 插入分页符
file.add_paragraph("This is a new page")

# 插入图片
file.paragraphs[-1].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)
file.add_picture("gaoda.jpg")

file.save('write_doc.docx')


import re
import time

from addressnet.predict import predict
import pandas as pd
from collections import Counter
from dbhepler.mysqlhelper import DBPipeline
from apscheduler.schedulers.blocking import BlockingScheduler

from excel_re import read_excel
import os
import glob

import setting as setting

total_path = glob.glob(os.path.join('*.xls*'))
product_io = '/Users/loctek/Desktop/loctek/address-net/addressnet/乐仓产品数据2.xlsx'
# product_io = 'C:\\addressnet\\乐仓产品数据(1).xlsx'

product_data = pd.read_excel(product_io, dtype=str)

none_product = []

name_list = setting.ssh_name_list
data_country = setting.data_country
word_number = setting.word_number
champion_name = setting.champion_name

def fun_isdigit(aString):
    try:
        return int(aString)
    except ValueError as e:
        return ''

def function(text):
    if 'OT' in text:
        return 'OTTO'
    elif 'AM' in text:
        return 'AMAZON'
    else:
        return 'OTHER'

def get_country(text):
    if pd.isnull(text):
        return ''
    text = str.upper(text)
    if text in data_country.keys():
        return data_country[text]
    else:
        return text

# PR1206-Ebony
def get_delivery(sku, country):  # 物流方式
    try:
        if int(product_data[product_data.SKU == sku]['is_GLS'].values[0]):
            country_list = product_data[product_data.SKU == sku]['国家'].values[0]
            if 'GLOBAL' in country_list:
                return 'GLS_BIZ_PCL'
            if country in country_list:
                return 'GLS_BIZ_PCL'
        product_size = float(product_data[product_data.SKU == sku]['围长'].values[0])  # 对应SKU的围长
        if country == 'DE' and int(product_size) <= 360:
            return 'DHL_DE_PAKET'
        elif ((country == 'DE' or country == 'AT') and product_size > 360) or (
                (country != 'DE' and country != 'AT') and (product_size > 300)):
            return 'DHL_FRIGHT'
        else:
            return 'DHL_DE_INT_PAKET'
    except:
        if sku not in none_product:
            none_product.append(sku)
        return ''

def get_company(consignee_name, old_company, delivery_style):
    if pd.isnull(old_company):
        old_company = ''
    split_names = re.split(r'[,]', consignee_name)

    champion = ''
    for names in split_names:
        get_split_name = names.split(' ')
        for name in reversed(get_split_name):
            if name in champion_name:
                champion = names
    if old_company:
        champion = str(old_company) + champion
    if champion:
        consignee_name = consignee_name.replace(champion, '')
    if 'DHL' in delivery_style and len(champion) > 61:
        return '||||||||||||||||||||||||||||||', consignee_name
    if 'GLS' in delivery_style and len(champion) > 41:
        return '||||||||||||||||||||||||||||||', consignee_name
    return champion, consignee_name

def get_email(text):
    if text:
        return text
    else:
        return '/'

def remake_null(text):
    if not pd.isnull(text):
        return text
    else:
        return ' '

def get_street(doorplate_number, street):
    rule = '(.*)' + doorplate_number + '[,]{0,1}$'
    re_street = re.findall(rule, doorplate_number)
    if re_street:
        return re_street[0]
    return street

def clear_comma(street):
    span_front = re.search(r'(,*$)', street).span()
    street = street[:span_front[0]]
    span_behind = re.search(r'(^,*)', street).span()
    street = street[span_behind[1]:]
    comma_word = re.findall(',,', street)
    if comma_word:
        street = street.replace(comma_word[0], ',')
    street += ','
    return street

def get_ez_street(street, zip_code, consignee_company, city, doorplate):
    street = clear_comma(street)
    print(street)
    ez_street = setting.ez_street
    for word in list(ez_street.keys()):
        capital_words = re.findall(word, street, flags=re.IGNORECASE)
        if capital_words:
            street = street.replace(capital_words[0], ez_street[word])
    zip_code_word = ''
    consignee_company_word = ''
    city_word = ''
    doorplate_word = ''
    # consignee_company += ' '
    print(street, zip_code, consignee_company, city, 123)
    if not pd.isnull(zip_code):
        try:
            zip_code_word = re.findall(zip_code, street, flags=re.IGNORECASE)
            consignee_company_word = re.findall(consignee_company, street, flags=re.IGNORECASE)  # 公司
            city_word = re.findall(city, street, flags=re.IGNORECASE)  # city
            doorplate_word = re.findall(doorplate, street, flags=re.IGNORECASE)  # doorplate
        except:
            print('122211')
    if zip_code_word:
        street = street.replace(zip_code_word[0], '')
    if consignee_company_word:
        # if consignee_company_word[0] != ' ':
        street = street.replace(consignee_company_word[0], '')
    if city_word:
        street = street.replace(city_word[0] + ' ', '')
    if doorplate_word:
        try:
            doorplate_re = doorplate_word[0]
            if '-' in doorplate_word[0]:
                doorplate_re = doorplate_word[0].replace('-', '\-')
            word_split = street.split(',')

            re_sql = doorplate_re + ',(.*)'
            val = re.findall(re_sql, street)
            # if not val:
            # re_s = '[^' + doorplate_re + '](,.*)'
            #  = re.findall(re_sql_2, street)
            mark_mes = val
            mark_mes = mark_mes[0] if mark_mes else ''
        except:
            mark_mes = ''
        consignee_company += mark_mes
        street = street.replace(doorplate_word[0], '')
        street = street.replace(mark_mes, '')
        # print(doorplate_word[0])
        # street = mark_mes
        print(mark_mes)
    consignee_company = consignee_company.replace(doorplate, '')
    street = clear_comma(street)
    consignee_company = clear_comma(consignee_company)
    if consignee_company == ',':
        consignee_company = ''

    if pd.isnull(consignee_company):
        consignee_company = ''
    if len(street) > 35:
        return '||||||||||||||||||||||||||||||', consignee_company
    return street, consignee_company

def get_task():
    db_helper = DBPipeline()  # get DB config
    db_helper.cursor.execute("""select * from view_address_check_bigdate""")  # run sql
    db_data = db_helper.cursor.fetchall()  # get result
    if not db_data:
        return ''
    fields = [field[0] for field in db_helper.cursor.description]  # get dict key in list
    data_list = [dict(zip(fields, item)) for item in db_data]
    df_data = pd.DataFrame(data_list)
    db_df_data = df_data[
        ['name', 'receiveman', 'countryname', 'city', 'street', 'receivezip', 'phone',
         'statezone', 'statezone', 'statezone', 'email', 'company', 'ebname', 'province']]
    db_df_data.columns = setting.ssh_old_columns  # get normal col
    print(db_df_data, 123222)

    db_helper.cursor.close()

    data = db_df_data
    data['Delivery Address Line 1'] = data.apply(lambda x: remake_null(x['Delivery Address Line 1']), axis=1)
    data_dict = dict(data)
    predict_adderss = []
    for i in data_dict['Delivery Address Line 1']:
        predict_adderss.append(i)
    item_list = predict(predict_adderss)  # predict
    tmp_dict = {'flat_number': []}

    b = dict(Counter(data_dict['Order Number']))
    order_tmp_dict = {key: value for key, value in b.items() if value > 1}  # 只展示重复元素
    index = 0
    for order_number in data_dict['Order Number']:
        if order_number in order_tmp_dict.keys():
            order_tmp_dict[order_number] = order_tmp_dict[order_number] - 1
            data_dict['Order Number'][index] = str(data_dict['Order Number'][index]) + str(
                word_number[order_tmp_dict[order_number]])
        tmp_dict['flat_number'].append(
            read_excel(data_dict['Delivery Address Line 1'][index], data_dict['Delivery Country'][index],
                       data_dict['Delivery Postcode'][index]))
        index += 1

    index = 0
    for i in item_list:
        if not tmp_dict['flat_number'][index]:
            if i:
                flat_number = ''
                if 'flat_number' in i.keys():
                    flat_number = i['flat_number']
                    tmp_dict['flat_number'][index] = fun_isdigit(flat_number)
        index += 1
    data_dict.update(tmp_dict)

    data = pd.DataFrame(data_dict)
    data_new = data[
        ['Order Number', 'Delivery Receive Name', 'Delivery Country', 'Delivery Town',
         'Delivery Address Line 1',
         'Delivery Postcode', 'Telephone Number', 'Product Code', 'Quantity', 'flat_number', 'Email Address',
         'Delivery Company', 'ebname', 'province']]
    data_new.columns = setting.ssh_columns
    data_new2 = data_new.reindex(columns=name_list)
    data_new2[['街道2/Street2']] = data_new2[['街道/Street']]
    data_new2[['街道3/Street3']] = data_new2[['收件人公司/Consignee Company']]
    data_new2[['仓库代码/Warehouse Code']] = 'EUKL'
    data_new2[['自动分配仓库']] = 'EUKL'
    data_new2['销售平台/Sales Platform'] = data_new2.apply(lambda x: function(x['参考编号/Reference Code']), axis=1)
    data_new2['收件人国家/Consignee Country'] = data_new2.apply(lambda x: get_country(x['收件人国家/Consignee Country']),
                                                           axis=1)
    data_new2['派送方式/Delivery Style'] = data_new2.apply(
        lambda x: get_delivery(x['SKU1'], x['收件人国家/Consignee Country']), axis=1)
    data_new2['门牌号/Doorplate'] = data_new2.apply(lambda x: get_email(x['门牌号/Doorplate']),
                                                 axis=1)
    try:
        data_new2['收件人公司/Consignee Company'], data_new2['街道/Street'] = zip(*data_new2.apply(
            lambda x: get_company(x['街道/Street'], x['收件人公司/Consignee Company'], x['派送方式/Delivery Style']),
            axis=1))

        # data_new2['街道/Street'] = data_new2.apply(lambda x: get_street(x['门牌号/Doorplate'], x['街道/Street']),
        #                                          axis=1)
        data_new2['街道/Street'], data_new2['收件人公司/Consignee Company'] = zip(*data_new2.apply(
            lambda x: get_ez_street(x['街道/Street'], x['邮编/Zip Code'],
                                    x['收件人公司/Consignee Company'],
                                    x['城市/City'], x['门牌号/Doorplate']
                                    ), axis=1))
    except Exception as error:
        print(error)
    # --- new ---

    # data_new2.to_excel('asdasd.xls', index=False)
    data_clear = data_new2[[
        '参考编号/Reference Code', 'ebname', '街道2/Street2', '城市/City', '邮编/Zip Code', 'province',
        '收件人国家/Consignee Country', '收件人电话/Consignee Phone', '收件人Email/Consignee Email',
        '街道3/Street3', '街道/Street', '门牌号/Doorplate', '收件人公司/Consignee Company'
    ]]
    data_clear.columns = setting.columns_to_dict
    data_clear = data_clear.to_dict(orient='records')
    # data_new2.to_excel('asdasd.xls', index=False)

    for item in data_clear:
        print(item)
        DBPipeline().process_item(item)
    return 'ok'

if __name__ == "__main__":
    get_task()
    scheduler = BlockingScheduler()
    scheduler.add_job(get_task, 'interval', hours=8)
    scheduler.start()


import requests
from async_helper import Async

async def get_homepages():
    quora_future = Async.run_in_executor(None, requests.get, 'http://www.quora.com')
    reddit_future = Async.run_in_executor(None, requests.get, 'http://www.reddit.com')
    quora_response = await quora_future
    reddit_response = await reddit_future
    return quora_response.content, reddit_response.content

def main():
    quora_homepage, reddit_homepage = Async.run_until_complete(get_homepages())
    print("Quora: {}, Reddit {}".format(len(quora_homepage), len(reddit_homepage)))

if __name__ == '__main__':
    main()


import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import adfuller
from arch.unitroot import PhillipsPerron
from statsmodels.regression.linear_model import OLS
import statsmodels.api as sm

acoes = ["PETR4.SA", "TIMS3.SA"]

start = "2023-01-01"
end = "2023-08-31"

df = yf.download(acoes, start=start, end=end)['Adj Close']

df.isna().sum()

# Trate os dados brutos para preencher os valores ausentes com a média
df.fillna(df.mean(), inplace=True)

# Extrai do data frame uma coluna com iloc
acao1 = df.iloc[:,0]
acao1.head()
acao2 = df.iloc[:,1]
acao2.head()

#Test Philip-Perron hipótese nula (H0): A série temporal possui uma raiz unitária e é não estacionária.
pp = PhillipsPerron(acao1)
print(pp.summary().as_text())

# Teste PP para ação 02
pp = PhillipsPerron(acao2)
print(pp.summary().as_text())

# Regressão Linear Simples
acao2 = sm.add_constant(acao2)
model = sm.OLS(acao1, acao2).fit()

# Print a summary of the regression results
print(model.summary())

# Extrair os resíduos do modelo
residuos = model.resid
residuos.plot()
plt.show()

# Teste de raiz unitária dos resíduos (PP)
pp = PhillipsPerron(residuos)
print(pp.summary().as_text())

# A série é cointegrada se apresentar P-valor abaixo de 0.10

# Apresentar séries no data frame em gráfico
df.plot()
plt.show()

# BBDC4 = -04,1373 + 0,7270 * ITUB4 (relação de equilíbrio)
bbdc4 = 14.30
itub4 = 27.21
diferenca = bbdc4 - (-4.1373 + 0.7270 * itub4)
diferenca

np.std(residuos) # desvio médio dos resíduos
max(residuos) # diferença máxima da média dos resíduos em módulo
min(residuos) # diferença mínima da média dos resíduos em módulo

'''
Processo Ornstein–Uhlenbeck
Teste de contagem para saber quantas vezes os pares cruzaram 0.00
Prepapar o loop para os outros ativos do IBOV
'''

# Calcular diferentes pares de ativos para uma série do IBOV
n_assets = 85
x = np.math.factorial(n_assets) / (np.math.factorial(n_assets - 2) * 2)
xyp-jani-qpk


import os
import librosa
import argparse
import numpy as np
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor, as_completed
from scipy.io import wavfile

def resample_wave(wav_in, wav_out, sample_rate):
    wav, _ = librosa.load(wav_in, sr=sample_rate)
    wav = wav / np.abs(wav).max() * 0.6
    wav = wav / max(0.01, np.max(np.abs(wav))) * 32767 * 0.6
    wavfile.write(wav_out, sample_rate, wav.astype(np.int16))

def process_file(file, wavPath, spks, outPath, sr):
    if file.endswith(".wav"):
        file = file[:-4]
        resample_wave(f"{wavPath}/{spks}/{file}.wav", f"{outPath}/{spks}/{file}.wav", sr)

def process_files_with_thread_pool(wavPath, spks, outPath, sr, thread_num=None):
    files = [f for f in os.listdir(f"./{wavPath}/{spks}") if f.endswith(".wav")]

    with ThreadPoolExecutor(max_workers=thread_num) as executor:
        futures = {executor.submit(process_file, file, wavPath, spks, outPath, sr): file for file in files}

        for future in tqdm(as_completed(futures), total=len(futures), desc=f'Processing {sr} {spks}'):
            future.result()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--wav", help="wav", dest="wav", required=True)
    parser.add_argument("-o", "--out", help="out", dest="out", required=True)
    parser.add_argument("-s", "--sr", help="sample rate", dest="sr", type=int, required=True)
    parser.add_argument("-t", "--thread_count", help="thread count to process, set 0 to use all cpu cores", dest="thread_count", type=int, default=1)

    args = parser.parse_args()
    print(args.wav)
    print(args.out)
    print(args.sr)

    os.makedirs(args.out, exist_ok=True)
    wavPath = args.wav
    outPath = args.out

    assert args.sr == 16000 or args.sr == 32000

    for spks in os.listdir(wavPath):
        if os.path.isdir(f"./{wavPath}/{spks}"):
            os.makedirs(f"./{outPath}/{spks}", exist_ok=True)
            if args.thread_count == 0:
                process_num = os.cpu_count() // 2 + 1
            else:
                process_num = args.thread_count
            process_files_with_thread_pool(wavPath, spks, outPath, args.sr, process_num)


import imp
from   io                   import StringIO
from   pluggdapps.plugin    import Plugin, implements
from   tayra                import BaseTTLPlugin

def __traceback_decorator__( frames ):
    from copy    import deepcopy
    from os.path import basename

    def _map2ttl( frame ):
        filename = frame.filename
        lineno = frame.lineno
        lines = open(filename).readlines()[:lineno]
        lines.reverse()
        rc = {}
        for l in lines :
            if l.strip().startswith('# lineno') :
                _, ttl_lineno = l.split(':', 1)
                ttl_lineno = int( ttl_lineno )
                ttl_text = open( _ttlfile ).readlines()[ ttl_lineno-1 ]
                return ttl_lineno, ttl_text
        return None, None

    newframes = []
    for frame in frames :
        newframes.append( frame )
        frameadded = getattr( frame, '_ttlframeadded', False )

        basen = basename( frame.filename )
        if basen.endswith( '.ttl.py' )              and basen == (basename( _ttlfile ) + '.py')              and frameadded == False :
            newframe = deepcopy( frame )
            frame._ttlframeadded = True
            try :
                newframe.lineno, newframe.linetext = _map2ttl( newframe )
                if newframe.lineno :
                    newframe.filename = _ttlfile
                    newframes.append( newframe )
            except :
                raise
                continue
    return newframes

_m.inherit( 'tayra:test/stdttl/base.ttl', globals() )

def body( *args, **kwargs ) :
  _m.pushbuf()
  _m.extend( ["<!-- \nThis file is subject to the terms and conditions defined in\nfile 'LICENSE', which is part of this source code package.\n      Copyright (c) 2011 SKR Farms (P) LTD.\n-->\n\n"] )
  # lineno:9
  _m.extend( [''] )
  _m.append(_m.evalexprs( '', 'parent.body()', '', globals(), locals()) )
  _m.extend( ['\n\n'] )
  return _m.popbuftext()

# ---- Global Functions

# lineno:11
def hd_styles() :
  _m.pushbuf()
  # lineno:12
  _m.extend( [''] )
  _m.append(_m.evalexprs( '', 'parent.hd_styles()', '', globals(), locals()) )
  _m.extend( ['\n  '] )
  # lineno:13
  _m.pushbuf()
  _m.extend( ['<style text/css>'] )
  _m.pushbuf()
  _m.extend( ['\n    '] )
  # lineno:14
  _m.extend( ['div.features {', '\n      '] )
  # lineno:15
  _m.extend( ['margin : 0px 5px;', '\n    '] )
  # lineno:16
  _m.extend( ['}', '\n    '] )
  # lineno:17
  _m.extend( ['div.features p.title {', '\n      '] )
  # lineno:18
  _m.extend( ['font-family : Amaranth, arial;', '\n      '] )
  # lineno:19
  _m.extend( ['font-size : large;', '\n    '] )
  # lineno:20
  _m.extend( ['}', '\n    '] )
  # lineno:21
  _m.extend( ['div.features input[type="text"] {', '\n      '] )
  # lineno:22
  _m.extend( ['margin : 10px 0px 0px 0px;', '\n      '] )
  # lineno:23
  _m.extend( ['background-color : #444;', '\n      '] )
  # lineno:24
  _m.extend( ['border : 1px solid gray;', '\n      '] )
  # lineno:25
  _m.extend( ['width : 40%;', '\n      '] )
  # lineno:26
  _m.extend( ['color : white;', '\n    '] )
  # lineno:27
  _m.extend( ['}', '\n    '] )
  # lineno:28
  _m.extend( ['div.features fieldset {', '\n      '] )
  # lineno:29
  _m.extend( ['padding : 0px 3px 5px 3px;', '\n      '] )
  # lineno:30
  _m.extend( ['margin : 0px 5px;', '\n      '] )
  # lineno:31
  _m.extend( ['width : 45%;', '\n      '] )
  # lineno:32
  _m.extend( ['border : 1px solid gray;', '\n    '] )
  # lineno:33
  _m.extend( ['}', '\n    '] )
  # lineno:34
  _m.extend( ['div.features fieldset legend {', '\n      '] )
  # lineno:35
  _m.extend( ['font-weight : bold;', '\n      '] )
  # lineno:36
  _m.extend( ['font-family : Amaranth, arial;', '\n    '] )
  # lineno:37
  _m.extend( ['}', '\n    '] )
  # lineno:38
  _m.extend( ['div.features fieldset div.keywords {', '\n      '] )
  # lineno:39
  _m.extend( ['text-align : center;', '\n    '] )
  # lineno:40
  _m.extend( ['}', '\n    '] )
  # lineno:41
  _m.extend( ['div.search {', '\n      '] )
  # lineno:42
  _m.extend( ['height : 5em;', '\n    '] )
  # lineno:43
  _m.extend( ['}', '\n    '] )
  # lineno:44
  _m.extend( ['div.features ul {', '\n      '] )
  # lineno:45
  _m.extend( ['list-style : none; ', '\n      '] )
  # lineno:46
  _m.extend( ['padding : 0px;', '\n      '] )
  # lineno:47
  _m.extend( ['margin : 0px;', '\n    '] )
  # lineno:48
  _m.extend( ['}', '\n    '] )
  # lineno:49
  _m.extend( ['div.features ul li {', '\n      '] )
  # lineno:50
  _m.extend( ['border-left : 1px solid crimson;', '\n      '] )
  # lineno:51
  _m.extend( ['margin : 5px 0px;', '\n      '] )
  # lineno:52
  _m.extend( ['background-color : #444;', '\n      '] )
  # lineno:53
  _m.extend( ['padding : 3px;', '\n      '] )
  # lineno:54
  _m.extend( ['padding-left : 5px;', '\n      '] )
  # lineno:55
  _m.extend( ['font-weight : bold;', '\n      '] )
  # lineno:56
  _m.extend( ['border-top : 1px solid #444;', '\n    '] )
  # lineno:57
  _m.extend( ['}', '\n    '] )
  # lineno:58
  _m.extend( ['div.features ul li:hover {', '\n      '] )
  # lineno:59
  _m.extend( ['background-color : #999;', '\n      '] )
  # lineno:60
  _m.extend( ['border-top : 1px solid #DDD;', '\n      '] )
  # lineno:61
  _m.extend( ['color : black;', '\n      '] )
  # lineno:62
  _m.extend( ['text-shadow : 0px 1px 1px #FFF, 0px 1px 1px black;', '\n      '] )
  # lineno:63
  _m.extend( ['-moz-text-shadow : 0px 1px 1px #FFF, 0px 1px 1px black;', '\n      '] )
  # lineno:64
  _m.extend( ['-webkit-text-shadow : 0px 1px 1px #FFF, 0px 1px 1px black;', '\n    '] )
  # lineno:65
  _m.extend( ['}', '\n\n'] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  return _m.popbuftext()

# lineno:67
def hd_script() :
  _m.pushbuf()
  # lineno:68
  _m.extend( [''] )
  _m.append(_m.evalexprs( '', 'parent.hd_script()', '', globals(), locals()) )
  _m.extend( ['\n  '] )
  # lineno:69
  _m.pushbuf()
  _m.extend( ['<script text/javascript>'] )
  _m.pushbuf()
  _m.extend( ['\n    '] )
  # lineno:70
  _m.extend( ['var speed = 200;', '\n    '] )
  # lineno:71
  _m.extend( ['$(document).ready( function() {', '\n      '] )
  # lineno:72
  _m.extend( ['// Search', '\n      '] )
  # lineno:73
  _m.extend( ["$('input.search').keydown( function(e) {", '\n        '] )
  # lineno:74
  _m.extend( ['var patt = new RegExp( $(\'input.search\').val(), "i" );', '\n        '] )
  # lineno:75
  _m.extend( ["$('div.features li').each( function(index, n) {", '\n          '] )
  # lineno:76
  _m.extend( ['patt.test( $(n).text() ) ? $(n).fadeIn(speed) : $(n).fadeOut(speed);', '\n        '] )
  # lineno:77
  _m.extend( ['})', '\n      '] )
  # lineno:78
  _m.extend( ['});', '\n      '] )
  # lineno:79
  _m.extend( ['// Showall', '\n      '] )
  # lineno:80
  _m.extend( ["$('.showall').click( function(e) {", '\n        '] )
  # lineno:81
  _m.extend( ["$('div.features li').each( function(index, n) { $(n).fadeIn(speed); } )", '\n      '] )
  # lineno:82
  _m.extend( ['});', '\n      '] )
  # lineno:83
  _m.extend( ['// Direct search', '\n      '] )
  # lineno:84
  _m.extend( ["$('.dsrch').click( function(e) {", '\n        '] )
  # lineno:85
  _m.extend( ['var patt = new RegExp( $(this).text(), "i" );', '\n        '] )
  # lineno:86
  _m.extend( ['console.log( $(this).text() );', '\n        '] )
  # lineno:87
  _m.extend( ["$('div.features li').each( function(index, n) {", '\n          '] )
  # lineno:88
  _m.extend( ['patt.test( $(n).text() ) ? $(n).fadeIn(speed) : $(n).fadeOut(speed);', '\n        '] )
  # lineno:89
  _m.extend( ['})', '\n      '] )
  # lineno:90
  _m.extend( ['});', '\n    '] )
  # lineno:91
  _m.extend( ['});', '\n\n'] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  return _m.popbuftext()

# lineno:93
def body_centerpane() :
  _m.pushbuf()
  # lineno:94
  _m.extend( [''] )
  _m.append(_m.evalexprs( '', 'parent.body_centerpane()', '', globals(), locals()) )
  _m.extend( ['\n  '] )
  # lineno:95
  _m.pushbuf()
  _m.extend( ['<div .features>'] )
  _m.pushbuf()
  _m.extend( ['\n    '] )
  # lineno:96
  _m.pushbuf()
  _m.extend( ['<p .title>'] )
  _m.pushbuf()
  # lineno:96
  _m.extend( [' Pluggdapps in a nutshell, that it is today and that it will be', '\n      '] )
  # lineno:97
  _m.extend( ['tomorrow.', '\n    '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:98
  _m.pushbuf()
  _m.extend( ['<div .search>'] )
  _m.pushbuf()
  _m.extend( ['\n      '] )
  # lineno:99
  _m.pushbuf()
  _m.extend( ['<inptext .search placeholder="Search features ...">'] )
  _m.pushbuf()
  _m.extend( ['\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:100
  _m.pushbuf()
  _m.extend( ['<a .showall.fntxsmall.pointer>'] )
  _m.pushbuf()
  # lineno:100
  _m.extend( [' show-all', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:101
  _m.pushbuf()
  _m.extend( ['<fieldset .floatr>'] )
  _m.pushbuf()
  _m.extend( ['\n        '] )
  # lineno:102
  _m.pushbuf()
  _m.extend( ['<legend>'] )
  _m.pushbuf()
  # lineno:102
  _m.extend( [' Common search terms', '\n        '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:103
  _m.pushbuf()
  _m.extend( ['<div .keywords>'] )
  _m.pushbuf()
  _m.extend( ['\n          '] )
  # lineno:104
  _m.pushbuf()
  _m.extend( ['<span .dsrch.pointer.ralign>'] )
  _m.pushbuf()
  # lineno:104
  _m.extend( ['plugin', '\n          '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:105
  _m.pushbuf()
  _m.extend( ['<span .dsrch.pointer.ralign>'] )
  _m.pushbuf()
  # lineno:105
  _m.extend( ['template', '\n          '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:106
  _m.pushbuf()
  _m.extend( ['<span .dsrch.pointer.ralign>'] )
  _m.pushbuf()
  # lineno:106
  _m.extend( ['web|html', '\n          '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:107
  _m.pushbuf()
  _m.extend( ['<span .dsrch.pointer.ralign>'] )
  _m.pushbuf()
  # lineno:107
  _m.extend( ['couch', '\n          '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:108
  _m.pushbuf()
  _m.extend( ['<span .dsrch.pointer.ralign>'] )
  _m.pushbuf()
  # lineno:108
  _m.extend( ['tayra', '\n          '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:109
  _m.pushbuf()
  _m.extend( ['<span .dsrch.pointer.ralign>'] )
  _m.pushbuf()
  # lineno:109
  _m.extend( ['program', '\n    '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:110
  _m.pushbuf()
  _m.extend( ['<ul>'] )
  _m.pushbuf()
  _m.extend( ['\n      '] )
  # lineno:111
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:111
  _m.extend( ['Build applications on web-technologies. Build it on pluggdapps.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:112
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:112
  _m.extend( ['Linus took unix to all programmers, and apt-get took Linux to all people.', '\n        '] )
  # lineno:113
  _m.extend( ['In pluggdapps, deploy a website by installing a package.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:114
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:114
  _m.extend( ['Not just websites, whether it is an application or web-application, libraries', '\n        '] )
  # lineno:115
  _m.extend( ['or plugins or just couple of template files, deploy them by installing an egg', '\n        '] )
  # lineno:116
  _m.extend( ['package.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:117
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:117
  _m.extend( ['MVC (Model-View-Controller) is great. Plugin architecture is great. Do them', '\n        '] )
  # lineno:118
  _m.extend( ['both in pluggdapps and get the best of both worlds.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:119
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:119
  _m.extend( ['Should client and server run on different machines ? Not with pluggdapps.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:120
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:120
  _m.extend( ['Pluggdapps run on python and javascript and web-browser and uses erlang for', '\n        '] )
  # lineno:121
  _m.extend( ['database, hence, it can run on any device supporting them. Why not ?', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:122
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:122
  _m.extend( ['Library is a tool. Great libraries are stateless and re-entrant. For', '\n        '] )
  # lineno:123
  _m.extend( ['pluggdapps, even applications are stateless and re-entrant.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:124
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:124
  _m.extend( ['A framework is just a library, with callback APIs. A plugin is just a library,', '\n        '] )
  # lineno:125
  _m.extend( ['with callback APIs. Hence, plugins are great way to design frameworks.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:126
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:126
  _m.extend( ['To access a library, import them. To access plugins, query for them.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:127
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:127
  _m.extend( ['Pluggdapps is not first to do it right, it merely tracks the footsteps of', '\n        '] )
  # lineno:128
  _m.extend( ['its masters - Python, Zope, Pyramid, ...', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:129
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:129
  _m.extend( ['Interface will specify attributes, methods, method-signature and its function.', '\n        '] )
  # lineno:130
  _m.extend( ['A callback API is nothing but an interface, hence, plugins are nothing but', '\n        '] )
  # lineno:131
  _m.extend( ['a bunch of code implementing an interface. That pretty much sums up the', '\n        '] )
  # lineno:132
  _m.extend( ['plugin architecture.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:133
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:133
  _m.extend( ['Install applications and access them on the url.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:134
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:134
  _m.extend( ['Configure and customize application along with modules, interfaces and plugins', '\n        '] )
  # lineno:135
  _m.extend( ['used by the application. Configure them in .ini file, configure them via web.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:136
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:136
  _m.extend( ['Applications are mounted on the url in three ways - domain, subdomain and', '\n        '] )
  # lineno:137
  _m.extend( ['script. While the default is script, choose the one that fits, and', '\n        '] )
  # lineno:138
  _m.extend( ['applications can be agnostic to how they are mounted.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:139
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:139
  _m.extend( ['Url-rewriting. Requests are automatically routed to the mounted', '\n        '] )
  # lineno:140
  _m.extend( ['application.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:141
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:141
  _m.extend( ['Cross application access. For apps to access each other in the same run-time.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:142
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:142
  _m.extend( ['Scaffolding. From first key-stroke to first application page in less than', '\n        '] )
  # lineno:143
  _m.extend( ['30 seconds.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:144
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:144
  _m.extend( ['Authenticate users and authorize them with permissions. Off-the-shelf plugins', '\n        '] )
  # lineno:145
  _m.extend( ['available for challenging credentials and interfacing with backend store.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:146
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:146
  _m.extend( ['Your browser has got the best documentation engine ever and wiki makes it', '\n        '] )
  # lineno:147
  _m.extend( ['accessible. Use EazyText to create content for your apps.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:148
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:148
  _m.extend( ['EazyText wiki markup. Generate HTML documents with out compromising on its', '\n        '] )
  # lineno:149
  _m.extend( ['readability.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:150
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:150
  _m.extend( ['With EazyText highlight your text as bold, italic, underline, subscript,', '\n        '] )
  # lineno:151
  _m.extend( ['superscript and more.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:152
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:152
  _m.extend( ['EazyText can hyperlink documents and images.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:153
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:153
  _m.extend( ['Text in EazyText looks natural for reading. All the same it can generate', '\n        '] )
  # lineno:154
  _m.extend( ['lists, tables, definitions, blockquotes and paragraphs.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:155
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:155
  _m.extend( ['EazyText macros, create new functions and use them in your documents.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:156
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:156
  _m.extend( ['EazyText extensions, extend the wiki engine.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:157
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:157
  _m.extend( ['Become an expert in EazyText and create interactive documents.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:158
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:158
  _m.extend( ['And EazyText is moving towards HTML5.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:159
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:159
  _m.extend( ['With CSS and javascript, your browser can be way more than just a document', '\n        '] )
  # lineno:160
  _m.extend( ['renderer. Use tayra templates to design your front end.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:161
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:161
  _m.extend( ['HTML is verbose. Make it consise with Tayra.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:162
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:162
  _m.extend( ['CSS Selector. That which pulls HTML, Javascript and CSS together.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:163
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:163
  _m.extend( ['Tayra templating language. Bunch of syntax wrapped around a bunch of', '\n        '] )
  # lineno:164
  _m.extend( ['specification. Adapt the language to your needs.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:165
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:165
  _m.extend( ['Intendations are only natural to html. Why not enforce them ?', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:166
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:166
  _m.extend( ['Tayra templates. Define templates as function.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:167
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:167
  _m.extend( ['Tayra templates. Organise template functions as modules. Import them in other', '\n        '] )
  # lineno:168
  _m.extend( ['templates.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:169
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:169
  _m.extend( ['Tayra templates. Templates are modules. Templates are objects. Use template', '\n        '] )
  # lineno:170
  _m.extend( ['inheritance to design layouts.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:171
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:171
  _m.extend( ['Tayra templates. Specify template interface. Implement template plugins. Use', '\n        '] )
  # lineno:172
  _m.extend( ['them else-where.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:173
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:173
  _m.extend( ['If you like decorators in python, you will like it in Tayra templates.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:174
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:174
  _m.extend( ['NoSQL is cool. CouchDB is radical. Program your database with CouchPy.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:175
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:175
  _m.extend( ["Don't you feel stored procedure in SQL as an after-thought ? After programming", '\n        '] )
  # lineno:176
  _m.extend( ['(views,...) in CouchDB, there is a high chance you might.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:177
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:177
  _m.extend( ['CouchDB on HTTP is nothing but CRUD on ReST.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:178
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:178
  _m.extend( ['CouchPy for CouchDB. Model. Transact. Replicate. Program. Query. Eventually', '\n        '] )
  # lineno:179
  _m.extend( ['consistent with MVCC.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:180
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  _m.extend( ['\n        '] )
  # lineno:181
  _m.pushbuf()
  _m.extend( ['<em>'] )
  _m.pushbuf()
  # lineno:181
  _m.extend( ['Programmers believe that the value of their system lies in', '\n          '] )
  # lineno:182
  _m.extend( ['the whole, in the building: posterity discovers it in the bricks with which', '\n          '] )
  # lineno:183
  _m.extend( ['they built and which are often used again for better building.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:184
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  _m.extend( ['\n        '] )
  # lineno:185
  _m.extend( ['Be it internet apps, be it desktop apps, build them on pluggdapps, whether your', '\n        '] )
  # lineno:186
  _m.extend( ['applications live or whither, your plugins will go on to build better apps.', '\n      '] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  # lineno:187
  _m.pushbuf()
  _m.extend( ['<li>'] )
  _m.pushbuf()
  # lineno:187
  _m.extend( ['Start by contributing plugins, grow as you design apps and become a network', '\n        '] )
  # lineno:188
  _m.extend( ['geek.', '\n'] )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  _m.handletag( _m.popbuftext(), _m.popbuftext(), **{'nl': '', 'oprune': False, 'indent': False, 'iprune': False} )
  return _m.popbuftext()

# ---- Interface functions

# ---- Footer


from copy import deepcopy
from functools import partial
from typing import Callable, Union

import hypothesis.extra.numpy as hnp
import hypothesis.strategies as st
import numpy as np
import pytest
from hypothesis import assume, given, infer, note, settings
from numpy.testing import assert_array_equal

import mygrad as mg
from mygrad import Tensor, astensor, mem_guard_off
from mygrad.operation_base import _NoValue
from mygrad.tensor_creation.funcs import (
    arange,
    empty,
    empty_like,
    eye,
    full,
    full_like,
    geomspace,
    identity,
    linspace,
    logspace,
    ones,
    ones_like,
    zeros,
    zeros_like,
)
from mygrad.typing import ArrayLike, DTypeLikeReals, Shape
from tests.custom_strategies import real_dtypes, tensors, valid_constant_arg
from tests.utils.checkers import expected_constant
from tests.utils.functools import SmartSignature

def check_tensor_array(tensor, array, data_compare=True):
    assert isinstance(tensor, Tensor)
    if data_compare:
        assert_array_equal(tensor.data, array)
    assert tensor.dtype is array.dtype

def clamp(val, min_=0.1, max_=None):
    if val is not _NoValue:
        val = max(val, min_)
        if max_ is not None:
            val = min(val, max_)
    return val

@pytest.mark.parametrize("as_kwargs", [True, False])
@pytest.mark.parametrize(
    "mygrad_func, numpy_func",
    [
        (arange, np.arange),
        (linspace, np.linspace),
        (geomspace, np.geomspace),
        (logspace, np.logspace),
    ],
)
@settings(max_examples=200)
@given(
    start=st.just(_NoValue) | st.integers(min_value=-10, max_value=10),
    stop=st.integers(min_value=-10, max_value=10),
    step=st.just(_NoValue) | st.integers(0, 5),
    dtype=infer,
    data=st.data(),
)
def test_arange_like_against_numpy_equivalent(
    start,
    stop,
    step,
    dtype: DTypeLikeReals,
    mygrad_func: Callable,
    numpy_func: Callable,
    data: st.DataObject,
    as_kwargs: bool,
):
    if numpy_func is not np.arange:
        axis = data.draw(st.sampled_from([_NoValue, -1]), label="axis")
    else:
        axis = _NoValue

    if numpy_func is np.geomspace:
        start = clamp(start)
        stop = clamp(stop)
        step = clamp(step)

    if numpy_func is np.logspace:
        start = clamp(start, max_=3)
        stop = clamp(stop, max_=3)
        step = clamp(step)

    if as_kwargs:
        inputs = SmartSignature(
            start=start, stop=stop, step=step, dtype=dtype, axis=axis
        )
    else:
        inputs = SmartSignature(start, stop, step, dtype=dtype, axis=axis)
    try:
        array = numpy_func(*inputs, **inputs)
    except (ZeroDivisionError, TypeError) as e:
        with pytest.raises(type(e)):
            mygrad_func(*inputs, **inputs)
        return

    constant = data.draw(valid_constant_arg(array.dtype), label="constant")
    tensor = mygrad_func(*inputs, **inputs, constant=constant)

    assert_array_equal(tensor, array)
    assert tensor.dtype == array.dtype
    assert tensor.constant is expected_constant(
        dest_dtype=tensor.dtype, constant=constant
    )

@pytest.mark.parametrize(
    "mygrad_func, numpy_func",
    [
        (empty, np.empty),
        (ones, np.ones),
        (zeros, np.zeros),
        (partial(full, fill_value=2), partial(np.full, fill_value=2)),
    ],
)
@settings(max_examples=20)
@given(shape=infer, dtype=infer, data=st.data())
def test_tensor_creation_from_shape_against_numpy_equivalent(
    shape: Shape,
    dtype: DTypeLikeReals,
    data: st.DataObject,
    mygrad_func: Callable,
    numpy_func: Callable,
):
    array = numpy_func(shape, dtype=dtype)

    constant = data.draw(valid_constant_arg(array.dtype), label="constant")
    tensor = mygrad_func(shape, dtype=dtype, constant=constant)
    if numpy_func is not np.empty:
        assert_array_equal(tensor, array)
    assert tensor.dtype == array.dtype
    assert tensor.constant is expected_constant(
        dest_dtype=tensor.dtype, constant=constant
    )

@pytest.mark.parametrize(
    "mygrad_func, numpy_func",
    [
        (partial(full_like, fill_value=-2), partial(np.full_like, fill_value=-2)),
        (zeros_like, np.zeros_like),
        (ones_like, np.ones_like),
        (empty_like, np.empty_like),
    ],
)
@given(arr_like=infer, dtype=infer, data=st.data())
def test_tensor_create_like_against_numpy_equivalent(
    arr_like: ArrayLike,
    dtype: DTypeLikeReals,
    data: st.DataObject,
    mygrad_func: Callable,
    numpy_func: Callable,
):
    _flat_shape = (np.asarray(arr_like).size,)
    shape = data.draw(st.sampled_from([_NoValue, _flat_shape]), label="shape")
    inputs = SmartSignature(arr_like, dtype=dtype, shape=shape)

    array = numpy_func(*inputs, **inputs)

    constant = data.draw(valid_constant_arg(array.dtype), label="constant")
    tensor = mygrad_func(*inputs, **inputs, constant=constant)

    if numpy_func is not np.empty_like:
        assert_array_equal(tensor, array)
    assert tensor.dtype == array.dtype
    assert tensor.constant is expected_constant(
        arr_like, dest_dtype=tensor.dtype, constant=constant
    )

@given(dtype=st.just(_NoValue) | real_dtypes, data=st.data(), n=st.integers(0, 4))
def test_identity(dtype: DTypeLikeReals, data: st.DataObject, n: int):
    inputs = SmartSignature(n, dtype=dtype)
    arr = np.identity(*inputs, **inputs)

    constant = data.draw(valid_constant_arg(arr.dtype), label="constant")
    tensor = identity(*inputs, **inputs, constant=constant)

    assert_array_equal(tensor, arr)
    assert tensor.dtype == arr.dtype
    assert tensor.constant is expected_constant(
        dest_dtype=tensor.dtype, constant=constant
    )

@given(
    dtype=st.just(_NoValue) | real_dtypes,
    data=st.data(),
    n=st.integers(0, 4),
    m=st.integers(0, 4),
)
def test_eye(dtype: DTypeLikeReals, data: st.DataObject, n: int, m: int):
    k = data.draw((st.just(_NoValue) | st.integers(0, min(n, m))), label="constant")
    inputs = SmartSignature(n, m, k, dtype=dtype)
    arr = np.eye(*inputs, **inputs)

    constant = data.draw(valid_constant_arg(arr.dtype), label="constant")
    tensor = eye(*inputs, **inputs, constant=constant)

    assert_array_equal(tensor, arr)
    assert tensor.dtype == arr.dtype
    assert tensor.constant is expected_constant(
        dest_dtype=tensor.dtype, constant=constant
    )

def test_simple_as_tensor():
    arr = np.array(1, dtype=np.int8)
    x = astensor(arr)
    assert x.constant is True
    assert x.data.dtype == np.int8
    assert x.data.item() == 1
    assert x.data is arr

    arr = np.array(1.0, dtype=np.float32)
    x = astensor(arr)
    assert x.constant is False
    assert x.data.dtype == np.float32
    assert x.data.item() == 1.0
    assert x.data is arr

@given(
    t=tensors(dtype=hnp.floating_dtypes(), include_grad=st.booleans()),
    in_graph=st.booleans(),
)
def test_astensor_returns_tensor_reference_consistently(t: Tensor, in_graph: bool):
    if in_graph:
        t = +t
    assert astensor(t) is t
    assert astensor(t, dtype=t.dtype) is t
    assert astensor(t, constant=t.constant) is t
    assert astensor(t, dtype=t.dtype, constant=t.constant) is t

@given(
    t=tensors(dtype=hnp.floating_dtypes(), include_grad=st.booleans()),
    in_graph=st.booleans(),
)
def test_astensor_with_incompat_constant_still_passes_array_ref(
    t: Tensor, in_graph: bool
):
    if in_graph:
        t = +t

    t2 = astensor(t, constant=not t.constant)
    assert t2 is not t
    assert t2.data is t.data
    assert t2.creator is None

    t3 = astensor(t, dtype=t.dtype, constant=not t.constant)
    assert t3 is not t
    assert t3.data is t.data
    assert t3.creator is None

@given(
    t=tensors(
        dtype=hnp.floating_dtypes(),
        include_grad=st.booleans(),
        elements=st.floats(-10, 10, width=16),
    ),
    in_graph=st.booleans(),
    dtype=st.none() | hnp.floating_dtypes(),
    constant=st.none() | st.booleans(),
)
@mem_guard_off
def test_astensor_doesnt_mutate_input_tensor(
    t: Tensor, in_graph: bool, dtype, constant: bool
):
    if in_graph:
        t = +t
    o_constant = t.constant
    o_creator = t.creator
    o_data = t.data.copy()
    o_grad = None if t.grad is None else t.grad.copy()

    astensor(t, dtype=dtype, constant=constant)
    assert t.constant is o_constant
    assert t.creator is o_creator
    assert_array_equal(t, o_data)
    if o_grad is not None:
        assert_array_equal(t.grad, o_grad)
    else:
        assert t.grad is None

@given(
    a=hnp.arrays(
        shape=hnp.array_shapes(min_dims=0, min_side=0),
        dtype=hnp.integer_dtypes() | hnp.floating_dtypes(),
        elements=dict(min_value=0, max_value=0),
    )
    | tensors(
        dtype=hnp.floating_dtypes(),
        include_grad=st.booleans(),
        elements=dict(min_value=0, max_value=0),
    ),
    as_list=st.booleans(),
    dtype=st.none() | hnp.integer_dtypes() | hnp.floating_dtypes(),
    data=st.data(),
)
def test_as_tensor(
    a: Union[np.ndarray, Tensor], as_list: bool, dtype, data: st.DataObject
):
    """Ensures `astensor` produces a tensor with the expected data, dtype, and constant,
    and that it doesn't mutate the input."""
    assume(~np.any(np.isnan(a)))

    constant = data.draw(
        valid_constant_arg(np.array(a, dtype=dtype).dtype), label="constant"
    )

    # make copies to check mutations
    if as_list:
        a = np.asarray(a).tolist()
        original = deepcopy(a)
    else:
        original = a.copy()

    t = astensor(a, dtype=dtype, constant=constant)

    ref_tensor = a if t is a else Tensor(a, dtype=dtype, constant=constant)

    assert isinstance(t, Tensor)
    assert t.dtype == ref_tensor.dtype
    assert t.constant is ref_tensor.constant
    assert_array_equal(ref_tensor.data, t.data)

    if as_list:
        assert a == original, "the original array was mutated"
    else:
        assert_array_equal(original, a, err_msg="the original array was mutated")

general_arrays = hnp.arrays(
    shape=hnp.array_shapes(min_side=0, min_dims=0),
    dtype=hnp.floating_dtypes() | hnp.integer_dtypes(),
    elements=st.integers(-2, 2),
)

class NotSet:
    pass

not_set = st.just(NotSet)

@settings(max_examples=1000)
@given(
    arr_like=general_arrays.map(lambda x: x.tolist()) | general_arrays,
    dtype=not_set | st.none() | hnp.floating_dtypes() | hnp.integer_dtypes(),
    copy=not_set | st.booleans(),
    # can't generically test with `constant=False` because of int-dtypes
    constant=st.none() | st.just(True),
    ndmin=not_set | st.integers(-6, 6),
)
def test_tensor_mirrors_array(arr_like, dtype, copy, constant, ndmin):
    if isinstance(arr_like, np.ndarray):
        note(f"arr_like.dtype: {arr_like.dtype}")

    kwargs = {}
    for name, var_ in [("dtype", dtype), ("copy", copy), ("ndmin", ndmin)]:
        if var_ is not NotSet:
            kwargs[name] = var_

    try:
        arr = np.array(arr_like, **kwargs)
    except (ValueError, OverflowError):
        assume(False)
        return

    tensor_like = (
        Tensor(arr_like.copy(), constant=constant)
        if isinstance(arr_like, np.ndarray)
        else arr_like
    )

    tens = mg.tensor(tensor_like, constant=constant, **kwargs)

    assert tens.dtype == arr.dtype
    assert tens.shape == arr.shape
    assert np.shares_memory(tens, tensor_like) is np.shares_memory(arr, arr_like)

    if arr.dtype.byteorder != ">":
        # condition due to https://github.com/numpy/numpy/issues/22897

        assert (tens is tensor_like) is (arr is arr_like)
        assert (tens.base is tensor_like) is (arr.base is arr_like)
        if tens.base is None:
            # sometimes numpy makes internal views; mygrad should never do this
            assert arr.base is not arr_like

@given(
    t=tensors(dtype=hnp.floating_dtypes() | hnp.integer_dtypes()),
    dtype=st.none() | hnp.floating_dtypes() | hnp.integer_dtypes(),
    copy=st.booleans(),
    # can't generically test with `constant=False` because of int-dtypes
    constant=st.none() | st.just(True),
    ndmin=st.none() | st.floats(),
)
def test_bad_ndmin_raises(t, dtype, copy, constant, ndmin):
    with pytest.raises(TypeError):
        mg.tensor(t, dtype=dtype, copy=copy, ndmin=ndmin, constant=constant)

@given(
    shapes=hnp.mutually_broadcastable_shapes(
        num_shapes=1, base_shape=(4, 3, 2), max_dims=3, max_side=4
    ),
    fill_is_tensor=st.booleans(),
    data=st.data(),
)
def test_full_can_broadcast_fill_value(
    shapes: hnp.BroadcastableShapes, fill_is_tensor: bool, data: st.DataObject
):
    fill_value = data.draw(hnp.arrays(shape=shapes.input_shapes[0], dtype=float))
    expected = np.full(shape=shapes.result_shape, fill_value=fill_value)

    if fill_is_tensor:
        fill_value = Tensor(fill_value)

    actual = full(shape=shapes.result_shape, fill_value=fill_value)

    assert_array_equal(actual, expected)