# -*- coding: utf-8 -*-
import math
from pathlib import Path
from time import perf_counter

import numpy as np
import pandas as pd

from functools import reduce
from operator import mul
from sys import float_info as sflt

TRADING_DAYS_PER_YEAR = 251
TRADING_HOURS_PER_DAY = 6.5
MINUTES_PER_HOUR = 60

def _above_below(
        series_a: pd.Series,
        series_b: pd.Series,
        above: bool = True,
        asint: bool = True,
        offset: int = None,
        **kwargs
    ):
    series_a = verify_series(series_a)
    series_b = verify_series(series_b)
    offset = get_offset(offset)

    series_a.apply(zero)
    series_b.apply(zero)

    # Calculate Result
    if above:
        current = series_a >= series_b
    else:
        current = series_a <= series_b

    if asint:
        current = current.astype(int)

    # Offset
    if offset != 0:
        current = current.shift(offset)

    # Name & Category
    current.name = f"{series_a.name}_{'A' if above else 'B'}_{series_b.name}"
    current.category = "utility"

    return current

def above(
        series_a: pd.Series,
        series_b: pd.Series,
        asint: bool = True,
        offset: int = None,
        **kwargs
    ):
    return _above_below(series_a, series_b, above=True, asint=asint, offset=offset, **kwargs)

def above_value(
        series_a: pd.Series,
        value: float,
        asint: bool = True,
        offset: int = None,
        **kwargs
    ):
    if not isinstance(value, (int, float, complex)):
        print("[X] value is not a number")
        return
    series_b = pd.Series(value, index=series_a.index, name=f"{value}".replace(".","_"))
    return _above_below(series_a, series_b, above=True, asint=asint, offset=offset, **kwargs)

def below(
        series_a: pd.Series,
        series_b: pd.Series,
        asint: bool =True,
        offset: int =None
        ,**kwargs
    ):
    return _above_below(series_a, series_b, above=False, asint=asint, offset=offset, **kwargs)

def below_value(
        series_a: pd.Series,
        value: float,
        asint: bool = True,
        offset: int = None,
        **kwargs
    ):
    if not isinstance(value, (int, float, complex)):
        print("[X] value is not a number")
        return
    series_b = pd.Series(value, index=series_a.index, name=f"{value}".replace(".","_"))
    return _above_below(series_a, series_b, above=False, asint=asint, offset=offset, **kwargs)

def category_files(category: str) -> list:
    """Helper function to return all filenames in the category directory."""
    files = [x.stem for x in list(Path(f"pandas_ta/{category}/").glob("*.py")) if x.stem != "__init__"]
    return files

def combination(**kwargs):
    """https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python"""
    n = int(math.fabs(kwargs.pop("n", 1)))
    r = int(math.fabs(kwargs.pop("r", 0)))

    if kwargs.pop("repetition", False) or kwargs.pop("multichoose", False):
        n = n + r - 1

    # if r < 0: return None
    r = min(n, n - r)
    if r == 0:
        return 1

    numerator   = reduce(mul, range(n, n - r, -1), 1)
    denominator = reduce(mul, range(1, r + 1), 1)
    return numerator // denominator

def cross_value(
        series_a: pd.Series,
        value: float,
        above: bool = True,
        asint: bool = True,
        offset: int = None,
        **kwargs
    ):
    series_b = pd.Series(value, index=series_a.index, name=f"{value}".replace(".","_"))
    return cross(series_a, series_b, above, asint, offset, **kwargs)

def cross(
        series_a: pd.Series,
        series_b: pd.Series,
        above: bool = True,
        asint: bool = True,
        offset: int = None,
        **kwargs
    ):
    series_a = verify_series(series_a)
    series_b = verify_series(series_b)
    offset = get_offset(offset)

    series_a.apply(zero)
    series_b.apply(zero)

    # Calculate Result
    current = series_a > series_b   # current is above
    previous = series_a.shift(1) < series_b.shift(1) # previous is below
    # above if both are true, below if both are false
    cross = current & previous if above else ~current & ~previous

    if asint:
        cross = cross.astype(int)

    # Offset
    if offset != 0:
        cross = cross.shift(offset)

    # Name & Category
    cross.name = f"{series_a.name}_{'XA' if above else 'XB'}_{series_b.name}"
    cross.category = "utility"

    return cross

def is_datetime_ordered(df: pd.DataFrame or pd.Series) -> bool:
    """Returns True if the index is a datetime and ordered."""
    index_is_datetime = pd.api.types.is_datetime64_any_dtype(df.index)
    try:
        ordered = df.index[0] < df.index[-1]
    except RuntimeWarning: pass
    finally:
        return True if index_is_datetime and ordered else False

def signals(indicator, xa, xb, cross_values, xserie, xserie_a, xserie_b, cross_series, offset) -> pd.DataFrame:
    df = pd.DataFrame()
    if xa is not None and isinstance(xa, (int, float)):
        if cross_values:
            crossed_above_start = cross_value(indicator, xa, above=True, offset=offset)
            crossed_above_end = cross_value(indicator, xa, above=False, offset=offset)
            df[crossed_above_start.name] = crossed_above_start
            df[crossed_above_end.name] = crossed_above_end
        else:
            crossed_above = above_value(indicator, xa, offset=offset)
            df[crossed_above.name] = crossed_above

    if xb is not None and isinstance(xb, (int, float)):
        if cross_values:
            crossed_below_start = cross_value(indicator, xb, above=True, offset=offset)
            crossed_below_end = cross_value(indicator, xb, above=False, offset=offset)
            df[crossed_below_start.name] = crossed_below_start
            df[crossed_below_end.name] = crossed_below_end
        else:
            crossed_below = below_value(indicator, xb, offset=offset)
            df[crossed_below.name] = crossed_below

    # xseries is the default value for both xserie_a and xserie_b
    if xserie_a is None:
        xserie_a = xserie
    if xserie_b is None:
        xserie_b = xserie

    if xserie_a is not None and verify_series(xserie_a):
        if cross_series:
            cross_serie_above = cross(indicator, xserie_a, above=True, offset=offset)
        else:
            cross_serie_above = above(indicator, xserie_a, offset=offset)

        df[cross_serie_above.name] = cross_serie_above

    if xserie_b is not None and verify_series(xserie_b):
        if cross_series:
            cross_serie_below = cross(indicator, xserie_b, above=False, offset=offset)
        else:
            cross_serie_below = below(indicator, xserie_b, offset=offset)

        df[cross_serie_below.name] = cross_serie_below

    return df

def df_error_analysis(dfA: pd.DataFrame, dfB: pd.DataFrame, **kwargs) -> pd.DataFrame:
    """ """
    col = kwargs.pop("col", None)
    corr_method = kwargs.pop("corr_method", "pearson")

    # Find their differences and correlation
    diff = dfA - dfB
    corr = dfA.corr(dfB, method=corr_method)

    # For plotting
    if kwargs.pop("plot", False):
        diff.hist()
        if diff[diff > 0].any():
            diff.plot(kind="kde")

    return corr

def fibonacci(**kwargs) -> np.ndarray:
    """Fibonacci Sequence as a numpy array"""
    n = int(math.fabs(kwargs.pop("n", 2)))
    zero = kwargs.pop("zero", False)
    weighted = kwargs.pop("weighted", False)

    if zero:
        a, b = 0, 1
    else:
        n -= 1
        a, b = 1, 1

    result = np.array([a])
    for i in range(0, n):
        a, b = b, a + b
        result = np.append(result, a)

    if weighted:
        fib_sum = np.sum(result)
        if fib_sum > 0:
            return result / fib_sum
        else:
            return result
    else:
        return result

def final_time(stime):
    time_diff = perf_counter() - stime
    return f"{time_diff * 1000:2.4f} ms ({time_diff:2.4f} s)"

def get_drift(x: int) -> int:
    """Returns an int if not zero, otherwise defaults to one."""
    return int(x) if x and x != 0 else 1

def get_offset(x: int) -> int:
    """Returns an int, otherwise defaults to zero."""
    return int(x) if x else 0

def is_percent(x: int or float) -> bool:
    if isinstance(x, (int, float)):
        return x is not None and x >= 0 and x <= 100
    return False

def non_zero_range(high: pd.Series, low: pd.Series) -> pd.Series:
    """Returns the difference of two series and adds epsilon if
    to any zero values.  This occurs commonly in crypto data when
    high = low.
    """
    diff = high - low
    if diff.eq(0).any().any():
        diff += sflt.epsilon
    return diff

def pascals_triangle(n: int = None, **kwargs) -> np.ndarray:
    """Pascal's Triangle

    Returns a numpy array of the nth row of Pascal's Triangle.
    n=4  => triangle: [1, 4, 6, 4, 1]
         => weighted: [0.0625, 0.25, 0.375, 0.25, 0.0625]
         => inverse weighted: [0.9375, 0.75, 0.625, 0.75, 0.9375]
    """
    n = int(math.fabs(n)) if n is not None else 0
    weighted = kwargs.pop("weighted", False)
    inverse = kwargs.pop("inverse", False)

    # Calculation
    triangle = np.array([combination(n=n, r=i) for i in range(0, n + 1)])
    triangle_sum = np.sum(triangle)
    triangle_weights = triangle / triangle_sum
    inverse_weights = 1 - triangle_weights

    if weighted and inverse:
        return inverse_weights
    if weighted:
        return triangle_weights
    if inverse:
        return None

    return triangle

def recent_maximum_index(x):
    return int(np.argmax(x[::-1]))

def recent_minimum_index(x):
    return int(np.argmin(x[::-1]))

def signed_series(series: pd.Series, initial: int =None) -> pd.Series:
    """Returns a Signed Series with or without an initial value

    Default Example:
    series = pd.Series([3, 2, 2, 1, 1, 5, 6, 6, 7, 5])
    and returns:
    sign = pd.Series([NaN, -1.0, 0.0, -1.0, 0.0, 1.0, 1.0, 0.0, 1.0, -1.0])
    """
    series = verify_series(series)
    sign = series.diff(1)
    sign[sign > 0] = 1
    sign[sign < 0] = -1
    sign.iloc[0] = initial
    return sign

def symmetric_triangle(n: int = None, **kwargs) -> list:
    """Symmetric Triangle with n >= 2

    Returns a numpy array of the nth row of Symmetric Triangle.
    n=4  => triangle: [1, 2, 2, 1]
         => weighted: [0.16666667 0.33333333 0.33333333 0.16666667]
    """
    n = int(math.fabs(n)) if n is not None else 2
    weighted = kwargs.pop("weighted", False)

    if n == 2:
        triangle = [1, 1]

    if n > 2:
        if n % 2 == 0:
            front = [i + 1 for i in range(0, math.floor(n/2))]
            triangle = front + front[::-1]
        else:
            front = [i + 1 for i in range(0, math.floor(0.5 * (n + 1)))]
            triangle = front.copy()
            front.pop()
            triangle += front[::-1]

    if weighted:
        triangle_sum = np.sum(triangle)
        triangle_weights = triangle / triangle_sum
        return triangle_weights

    return triangle

def unsigned_differences(series: pd.Series, amount: int = None, **kwargs) -> pd.Series:
    """Unsigned Differences
    Returns two Series, an unsigned positive and unsigned negative series based
    on the differences of the original series. The positive series are only the
    increases and the negative series is only the decreases.

    Default Example:
    series   = pd.Series([3, 2, 2, 1, 1, 5, 6, 6, 7, 5, 3]) and returns
    postive  = pd.Series([0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0])
    negative = pd.Series([0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1])
    """
    amount = int(amount) if amount is not None else 1
    negative = series.diff(amount)
    negative.fillna(0, inplace=True)
    positive = negative.copy()

    positive[positive <= 0] = 0
    positive[positive > 0] = 1

    negative[negative >= 0] = 0
    negative[negative < 0] = 1

    if kwargs.pop("asint", False):
        positive = positive.astype(int)
        negative = negative.astype(int)

    return positive, negative

def verify_series(series: pd.Series) -> pd.Series:
    """If a Pandas Series return it."""
    if series is not None and isinstance(series, pd.core.series.Series):
        return series

def weights(w):
    def _dot(x):
        return np.dot(w, x)
    return _dot

def zero(x: [int, float]) -> [int, float]:
    """If the value is close to zero, then return zero.
    Otherwise return the value."""
    return 0 if abs(x) < sflt.epsilon else x

# Candle Functions

def candle_color(open_, close):
    color = close.copy().astype(int)
    color[close >= open_] = 1
    color[close < open_] = -1
    return color

def real_body(close, open_):
    return non_zero_range(close, open_)

def high_low_range(high, low):
    return non_zero_range(high, low)


#!/usr/local/bin/python3
initial =  float(input("初期投資額: ").strip())
monthly =  float(input("積立額/月: ").strip())
bonus =    float(input("ボーナス額/回: ").strip())
years =    float(input("運用年数: ").strip())
interest = float(input("想定利回り/年: ").strip())

sumOfInvest = initial
total = initial

interestOfMonth = interest/12/100

for m in range(int(12*years)):
    total *= (1 + interestOfMonth)
    total += monthly
    sumOfInvest += monthly
    if m%6 == 0:
        total += bonus
        sumOfInvest += bonus

print("試算結果: " + "{:,}".format(int(total)))
print("投資総額: " + "{:,}".format(int(sumOfInvest)))


from builtins import bytes

import hmac
import hashlib

def CreateHmac( content, hmac_secret ):
  if not isinstance( content, bytes ):
    raise TypeError( 'content was not of bytes type; you have a bug!' )
  if not isinstance( hmac_secret, bytes ):
    raise TypeError( 'hmac_secret was not of bytes type; you have a bug!' )

  return bytes( hmac.new( hmac_secret,
                          msg = content,
                          digestmod = hashlib.sha256 ).digest() )

def CreateRequestHmac( method, path, body, hmac_secret ):
  if not isinstance( body, bytes ):
    raise TypeError( 'body was not of bytes type; you have a bug!' )
  if not isinstance( hmac_secret, bytes ):
    raise TypeError( 'hmac_secret was not of bytes type; you have a bug!' )
  if not isinstance( method, bytes ):
    raise TypeError( 'method was not of bytes type; you have a bug!' )
  if not isinstance( path, bytes ):
    raise TypeError( 'path was not of bytes type; you have a bug!' )

  method_hmac = CreateHmac( method, hmac_secret )
  path_hmac = CreateHmac( path, hmac_secret )
  body_hmac = CreateHmac( body, hmac_secret )

  joined_hmac_input = bytes().join( ( method_hmac, path_hmac, body_hmac ) )
  return CreateHmac( joined_hmac_input, hmac_secret )


import matplotlib.pyplot as plt
from wordcloud import WordCloud
from wordcloud import STOPWORDS

def ser_to_wordcloud(ser, random_state=None):
    text = " ".join(i for i in ser)
    stopwords = set(STOPWORDS)
    wordcloud = WordCloud(
        width=600,
        height=400,
        random_state=random_state,
        stopwords=stopwords,
        background_color="white",
    ).generate(text)
    return wordcloud

def wordcloud_to_fig(wordcloud, title=None):
    fig, ax = plt.subplots(figsize=(16, 9))
    ax.imshow(wordcloud)

    ax.axis("off")
    if title:
        fig.suptitle(title, fontsize=40, fontweight="bold")
    return fig, ax

def ser_to_fig_wordcloud(ser, title=None, *args, **kwargs):
    wordcloud = ser_to_wordcloud(ser, *args, **kwargs)
    return wordcloud_to_fig(wordcloud, title=title)


import nmap

class Network(object):
    def __init__(self):
        ip = input('Please enter IP: ')
        self.ip = ip

    def NetScanner(self):
        if len(self.ip) == 0:
            print('Please enter a valid IP')
        else:
            network = self.ip + '/24'

        print('Scanning please wait...')

        nam = nmap.PortScanner()
        nam.scan(hosts = network, arguments = '-sn')
        host_list = [(x, nam[x]['status']['status']) for x in nam.all_hosts()]
        for host, ststus in host_list:
            print(f'Host {host_list}')

if __name__ == '__main__':
    D = Network()
    D.NetScanner()


import os
import sys
sys.path.append('../')
import open3d as o3d
import trimesh
import argparse
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from utils.utils import check_exist_or_mkdirs, trimesh_remove_texture
from tqdm import tqdm
import logging

class DisableLogger():
    def __enter__(self):
       logging.disable(logging.CRITICAL)
    def __exit__(self, a, b, c):
       logging.disable(logging.NOTSET)

def create_ptcloud_folder(dataset_path, model_path, points_dirname, num_points, instance_num = 52430):

    f_class = open(os.path.join(dataset_path, "splits/classes.txt"),"r")
    points_path = os.path.join(dataset_path, points_dirname)
    check_exist_or_mkdirs(points_path)
    class_num = 0
    counter = 0
    fname = 'ptcloud'
    pbar = tqdm(total = instance_num)
    for cl in f_class:
        index = cl.find(' ')
        class_num += 1
        clname = cl[:index]
        clid = cl[index+1:-1]
        check_exist_or_mkdirs(os.path.join(points_path, clname))
        for split in ['train','val','test']:
            f = open(os.path.join(dataset_path, "splits/lists/%s/%s.txt"%(clname,split)),"r")
            for x in f:
                instance_id = x[:-1]
                check_exist_or_mkdirs(os.path.join(points_path, clname, instance_id))
                ptcloud_path = os.path.join(points_path, clname, instance_id, '%s.ply' % fname)
                mesh_path = os.path.join(args.model_path, clid, instance_id, "models", "model_normalized.obj")
                with DisableLogger():
                    mesh_or_scene = trimesh.load_mesh(mesh_path)
                obj_mesh = trimesh_remove_texture(mesh_or_scene)
                obj_mesh = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(obj_mesh.vertices),
                                                    o3d.utility.Vector3iVector(obj_mesh.faces))
                ptcloud = obj_mesh.sample_points_uniformly(number_of_points = num_points)
                o3d.io.write_point_cloud(ptcloud_path, ptcloud)
                counter += 1
                pbar.update(n=1)
    pbar.close()
    print('Total Instance Number: %d, Total Class Number: %d' % (counter, class_num))

def visualize_points():
    for i in range(10):
        plydata = o3d.io.read_point_cloud("../results/%d.ply"% i)
        o3d.visualization.draw_geometries([plydata])

def main(args):
    #visualize_points()
    create_ptcloud_folder(args.dataset_path, args.model_path, args.points_dirname, args.num_points)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='object-centered mode')
    parser.add_argument("--dataset-path",type=str,default="/home/../../public/zyf/What3D/",
                        help='path to dataset')
    parser.add_argument("--points-dirname",type=str,default="points_1024_obj",
                        help='path to save sampled pointcloud')
    parser.add_argument("--model-path",type=str,default="/home/../../public/zyf/ShapeNetCore.v2",
                        help='path of load mesh model')
    parser.add_argument("--num-points",type=int,default=1024,
                        help='number of points to sample')
    args = parser.parse_args()
    print(str(args))
    sys.stdout.flush()
    main(args)


from django import forms

from sweetshop.main.models import SubscribedUser

class NewsSubscriptCreateForm(forms.ModelForm):
    class Meta:
        model = SubscribedUser
        fields = "__all__"
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Fill your name'}),
            'email': forms.EmailInput(attrs={'placeholder': 'Fill your email'}),
        }

class SearchForm(forms.Form):
    search_name = forms.CharField(
        max_length=30,
    )


import os.path
import platform

from PySide6.QtGui import QAction, QIcon
from PySide6.QtWidgets import *
from PySide6.QtCore import Qt

import glob, subprocess

def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['b', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

class CreateWindow(QDialog):
    def __init__(self, parent=None):
        super().__init__()

        self.parent = parent
        self.setWindowTitle("Create image")

        l1 = QLabel("Size:")
        self.size = QLineEdit("10")
        self.size.setFixedWidth(60)
        l2 = QLabel("MB")
        create = QPushButton("Save")
        create.clicked.connect(self.create_image)

        layout = QHBoxLayout()
        layout.addWidget(l1)
        layout.addWidget(self.size)
        layout.addWidget(l2)
        layout.addWidget(create)

        vlay = QVBoxLayout()
        self.progress = QProgressBar()
        self.progress.setTextVisible(False)
        vlay.addLayout(layout)
        vlay.addWidget(self.progress)

        self.setLayout(vlay)

    def create_image(self):
        filename = QFileDialog.getSaveFileName(self, "Save image", "", "Image files (*.img *.hda)")[0]

        if not filename:
            # self.close()
            return

        size = int(self.size.text())
        data = bytes([0] * 1024 * 1024)
        # f.seek(size*1024*1024)
        # f.write(b'0')
        self.progress.setMaximum(size - 1)

        with open(filename, "w+b") as f:
            for i in range(size):
                f.write(data)
                self.progress.setValue(i)

        self.parent.open_path([filename])
        self.close()

class Main(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("MacImageMount")

        if platform.system() == "Darwin":
            about_action = QAction(QIcon(), "About", self)
            about_action.triggered.connect(lambda: QMessageBox.information(self, "About", "Made by: SinTech\nVer: 1.0"))
            menubar = self.menuBar()
            menu = menubar.addMenu("Help")
            menu.addAction(about_action)

        self.create = QPushButton("Create")
        self.create.clicked.connect(self.create_image)
        self.image_list = [{}]
        self.dir = "Path"
        self.path = QLineEdit(self.dir)
        self.open = QPushButton("Open dir", )
        self.open.clicked.connect(self.open_path)

        addr_lay = QHBoxLayout()
        addr_lay.addWidget(self.create)
        addr_lay.addWidget(self.path)
        addr_lay.addWidget(self.open)

        self.table = QTableWidget()
        self.table.setRowCount(0)
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(["Image", "Size", ""])
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)

        self.layout = QVBoxLayout()
        self.layout.addLayout(addr_lay)
        self.layout.addWidget(self.table)

        container = QWidget()
        container.setLayout(self.layout)
        self.setCentralWidget(container)

    def create_image(self):
        self.create_window = CreateWindow(self)
        self.create_window.setModal(True)
        self.create_window.show()

    def mount_image(self):
        button = self.sender()
        index = self.table.indexAt(button.pos())
        if not index.isValid():
            return
        table_row = index.row()

        if button.text() == "mount":
            proc = subprocess.run(["hdiutil", "attach", "-noverify", "-imagekey", "diskimage-class=CRawDiskImage",
                                   self.image_list[table_row]["image"]], capture_output=True, timeout=10,
                                  universal_newlines=True)
            if proc.returncode > 0:
                msgBox = QMessageBox()
                msgBox.setText("Image mounting error")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setDetailedText(" ".join(proc.args) + "\n\n" + proc.stderr)
                hs = QSpacerItem(500, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
                layout = msgBox.layout()  # .setSizeConstraint(QLayout.SetMinimumSize)
                layout.addItem(hs, layout.rowCount(), 0, 1, layout.columnCount())
                msgBox.exec()
            else:
                print(proc.stdout)
                disk = proc.stdout.split("\n")[0].split(" ")[0]
                if "disk" not in disk:
                    QMessageBox.warning(self, "Warning", "Something went wrong")
                    return

                self.image_list[table_row]["mounted"] = disk
                self.table.item(table_row, 0).setText(
                    self.image_list[table_row]["image"].replace(self.dir + os.sep, "") + " (" + disk + ")"
                )
                self.table.item(table_row, 0).setBackground(Qt.green)
                self.table.cellWidget(table_row, 2).setText("unmount")

        elif button.text() == "unmount":
            if not self.image_list[table_row]["mounted"]:
                QMessageBox.warning(self, "Warning", "Something went wrong (mount point is empty)")
                return

            proc = subprocess.run(["hdiutil", "detach", self.image_list[table_row]["mounted"]], capture_output=True,
                                  timeout=10,
                                  universal_newlines=True)
            if proc.returncode > 0:
                msgBox = QMessageBox()
                msgBox.setText("Image un-mounting error")
                msgBox.setIcon(QMessageBox.Critical)
                msgBox.setDetailedText(" ".join(proc.args) + "\n\n" + proc.stderr)
                hs = QSpacerItem(400, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)
                layout = msgBox.layout()  # .setSizeConstraint(QLayout.SetMinimumSize)
                layout.addItem(hs, layout.rowCount(), 0, 1, layout.columnCount())
                msgBox.exec()
            else:
                self.image_list[table_row]["mounted"] = None
                self.table.item(table_row, 0).setText(
                    self.image_list[table_row]["image"].replace(self.dir + os.sep, "")
                )
                self.table.item(table_row, 0).setBackground(Qt.white)
                self.table.cellWidget(table_row, 2).setText("mount")

    def open_path(self, ext_list=[]):

        if ext_list:
            self.dir = os.path.dirname(ext_list[0])
            file_list = ext_list
        else:
            self.dir = QFileDialog.getExistingDirectory(self, "Open Directory",
                                                        "",
                                                        QFileDialog.ShowDirsOnly)

            if not self.dir:
                return

            file_list = []
            file_list.extend(glob.glob(self.dir + os.path.sep + '**/*.img', recursive=True))
            file_list.extend(glob.glob(self.dir + os.path.sep + '**/*.hda', recursive=True))
            file_list.extend(glob.glob(self.dir + os.path.sep + '**/*.iso', recursive=True))

        self.path.setText(self.dir)
        self.image_list = []
        # self.table.clear()
        self.table.setRowCount(0)

        for file in sorted(file_list):
            self.image_list.append({"image": file, "mounted": None})

        for i, img_info in enumerate(self.image_list):
            file = img_info["image"]
            item_name = QTableWidgetItem(file.replace(self.dir + "/", ""))
            item_size = QTableWidgetItem(convert_bytes(os.path.getsize(file)))
            item_button = QPushButton("mount")
            item_button.clicked.connect(self.mount_image)
            self.table.insertRow(i)
            self.table.setItem(i, 0, item_name)
            self.table.setItem(i, 1, item_size)
            self.table.setCellWidget(i, 2, item_button)

if __name__ == "__main__":
    app = QApplication()

    widget = Main()
    widget.resize(800, 600)
    widget.show()

    app.exec()


from tkinter import *
from random import *
import sys
def win_check():
    for i in range(5):
        for j in range(5):
            if list(but_array[i][j].config()["background"])[-1]=="white":
                return False
    return True
def but_func(x,y):
    if list(but_array[x][y].config()["background"])[-1]=="black":
        but_array[x][y].config(bg="white")
    else:
        but_array[x][y].config(bg="black")
    if x+1<5:
        if list(but_array[x+1][y].config()["background"])[-1]=="black":
            but_array[x+1][y].config(bg="white")
        else:
            but_array[x+1][y].config(bg="black")
    if y+1<5:
        if list(but_array[x][y+1].config()["background"])[-1]=="black":
            but_array[x][y+1].config(bg="white")
        else:
            but_array[x][y+1].config(bg="black")

    if x-1>-1:
        if list(but_array[x-1][y].config()["background"])[-1]=="black":
            but_array[x-1][y].config(bg="white")
        else:
            but_array[x-1][y].config(bg="black")

    if y-1>-1:
        if list(but_array[x][y-1].config()["background"])[-1]=="black":
            but_array[x][y-1].config(bg="white")
        else:
            but_array[x][y-1].config(bg="black")
    if win_check()==True:
        label_1.config(text="You Win The Game")
    label_turn.config(text=str(int(list(label_turn.config()["text"])[-1])+1))

def rand_gen():
    rand_col=[]
    rand_row=[]
    for i in range(3):
        rand_col.append(randint(0,4))
        rand_row.append(randint(0,4))
    but_array[rand_row[0]][rand_col[0]].config(bg="white")
    but_array[rand_row[1]][rand_col[1]].config(bg="white")
    but_array[rand_row[2]][rand_col[2]].config(bg="white")
def reset():
    for i in range(5):
        for j in range(5):
            but_array[i][j].config(bg="black")
    rand_gen()
if __name__=="__main__":
    but_array=[]
    program=Tk()
    program.title("Lights Out")
    root=Frame(program)
    root.pack(expand=YES,fill=BOTH)
    label_1=Label(root,text="Play . . .")
    label_1.pack()
    label_frame=Frame(root)
    label_frame.pack(expand=YES,fill=BOTH,side=TOP)
    label_show=Label(label_frame,text="Click : ")
    label_show.pack(side=LEFT)
    label_turn=Label(label_frame,text="0")
    label_turn.pack(side=RIGHT)

    val=IntVar()
    for i in range(5):
        but_temp=[]
        frame=Frame(root)
        frame.pack(expand=YES,fill=BOTH)
        for j in range(5):
            but_temp.append(Button(frame,text="",command=lambda k=i, w=j:but_func(k,w),bg="black"))
            but_temp[j].pack(side=LEFT,expand=YES,fill=BOTH)
        but_array.append(but_temp)
    frame_exit=Frame(root)
    frame_exit.pack(expand=YES,fill=BOTH,side=TOP)
    frame_reset=Frame(root)
    frame_reset.pack(expand=YES,fill=BOTH,side=TOP)
    but_exit=Button(frame_exit,text="Exit",command= lambda : program.destroy())
    but_exit.pack(expand=YES,side=TOP,fill=BOTH)
    but_reset=Button(frame_reset,text="Reset",command=lambda : reset())
    but_reset.pack(expand=YES,fill=BOTH,side=TOP)
    rand_gen()
    root.mainloop()


# -*- coding: utf-8 -*-

from openerp import models, fields, api, _
from openerp.exceptions import except_orm, Warning, RedirectWarning

import datetime
import pdb

Device_State = [
    ('used','Używane'),
    ('unused','Nieużywane')
]

class c_motohour_wizard(models.TransientModel):
    _name = "c.motohour.wizard"
    _description = "Motogodziny"

    hours = fields.Float(string='Ilość godzin', required=True)

    @api.one
    def add_motohour(self):
        w = self.browse(self._ids)
        device_id = self._context['active_id']
        device = self.env['c.device'].browse(device_id)

        if device.motohours > w.hours:
            raise except_orm(('Ostrzeżenie!'), ('Poprzedni wpis motogodzin jest większy od aktualnego'))

        self.env['c.device.motohours'].create({'device_id': device.id, 'hours': w.hours})


import json
import tablib
import unicodecsv

from biblion.models import Post
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import get_current_site
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.template.loader import render_to_string
from symposion.proposals.models import ProposalBase
from symposion.reviews.models import ProposalResult
from symposion.reviews.views import access_not_permitted
from symposion.schedule.models import Slot
from symposion.speakers.models import Speaker
from symposion.sponsorship.models import Sponsor
from unidecode import unidecode

def json_serializer(obj):
    if isinstance(obj, datetime.time):
        return obj.strftime("%H:%M")
    raise TypeError

def duration(start, end):
    start_dt = datetime.strptime(start.isoformat(), "%H:%M:%S")
    end_dt = datetime.strptime(end.isoformat(), "%H:%M:%S")
    delta = end_dt - start_dt
    return delta.seconds // 60

@login_required
def proposal_export(request):
    if not request.user.is_superuser:
        return access_not_permitted(request)

    content_type = 'text/csv'
    response = HttpResponse(content_type=content_type)
    response['Content-Disposition'] = 'attachment; filename="proposal_export.csv"'

    domain = get_current_site(request).domain
    writer = unicodecsv.writer(response, quoting=unicodecsv.QUOTE_ALL)
    writer.writerow([
        'id',
        'proposal_type',
        'speaker',
        'speaker_email',
        'title',
        'audience_level',
        'kind',
        'recording_release',
        'comment_count',
        'plus_one',
        'plus_zero',
        'minus_zero',
        'minus_one',
        'review_detail'
    ])

    proposals = ProposalBase.objects.all().select_subclasses().order_by('id')
    for proposal in proposals:
        try:
            proposal.result
        except ProposalResult.DoesNotExist:
            ProposalResult.objects.get_or_create(proposal=proposal)

        writer.writerow([
            proposal.id,
            proposal._meta.module_name,
            proposal.speaker,
            proposal.speaker.email,
            proposal.title,
            proposal.get_audience_level_display(),
            proposal.kind,
            proposal.recording_release,
            proposal.result.comment_count,
            proposal.result.plus_one,
            proposal.result.plus_zero,
            proposal.result.minus_zero,
            proposal.result.minus_one,
            'https://{0}{1}'.format(domain, reverse('review_detail',
                                                    args=[proposal.pk])),
        ])
    return response

def schedule_json(request):
    slots = Slot.objects.all().order_by("start")
    data = []
    for slot in slots:
        if slot.kind.label in ["talk", "tutorial", "plenary"] and slot.content and slot.content.proposal.kind.slug in ["talk", "tutorial"]:
            if hasattr(slot.content.proposal, "recording_release"):
                slot_data = {
                    "name": slot.content.title,
                    "room": ", ".join(room["name"] for room in slot.rooms.values()),
                    "start": datetime.combine(slot.day.date, slot.start).isoformat(),
                    "end": datetime.combine(slot.day.date, slot.end).isoformat(),
                    "duration": duration(slot.start, slot.end),
                    "authors": [s.name for s in slot.content.speakers()],
                    "released": slot.content.proposal.recording_release,
                    "license": "",
                    "contact": [s.email for s in slot.content.speakers()] if request.user.is_staff else ["redacted"],
                    "abstract": slot.content.abstract.raw,
                    "description": slot.content.description.raw,
                    "conf_key": slot.pk,
                    "conf_url": "https://%s%s" % (
                        Site.objects.get_current().domain,
                        reverse("schedule_presentation_detail", args=[slot.content.pk])
                    ),

                    "kind": slot.content.proposal.kind.slug,
                    "tags": "",
                }
        elif slot.kind.label == "lightning":
            slot_data = {
                "name": slot.content_override.raw if slot.content_override else "Lightning Talks",
                "room": ", ".join(room["name"] for room in slot.rooms.values()),
                "start": datetime.combine(slot.day.date, slot.start).isoformat(),
                "end": datetime.combine(slot.day.date, slot.end).isoformat(),
                "duration": duration(slot.start, slot.end),
                "authors": None,
                "released": True,
                "license": "",
                "contact": None,
                "abstract": "Lightning Talks",
                "description": "Lightning Talks",
                "conf_key": slot.pk,
                "conf_url": None,
                "kind": slot.kind.label,
                "tags": "",
            }
        else:
            continue
        data.append(slot_data)

    return HttpResponse(
        json.dumps(data, default=json_serializer),
        content_type="application/json"
    )

@login_required
def schedule_guidebook(request):
    headers = (
        'Session Title',
        'Date',
        'Time Start',
        'Time End',
        'Room/Location',
        'Schedule Track (Optional)',
        'Description (Optional)'
    )

    slots = Slot.objects.all().order_by('start')
    data = []
    for slot in slots:
        # authors = slot.content.speakers() if hasattr(slot.content, 'speakers') else []

        if slot.content_override:
            name = slot.content_override.raw
        else:
            name = slot.content.title if hasattr(slot.content, 'title') else ''

        description = slot.content.description.raw if hasattr(slot.content, 'description') else ''
        description = unidecode(description)
        description = description.replace('\r', '')
        description = description.replace('\n', '<br>')
        room_location = ', '.join(room['name'] for room in slot.rooms.values())
        track = slot.content.proposal.get_audience_level_display() if hasattr(slot.content, 'proposal') else ''

        if track == 'Not Applicable':
            track = 'N/A'

        slot_data = [
            name,
            slot.day.date.isoformat(),
            slot.start.isoformat(),
            slot.end.isoformat(),
            room_location,
            track,
            description,
        ]

        data.append(slot_data)

    data = tablib.Dataset(*data, headers=headers)

    response = HttpResponse(
        data.xlsx,
        content_type='application/vnd.ms-excel'
    )
    response['Content-Disposition'] = 'attachment; filename="guidebook_schedule.xls"'
    return response

@login_required
def guidebook_sponsor_export(request):
    content_type = 'text/csv'
    response = HttpResponse(content_type=content_type)
    response['Content-Disposition'] = 'attachment; filename="guidebook_sponsors.csv"'

    writer = unicodecsv.writer(response, quoting=unicodecsv.QUOTE_ALL)
    writer.writerow([
        'Name',
        'Sub-Title (i.e. Location, Table/Booth, or Title/Sponsorship Level)',
        'Description (Optional)',
        'Location/Room',
        'Image (Optional)'
    ])

    sponsors = Sponsor.objects.active()
    for sponsor in sponsors:
        writer.writerow([
            sponsor.name,
            sponsor.level.name,
            sponsor.listing_text,
            '',
            'https://{0}{1}'.format(
                Site.objects.get_current().domain,
                sponsor.website_logo.url
            )
        ])

    return response

@login_required
def guidebook_speaker_export(request):
    content_type = 'text/csv'
    response = HttpResponse(content_type=content_type)
    response['Content-Disposition'] = 'attachment; filename="guidebook_speakers.csv"'

    writer = unicodecsv.writer(response, quoting=unicodecsv.QUOTE_ALL)
    writer.writerow([
        'Name',
        'Sub-Title (i.e. Location, Table/Booth, or Title/Sponsorship Level)',
        'Description (Optional)',
        'Location/Room',
        'Image (Optional)'
    ])

    speakers = Speaker.objects.filter(
        presentations__isnull=False,
        presentations__cancelled=False)
    for speaker in speakers:

        if hasattr(speaker.photo, 'url'):
            photo_url = 'https://{0}{1}'.format(
                Site.objects.get_current().domain,
                speaker.photo.url
            )
        else:
            photo_url = ''

        writer.writerow([
            speaker.name,
            '',
            unidecode(speaker.biography.rendered),
            '',
            photo_url,
        ])

    return response

def guidebook_news_feed(request):
    """
    Sections are broken in the version of `biblion` that we are using so
    lifting this form `pinax-blog` which is the successor.

    https://github.com/pinax/pinax-blog/blob/master/pinax/blog/views.py#L146
    """
    current_site = Site.objects.get_current()

    feed_title = 'DjangoCon US News Updates'
    feed_description = 'The latest updates and additions for DjangoCon US.'
    feed_mimetype = 'application/rss+xml'
    feed_template = 'pinax/blog/rss_feed.xml'

    blog_url = 'http://%s%s' % (current_site.domain, reverse('blog'))
    # feed_url = 'http://%s%s' % (current_site.domain, reverse(url_name, kwargs=kwargs))

    posts = Post.objects.published().exclude(title__endswith='Sponsor')\
        .order_by('-published')

    if posts:
        feed_updated = posts[0].updated
    else:
        feed_updated = datetime(2009, 8, 1, 0, 0, 0)

    feed = render_to_string(feed_template, {
        # 'feed_id': feed_url,
        'feed_title': feed_title,
        'feed_description': feed_description,
        'blog_url': blog_url,
        # 'feed_url': feed_url,
        'feed_updated': feed_updated,
        'entries': posts,
        'current_site': current_site,
    })

    return HttpResponse(feed, content_type=feed_mimetype)


import pickle

class Program:
    def __init__(self,name, txt, cost, protected, ext):
        self.name = name
        self.txt = txt
        self.cost = cost
        self.protected = protected
        self.exten = ext

try:
    f = open("soft.db", "rb+")
except FileNotFoundError:
    f = open("soft.db", "wb+")
    pickle.dump([], f)

data = pickle.load(f)
f.close()
while True:
    print("1. Add software\n2. View market\n3. Exit")
    ent = input("Select option: ")
    if ent == "1":
        name = input("Enter software name: ")
        fl = input("Enter file_path: ")
        with open(fl, "r") as fl:
            txt = fl.read()
        cost = int(input("Enter cost: "))
        prot = input("Do you want to hide your code(y/n)?: ")
        pro = True if prot.lower() == "y" else False
        ext = input("Enter file extension: ")
        pr = Program(name, txt, cost, pro, ext)
        data.append(pr)
        print("Program '{}' added".format(pr.name))
    elif ent == "2":
        while True:
            for nm,x in enumerate(data, start=1):
                print("{}. {} cost:{}$".format(nm,x.name, x.cost))
            ent = input("Type a number to view a program, 'e' - to exit: ")
            if ent == "e":
                break
            else:
                prog = data[int(ent)-1]
                code = prog.txt if not prog.protected else "The code is hidden"
                print("{}    cost:{}$".format(prog.name, prog.cost))
                print("Code:\n{}".format(code))
                print("\n1. Buy software\n2. Back")
                ent = input("Select: ")
                if ent == "1":
                    loc = input("Enter location to upload file: ")
                    loc += "/" + "purchased." + prog.exten
                    fl = open(loc, "w")
                    fl.write(prog.code)
                    fl.close()
                    print("Purchase succesfull.")
                    print("You can find the software at " + loc)

    elif ent == "3":
        f = open("soft.db", "wb")
        pickle.dump(data, f)
        f.close()


import random

# Функция формирует список длины N случайных имен списка names_list
def F(names_list, N):
    result=[None]*N # Инициализация списка из N пустых элементов
    for i in range (0,N):
        result[i]=names_list[int(random.random()*len(names_list))]
    return result
    # 2 способ - Использование готовой функции:
    # return random.choices(names_list, k=N)

# Функция вычисляет наиболее частое имя
def Common_Word(list):
    stat={}
    for i in range(0,len(list)):
        if list[i] in stat.keys():
            stat[list[i]]+=1
        else:
            stat[list[i]]=1
    sorted_list=sorted(stat,key=stat.get, reverse=True)
    return sorted_list[0]

# Функция вычисляет наиболее редкой начальной буквы
def Rare_Letter(list):
    stat={}
    for i in range(0,len(list)):
        if list[i][0:1] in stat.keys():
            stat[list[i][0:1]]+=1
        else:
            stat[list[i][0:1]]=1
    sorted_list=sorted(stat,key=stat.get, reverse=False)
    return sorted_list[0]

# Функция определяет дату последнего лога в файле:
def Last_Log_file(filename):
    text_file = open(filename, "r")
    lines = text_file.readlines()
    # print(lines)
    # print(len(lines))
    text_file.close()

    sorted_lines=sorted(lines,reverse=True)
    # print(sorted_lines[0])
    return sorted_lines[0][0:23]

if __name__=='__main__' :
    Names=['Алексей', 'Анна', 'Александр', 'Екатерина', 'Павел', 'Мария', 'Артемий', 'Андрей', 'Ирина', 'Олимпиада'
        , 'Надежда', 'Сергей', 'Вера', 'Любовь', 'Тимофей', 'Иоанн', 'Пётр', 'Ксения', 'София', 'Марфа']

    ch_list=F(Names, N=100)
    print(ch_list)

    print(Common_Word(ch_list))

    print(Rare_Letter(ch_list))

    print(Last_Log_file('log'))

# with open('log','r') as f:
#     for line in f:
#         curdate=line[0:23]
#         print(curdate)
#

# f=open('log', 'r')
# for line in f:
#     print(line)
# # content=f.read()
# # print(content)
# f.close()


# 从网络上获取一个图片（一般以jpg格式结尾），图片实际内容为2进制
import requests
import os
url = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1849459778,3492875633&fm=26&gp=0.jpg"  # 点击图片右键赋值Url即可
# 设置获取文件后存储在本机哪个位置,注意windows下文件采用反斜杠\来表示路径，但是在字符串中反斜杠用做转义字符因此使用双反斜杠\\
path = "C:\\Users\\71058\\Desktop\\epub\\a.jpg"
r = requests.get(url)
print(r.status_code)  # 200获取成功
# print(len(r.text))   # 图片采用字符串解释出现乱码
# print(r.text[:100])
# 已经获得了这个文件那么接下来就是如何将其内容保存在本地电脑中，我们采用文件写方法将内容写入即可

with open(path, "wb") as f:
    f.write(r.content)  # 如果路径中没有文件则创建一个空文件，通过content获得返回的二进制形式的内容，note:每次写都是从头开始写，因此永远可以写，哪怕文件存在

f.close()

# 更加优化（排除错误）的写法
url = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1849459778,3492875633&fm=26&gp=0.jpg"
root = "C:\\Users\\71058\\Desktop\\epub"   # 为了能够灵活的命名文件，可以使用网站上的名字也可以使用自己定义的名字
path = root + "\\安达与岛村.jpg"
try:
    if not os.path.exists(root):  # 判断根目录是否存在
        os.mkdir(root)
    if not os.path.exists(path):  # 判断文件是否已经存在
        r = requests.get(url)
        r.raise_for_status()
        with open(path, "wb") as f:
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已经存在")
except:
    print("爬取失败")


#!/usr/bin/python3

import glob
import re
import sys

import debianbts as bts

# Shell: /bin/sh linked to /bin/dash
FALSE_POSITIVES = set(['/bin/sh', '/bin/dash',
                   '/usr/bin/sh', '/usr/bin/dash',
                   '/usr/sbin/piuparts',
                   '/usr/share/fonts',
                  ])

for dpkg_list in glob.glob('/var/lib/dpkg/info/*.list') + glob.glob('/var/lib/dpkg/info/*.conffiles'):
    with open(dpkg_list, 'r') as files:
        for file in files:
            FALSE_POSITIVES.add(file.rstrip('\n'))

# exclude "'" because it's added by dpkg in error messages
re_cruft = re.compile(r'/(?:bin|usr|etc|var|\.cache)/[A-Za-z0-9_\/\.\-]*')

# https://udd.debian.org/cgi-bin/bts-usertags.cgi?user=cruft-ng@packages.debian.org&tag=cruft
if len(sys.argv) > 1:
    bugs = [int(bug) for bug in sys.argv[1:]]
else:
    bugs = bts.get_usertag('cruft-ng@packages.debian.org', tags=['cruft'])['cruft']

cruft = dict()

todo = set(bugs)
done = set()

while todo:
    todo -= done
    for bug in bts.get_status(list(todo)):
        todo.update(set(bug.mergedwith))
        done.add(bug.bug_num)
        for match in re.findall(re_cruft, bug.subject):
            match = match.rstrip('./')
            if match in cruft:
                continue
            cruft[match] = (bug.bug_num, bug.source, bug.subject)
        for mail in bts.get_bug_log(bug.bug_num):
            for line in mail['body'].splitlines():
                for match in re.findall(re_cruft, line):
                    if match in FALSE_POSITIVES:
                        continue
                    if match.startswith('/var/lib/dpkg/'):
                        continue
                    if '  interest-noawait ' in line:
                        continue
                    match = match.rstrip('./')
                    if match in cruft:
                        # keep original bug report
                        continue
                    cruft[match] = (bug.bug_num, bug.source, line)

for path,data in sorted(cruft.items()):
    bug, package, raw = data
    #print(raw)
    print('%s %s %s' % (path, bug, package))


from numpy import *
train_x = []
train_y = []
fileIn = open('/Users/cengchenchen/Downloads/python/testset.txt')
for line in fileIn.readlines():
    lineArr = line.strip().split(',')
    train_x.append([float(lineArr[0]), float(lineArr[1])])
    train_y.append([float(lineArr[2])])
    x = mat(train_x)
    y = mat(train_y)


# 链接：https://leetcode.com/problems/increasing-order-search-tree/
# 题意：给定一棵二叉搜索树 root ，将其转换成最左侧结点为根结点，
#      且所有结点无左子结点的树，最后再返回结果树的根节点。

# 数据限制：
#  这棵树的结点数在 [0, 100] 内
#  0 <= Node.val <= 1000

# 输入： root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
# 输出： [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
# 解释：       5                1
#          /     \              \
#         3       6              2
#        / \       \       →      \
#       2   4       8              3
#      /           / \              \
#     1           7   9              4
#                                     \
#                                      5
#                                       \
#                                        6
#                                         \
#                                          7
#                                           \
#                                            8
#                                             \
#                                              9

# 输入： root = [5,1,7]
# 输出： [1,null,5,null,7]
# 解释： 5            1
#      / \     →      \
#     1   7            5
#                       \
#                        7

# 思路： 递归
#
#      二叉搜索树是左子树的值小于根节点，右子树的值大于根节点。
#
#      所以可以通过递归的方式来中序遍历这棵树，
#      为了方便处理，我们维护一个 right_most 结点，
#      表示结果树中最右侧的结点，
#      初始化为 dummy 结点，这样就不需要特殊处理了。
#
#      使用 dfs(root) 闭包来处理当前结点，
#      同时该闭包能引用外部变量 right_most ，
#      如果 root 为空，则直接返回。
#
#      否则，先递归处理左子树 dfs(root.left) ，
#      然后，将当前结点插入到 right_most 的右侧，
#      即 right_most.right = root 。
#
#      同时我们要更新 right_most 为当前结点，
#      即 right_most = root ，
#      最后再递归处理右子树 dfs(root.right) 。
#
#
#      时间复杂度：O(n)
#          1. 需要遍历二叉搜索树中全部 O(n) 个结点
#      空间复杂度：O(n)
#          1. 栈递归深度就是树高，最差情况下，全部 O(n) 个结点在一条链上

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:
        # 使用一个 dummy 结点，方便后续处理
        dummy: TreeNode = TreeNode()
        # 定义 dfs 中序遍历函数
        right_most: TreeNode = dummy
        def dfs(root: TreeNode):
            if root:
                # 先递归处理左子树
                dfs(root.left)
                root.left = None
                # 然后把 root 挂在 right_most 的右子结点上
                nonlocal right_most
                right_most.right = root
                # 移动 rightMost 到其右子结点上（也就是 root 结点）
                right_most = right_most.right
                # 最后递归处理右子树
                dfs(root.right)

        # 递归处理二叉树 root
        dfs(root)
        # dummy 的右子结点就是结果树的根节点
        return dummy.right

Python3/src/0801 ~ 0900/0897 - Increasing Order Search Tree.py


import source   # Access the source
source.main()   # and execute main.

####################
# source/__init__.py
####################

import tkinter, time, os, sys, test.support
import xml.sax._exceptions

from tkinter import Label, Frame, LabelFrame, Entry, Button
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showinfo, showwarning, showerror

from . import exe_queue, gui_logs, splash, teach_me, testbank

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

def main():
    with test.support.captured_output('stderr') as stderr:
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        with splash.Splash(root, 'images//QuizMe Logo.gif', 3):
            # Set up the root window.
            root.title('QuizMe 2.5')
            root.resizable(False, False)
            root.wm_iconbitmap(default='images//Icon.ico')
            # Create the program GUI.
            application = QuizMe(root)
            application.grid()
        mainloop(root)
    cleanup(stderr)

def mainloop(root):
    # Threading Support Experiment
    gui_logs.root = exe_queue.Pipe(root)
    while True:
        try:
            root.update()
        except:
            return
        time.sleep(1 / 64)
        gui_logs.root.update()

def cleanup(stream):
    # Record Any Errors
    value = stream.getvalue()
    if value:
        today = time.asctime()
        ruler = '=' * len(today)
        stamp = '{1}\n{0}\n{1}\n'.format(today, ruler)
        file = open('error.log', 'at')
        file.write(stamp)
        file.write(value)
        file.close()

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

class QuizMe(Frame):

    PROMPT = 'What testbank do you want to open?'

    def __init__(self, master):
        # Initialize the Frame object.
        super().__init__(master)
        # Create every opening widget.
        self.intro = Label(self, text=self.PROMPT)
        self.group = LabelFrame(self, text='Filename')
        self.entry = Entry(self.group, width=35)
        self.click = Button(self.group, text='Browse ...', command=self.file)
        self.enter = Button(self, text='Continue', command=self.start)
        # Make Windows entry bindings.
        def select_all(event):
            event.widget.selection_range(0, tkinter.END)
            return 'break'
        self.entry.bind('<Control-Key-a>', select_all)
        self.entry.bind('<Control-Key-/>', lambda event: 'break')
        # Position them in this frame.
        options = {'sticky': tkinter.NSEW, 'padx': 5, 'pady': 5}
        self.intro.grid(row=0, column=0, **options)
        self.group.grid(row=1, column=0, **options)
        self.entry.grid(row=0, column=0, **options)
        self.click.grid(row=0, column=1, **options)
        self.enter.grid(row=2, column=0, **options)

    def file(self):
        # Find filename for self.entry
        options = {'defaultextension': '.xml',
                   'filetypes': [('All', '*'), ('XML', '.xml')],
                   'initialdir': os.path.join(os.getcwd(), 'tests'),
                   'parent': self,
                   'title': 'Testbank to Open'}
        filename = askopenfilename(**options)
        if filename:
            self.entry.delete(0, tkinter.END)
            self.entry.insert(0, filename)

    def start(self):
        # Validate self.entry and begin
        path = self.entry.get()
        if os.path.exists(path):
            if os.path.isfile(path):
                try:
                    bank = testbank.parse(path)
                    engine = teach_me.FAQ(bank)
                except xml.sax._exceptions.SAXParseException as error:
                    title = error.getMessage().title()
                    LN = error.getLineNumber()
                    CN = error.getColumnNumber()
                    message = 'Line {}, Column {}'.format(LN, CN)
                    showerror(title, message, master=self)
                except AssertionError as error:
                    title = 'Validation Error'
                    message = error.args[0]
                    showerror(title, message, master=self)
                except:
                    title = 'Error'
                    message = 'Unknown exception was thrown!'
                    showerror(title, message, master=self)
                else:
                    self.done = False
                    self.next_event = iter(engine).__next__
                    self.after_idle(self.execute_quiz)
            else:
                title = 'Warning'
                message = 'File does not exist.'
                showwarning(title, message, master=self)
        else:
            title = 'Information'
            message = 'Path does not exist.'
            showinfo(title, message, master=self)

    def execute_quiz(self):
        # Follow the logic from the last program.
        # This will be called to handle an event.
        try:
            event = self.next_event()
        except StopIteration:
            assert self.done, 'Final event not processed!'
        else:
            if isinstance(event, teach_me.Enter):
                gui_logs.ShowStatus(self, 'Entering', event, self.execute_quiz)
            elif isinstance(event, teach_me.Exit):
                gui_logs.ShowStatus(self, 'Exiting', event, self.execute_quiz)
                self.last_exit = event.kind
            elif isinstance(event, teach_me.Question):
               gui_logs. AskQuestion(self, event, self.execute_quiz)
            elif isinstance(event, teach_me.Report):
                flag = [True]
                if self.last_exit == 'Section' and event.wrong:
                    flag[0] = False
                    gui_logs.ReviewProblems(self, event, flag)
                if flag[0]:
                    gui_logs.ShowReport(self, event, self.execute_quiz)
                if event.final:
                    title = 'Congratulations!'
                    message = 'You have finished the test.'
                    showinfo(title, message, master=self)
                    self.done = True
            else:
                title = 'Type Error'
                message = repr(event)
                showerror(title, message, master=self)


inputs = [*map(str.split, open("input.txt").read().splitlines())]

mem = dict()
for addr, _, val  in inputs:
    if addr == "mask":
        mask, l = val, len(val)
    if addr.startswith("mem"):
        addr = bin(int(addr[4:-1]))[2:].zfill(l)
        addrs = [str()]
        for n in range(l):
            if mask[n] == '0':
                addrs = [a+addr[n] for a in addrs]
            if mask[n] == '1':
                addrs = [a+'1' for a in addrs]
            if mask[n] == 'X':
                addrs = [a+x for a in addrs for x in ('0', '1')]
        for addr in addrs:
            mem[addr] = int(val)

print("part2", sum(mem.values()))


import sys
import math
import random
from statistics import mean
'''
Authors: Jackson Jacobs and Jorge Soto-Ventura

Implements the k-means algo.
'''

inputFileName= sys.argv[1]
inputFile= open("../datasets/" + inputFileName, "r")

allPoints= []
centers= []
oldcenters=[]
delAllPoints=[]
k= 5
counter=0
closestCenterList= [x * [] for x in range(k)]
for line in inputFile:
    word=line.split()
    x= int(word[0])
    y= int(word[1])
    allPoints.append([x, y])
inputFile.close()
delAllPoints= allPoints.copy()
centersChanged= True
#Append a random center
for x in range(k):
    i= random.randint(0, len(allPoints)-1)
    centers.append(allPoints[i])
    delAllPoints.remove(delAllPoints[i])
print(centers)
pointToCenterDistance=0 # The distance between this point and the closest center
while centersChanged == True:
    counter+=1
    if not counter % 100:
        print("Counter", counter)
        print("Centers", centers)
    oldCenters= centers.copy()
    for currentPoint in allPoints:
        currentList=0
        currentIndex=0
        pointToCenterDistance=-1 # Initialize to 0 each time we go to the next point
        for currentCenter in centers:
            currentDistance= math.sqrt(((currentCenter[0]- currentPoint[0])**2) + ((currentCenter[1] - currentPoint[1])**2)) # Get the current distance
            if pointToCenterDistance > currentDistance or pointToCenterDistance == -1: # Finds the point's closest center
                pointToCenterDistance= currentDistance
                currentList= currentIndex
            currentIndex+=1
        closestCenterList[currentList].append(currentPoint) #Appends the point to a nested list corresponding to the same index as the center in centers
    xCor=0
    yCor=0
    total=0
    for x in range(len(closestCenterList)): #Finds the length of closestCenter List could also just use k
        for y in range(len(closestCenterList[x])): #Find length of the nested list in closestCenterList[x]
            xCor+= closestCenterList[x][y][0] #Adds to X cor
            yCor+= closestCenterList[x][y][1] #Adds to Y Cor
            total+=1
        meanXCor= (xCor/total)
        meanYCor= (yCor/total)
        centers[x]= [meanXCor, meanYCor] #Adds the new mean of x and y to centers depending on the current center
    if centers != oldCenters:
        centersChanged = True #Keeps true if centers and old centers are not the same
        #print("Centers",centers)
        #print("OldCenters", oldCenters)
        closestCenterList=[x * [] for x in range(k)]
    else:
        centersChanged= False

#K-Means

#Print Stuff
print(centers)


import numpy as np
import matplotlib.pyplot as plt
from my_utils.functions import entradas, xor, capas_perceptron
from my_utils.functions_ej6 import entrenar_perceptron_multicapa_SA

''' EJERCICIO 6
Encontrar un perceptrón multicapa que resuelva una XOR de 2 entradas
mediante simulated annealing.
Graficar el error a lo largo del proceso de aprendizaje.
'''

#Numero de entradas
ENTRADAS = 2
#Capas ocultas
CAPAS_OCULTAS_PERCEPTRON = np.array([7])

x_input = entradas(ENTRADAS)
xor_output = xor(x_input)

#Capas de neuronas del perceptron
capas_perceptron = capas_perceptron(x_input, xor_output, CAPAS_OCULTAS_PERCEPTRON)

#Configuracion del ejercicio
W, errores = entrenar_perceptron_multicapa_SA(x_input, xor_output, capas_perceptron)

#Grafico Error vs Iteracion
plt.figure()
plt.rcParams["figure.figsize"] = (6,4)
plt.title(f"Evolución del error")
plt.plot(np.arange(errores.shape[0]), errores, label = f"Perceptrón de capas { capas_perceptron } .")
plt.grid()
plt.legend()
plt.xlabel("Iteraciones")
plt.ylabel("Error")

##Grafico Error vs Temperatura
TEMPERATURA_INICIAL = 40
ALFA = 0.95
T = np.array([TEMPERATURA_INICIAL])
for i in range(errores.shape[0]-1):
    T = np.append(T, T[-1]*ALFA)

plt.figure()
plt.rcParams["figure.figsize"] = (6,4)
plt.title(f"Evolución del error")

plt.plot( T,errores, label = f"Perceptrón de capas { capas_perceptron } .")
plt.grid()
plt.legend()
plt.xlabel("Temperatura")
plt.ylabel("Error")
plt.xlim(max(T), min(T))


################################################################################
#    Created by Oscar Martinez                                                 #
#    martinez@astro.rug.nl                                                     #
################################################################################
from ledama.leddb.Naming import LDS, CENTFREQ, STATION, CORR, DIRRA, DIRDEC,\
    NAME, STATION2, QKIND

# A class to define what is plotted
class DiagPlotKey:
    # Initialize with the several attributes that can define a diag. plot
    #    names is a list of the attributes, example [LDS, SBINDEX] or a string
    def __init__(self, names = None):
        if names != None:
            if type(names) == list:
                self.names = names
            else:
                self.names = []
                if ('l' in names):
                    self.names.append(LDS)
                if ('f' in names):
                    self.names.append(CENTFREQ)
                if ('s' in names):
                    self.names.append(STATION)
                if ('c' in names):
                    self.names.append(CORR)
                if ('r' in names):
                    self.names.append(DIRRA)
                if ('d' in names):
                    self.names.append(DIRDEC)
                if ('q' in names):
                    self.names.append(NAME)
                if ('b' in names):
                    self.names.append(STATION2)

    def getDescription(self):
        return 'l:' + LDS + ', f:' + CENTFREQ + ', s:' + STATION + ', c:' + CORR + ', r:' + DIRRA + ', d:' + DIRDEC + ', q:' + QKIND + ', b:' + STATION2

    # Get a tuple key with the only the values of the enabled attributes
    def getKey(self, attDict):
        key = []
        for name in self.names:
            key.append(str(attDict[name]))
        return tuple(key)

    # Get the attDict to be usde by getKey
    def getAttDict(self, lds, centFreq, station, corr, dirRA, dirDec, station2, qKind):
        return {LDS:lds, CENTFREQ:centFreq, STATION: station, CORR: corr, DIRRA:dirRA, DIRDEC:dirDec, STATION2: station2, NAME: qKind}

    # Compare two diagPlotKey, the must contain different att names
    def compare(self, diagPlotKey):
        for name in self.names:
            if name in diagPlotKey.names:
                return False
        return True

    # Check that the contained names in current key are also contained in the specified namesvalidate
    def validate(self, namesvalidate):
        for name in self.names:
            if (name != CORR) and (name not in namesvalidate):
                return False
        return True


import numpy as np
import queue
import time
import sys

import collections

import pprintpp
import pprint
import codecs

def read_file(filepath):
    with codecs.open(filepath, 'r', encoding='utf-8', errors='ignore') as txt:

        raw_txt = txt.read()

    raw_txt = raw_txt.upper()
    raw_txt.replace(' ','')
    raw_txt = raw_txt.strip()

    matrix = {}

    p = []
    m = raw_txt.split('\n')

    print(m)

    for i in m:
        x = i.split('=')

        value = x[1]

        matrix = {x[0]:value}
        # print(matrix)
        p.append(matrix)

    width = 0
    height = 0
    source = 0
    target = 0
    kingmode = False

    person = []
    for i in range(len(p)):

        if 'WIDTH' in p[i].keys():

            # print("v",p[i]["WIDTH"])
            width =   p[i]["WIDTH"]

        elif 'HEIGHT' in p[i].keys():
            # print("v",p[i]["HEIGHT"])
            height =  p[i]["HEIGHT"]

        elif 'SOURCE' in p[i].keys():
            # print("v",p[i]["SOURCE"])
            source = p[i]["SOURCE"]

            source = source.split(',')
            # print(source)
            source = (int(source[0]),int(source[1]))

        elif 'TARGET' in p[i].keys():
            # print('v',p[i]['TARGET'])
            target = p[i]['TARGET']
            target = target.split(',')
            # print(target)
            target = (int(target[0]),int(target[1]))

        elif 'KINGMODE' in p[i].keys():
            # print('v',p[i]['KINGMODE'])
            kingmode = p[i]['KINGMODE'].strip()

            if kingmode == 'TRUE':
                kingmode =True
            else:
                 kingmode =False

        elif "PERSON" in p[i].keys():
            # print("v",p[i]["PERSON"])s

            person.append(p[i]['PERSON'])
###
    width = int(width)+1
    height = int(height)+1

    Matrix = [[0 for x in range(height)] for y in range(width)]

    # pprint.pprint(Matrix)

    for i in range(len(person)):

        man  = person[i].split(',')
        x =  int(man[0])
        y =  int(man[1])
        Matrix[x-1][y-1] = 1

    pprint.pprint(Matrix)

    return Matrix, target, source, kingmode, width, height,target

grid, target, source, kingmode, width, height, target = read_file(sys.argv[1])

print(grid[target[0]][target[1]])

grid[target[0]][target[1]] = 9

pprint.pprint(grid)

def bfs(grid, start):
    count = 0;
    queue = collections.deque([[start]])
    seen = set([start])
    while queue:
        path = queue.popleft()
        x, y = path[-1]

        count += 1

        if grid[y][x] == goal:
            return path
        for x2, y2 in ((x+1,y), (x-1,y), (x,y+1), (x,y-1)):
            count += 1

            if 0 <= x2 < height  and 0 <= y2 <  width and grid[y2][x2] != wall and (x2, y2) not in seen:
                queue.append(path + [(x2, y2)])
                seen.add((x2, y2))

wall, clear, goal = 1, 0, 9

path = bfs(grid, (0, 0))

print(path)

maze = grid

for step in path:
    maze[step[0]][step[1]] = 2

for row in maze:
    line = []
    for col in row:
        if col == 1:
            line.append("p")
        elif col == 0:
            line.append("-")
        elif col == 2:
            line.append("*")
    print("".join(line))

start_time = time.time()
result =   example(argv)
time_taken = format(round((time.time() - start_time),9))
result = {'astar':{'comparisons':result,'clock':time_taken}}

print(result)


# coding:utf-8

from PyQt5.QtCore import (
    QAbstractAnimation, QEasingCurve, QPropertyAnimation, Qt, QTimer,
    pyqtSignal)
from PyQt5.QtGui import QBrush, QFont, QFontMetrics, QPainter, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QWidget

from my_functions.get_cover_path import getCoverPath
from my_functions.is_not_leave import isNotLeave
from my_widget.my_button import ThreeStateButton
from my_widget.my_slider import Slider

from .play_button import PlayButton
from .system_volume import SystemVolume

class SubPlayWindow(QWidget):
    """ 桌面左上角子播放窗口 """

    def __init__(self, parent=None, songInfo: dict = None):
        super().__init__(parent)
        self.songInfo = {}
        if songInfo:
            self.songInfo = songInfo
        self.__lastSongIconPath = {'normal': r'resource\images\sub_play_window\lastSong_50_50_normal.png',
                                   'hover': r'resource\images\sub_play_window\lastSong_50_50_hover.png',
                                   'pressed': r'resource\images\sub_play_window\lastSong_50_50_pressed.png'}
        self.__nextSongIconPath = {'normal': r'resource\images\sub_play_window\nextSong_50_50_normal.png',
                                   'hover': r'resource\images\sub_play_window\nextSong_50_50_hover.png',
                                   'pressed': r'resource\images\sub_play_window\nextSong_50_50_pressed.png'}
        # 创建小部件
        self.volumeSlider = Slider(Qt.Vertical, self)
        self.volumeLabel = QLabel(self)
        self.lastSongButton = ThreeStateButton(
            self.__lastSongIconPath, self, (50, 50))
        self.playButton = PlayButton(self)
        self.nextSongButton = ThreeStateButton(
            self.__nextSongIconPath, self, (50, 50))
        self.albumPic = QLabel(self)
        self.songNameLabel = QLabel(self)
        self.songerNameLabel = QLabel(self)
        self.ani = QPropertyAnimation(self, b'windowOpacity')
        self.timer = QTimer(self)
        # 系统音量控制类
        self.systemVolume = SystemVolume()
        # 初始化
        self.__initWidget()

    def __initWidget(self):
        """ 初始化小部件 """
        self.resize(635, 175)
        self.__initLayout()
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.FramelessWindowHint |
                            Qt.Window | Qt.WindowStaysOnTopHint)
        # 初始化音量滑块
        self.volumeSlider.setRange(0, 100)
        self.volumeSlider.setSingleStep(1)
        # 初始化动画和定时器
        self.timer.setInterval(3000)
        self.ani.setEasingCurve(QEasingCurve.Linear)
        self.ani.setDuration(700)
        self.ani.setStartValue(1)
        self.ani.setEndValue(0)
        # 分配ID
        self.volumeLabel.setObjectName('volumeLabel')
        self.songNameLabel.setObjectName('songNameLabel')
        self.songerNameLabel.setObjectName('songerNameLabel')
        # 设置层叠样式
        self.__setQss()
        # 将信号连接到槽
        self.__connectSignalToSlot()
        self.volumeSlider.setValue(self.systemVolume.getVolume())
        # 设置封面和标签
        self.updateWindow(self.songInfo)
        # 引用方法
        self.setPlay = self.playButton.setPlay

    def __initLayout(self):
        """ 初始化布局 """
        self.move(62, 75)
        self.albumPic.move(478, 25)
        self.playButton.move(222, 26)
        self.volumeLabel.move(32, 140)
        self.volumeSlider.move(34, 25)
        self.songNameLabel.move(122, 93)
        self.lastSongButton.move(122, 26)
        self.nextSongButton.move(322, 26)
        self.songerNameLabel.move(122, 135)
        self.albumPic.setFixedSize(125, 125)
        self.songNameLabel.setFixedWidth(285)
        self.songerNameLabel.setFixedWidth(290)
        self.volumeLabel.setFixedWidth(65)

    def updateWindow(self, songInfo: dict):
        """ 设置窗口内容 """
        self.songInfo = songInfo
        self.songName = self.songInfo.get('songName', '未知歌曲')
        self.songerName = self.songInfo.get('songer', '未知歌手')
        # 调整长度
        self.__adjustText()
        # 更新标签和专辑封面
        self.songNameLabel.setText(self.songName)
        self.songerNameLabel.setText(self.songerName)
        self.__setAlbumCover()

    def timerSlot(self):
        """ 定时器溢出时间 """
        self.timer.stop()
        self.ani.start()

    def enterEvent(self, e):
        """ 鼠标进入时停止动画并重置定时器 """
        self.timer.stop()
        if self.ani.state() == QAbstractAnimation.Running:
            self.ani.stop()
            self.setWindowOpacity(1)

    def leaveEvent(self, e):
        """ 鼠标离开窗口时打开计时器 """
        # 判断事件发生的位置发生在自己所占的rect内
        notLeave = isNotLeave(self)
        if not notLeave:
            self.timer.start()

    def show(self):
        """ show()时重置透明度并根据鼠标位置决定是否打开计时器 """
        self.setWindowOpacity(1)
        self.volumeSlider.setValue(self.systemVolume.getVolume())
        super().show()
        notLeave = isNotLeave(self)
        if not notLeave:
            self.timer.start()

    def paintEvent(self, e):
        """ 绘制背景色 """
        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)
        brush = QBrush(Qt.black)
        painter.setBrush(brush)
        # 绘制音量滑动条的背景
        painter.drawRect(0, 0, 81, 175)
        # 绘制控制面板的背景
        painter.drawRect(86, 0, 549, 175)

    def __connectSignalToSlot(self):
        """ 将信号连接到槽 """
        self.ani.finished.connect(self.hide)
        self.timer.timeout.connect(self.timerSlot)
        self.volumeSlider.valueChanged.connect(self.sliderValueChangedSlot)

    def __setQss(self):
        """ 设置层叠样式 """
        with open(r'resource\css\subPlayWindow.qss', encoding='utf-8') as f:
            self.setStyleSheet(f.read())

    def __setAlbumCover(self):
        """ 设置封面 """
        # 如果专辑信息为空就直接隐藏
        self.coverPath = getCoverPath(self.songInfo.get('modifiedAlbum'))
        self.albumPic.setPixmap(
            QPixmap(self.coverPath).scaled(
                125, 125, Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def __adjustText(self):
        """ 根据文本长度决定是否显示省略号 """
        fontMetrics_1 = QFontMetrics(QFont('Microsoft YaHei', 17, 63))
        self.songName = fontMetrics_1.elidedText(
            self.songName, Qt.ElideRight, 285)
        fontMetrics_2 = QFontMetrics(QFont('Microsoft YaHei', 9))
        self.songerName = fontMetrics_2.elidedText(
            self.songerName, Qt.ElideRight, 290)

    def __adjustVolumeLabelPos(self):
        """ 调整音量标签的位置 """
        if 10 <= int(self.volumeLabel.text()) <= 99:
            self.volumeLabel.move(32, 140)
        elif 0 <= int(self.volumeLabel.text()) <= 9:
            self.volumeLabel.move(37, 140)
        else:
            self.volumeLabel.move(27, 140)

    def sliderValueChangedSlot(self, value):
        """ 音量改变时调整系统音量并更新标签 """
        self.volumeLabel.setText(str(value))
        self.__adjustVolumeLabelPos()
        self.systemVolume.setVolume(value)


from unittest.mock import patch
from unittest import TestCase
from hamcrest import assert_that, equal_to
from ycmd import handlers
from ycmd.completers.cpp import clangd_completer
from ycmd.completers.language_server.language_server_completer import (
    LanguageServerConnectionTimeout )
from ycmd.tests.clangd import IsolatedYcmd, PathToTestFile
from ycmd.tests.test_utils import BuildRequest
from ycmd.user_options_store import DefaultOptions

class MockPopen:
  stdin = None
  stdout = None
  pid = 0

  def communicate( self ):
    return ( bytes(), None )

class UtilitiesTest( TestCase ):
  def test_ClangdCompleter_GetClangdCommand_NoCustomBinary( self ):
    user_options = DefaultOptions()

    # Supported binary in third_party.
    THIRD_PARTY = '/third_party/clangd'
    clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
    with patch( 'ycmd.completers.cpp.clangd_completer.GetThirdPartyClangd',
                return_value = THIRD_PARTY ):
      assert_that( clangd_completer.GetClangdCommand( user_options )[ 0 ],
                   equal_to( THIRD_PARTY ) )
      # With args
      clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
      CLANGD_ARGS = [ "1", "2", "3" ]
      user_options[ 'clangd_args' ] = CLANGD_ARGS
      assert_that( clangd_completer.GetClangdCommand( user_options )[ 1:4 ],
                   equal_to( CLANGD_ARGS ) )

    # No supported binary in third_party.
    clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
    with patch( 'ycmd.completers.cpp.clangd_completer.GetThirdPartyClangd',
                return_value = None ):
      assert_that( clangd_completer.GetClangdCommand( user_options ),
                   equal_to( None ) )

    clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED

  @patch( 'ycmd.completers.cpp.clangd_completer.FindExecutable',
          lambda exe: exe )
  def test_ClangdCompleter_GetClangdCommand_CustomBinary( self ):
    CLANGD_PATH = '/test/clangd'
    user_options = DefaultOptions()
    user_options[ 'clangd_binary_path' ] = CLANGD_PATH
    # Supported version.
    with patch( 'ycmd.completers.cpp.clangd_completer.CheckClangdVersion',
                return_value = True ):
      clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
      assert_that( clangd_completer.GetClangdCommand( user_options )[ 0 ],
                   equal_to( CLANGD_PATH ) )

      # No Clangd binary in the given path.
      with patch( 'ycmd.completers.cpp.clangd_completer.FindExecutable',
                  return_value = None ):
        clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
        assert_that( clangd_completer.GetClangdCommand( user_options ),
                     equal_to( None ) )

    # Unsupported version.
    with patch( 'ycmd.completers.cpp.clangd_completer.CheckClangdVersion',
                return_value = False ):
      # Never fall back to the third-party Clangd.
      clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
      assert_that( clangd_completer.GetClangdCommand( user_options ),
                   equal_to( None ) )

    clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED

  @patch( 'ycmd.completers.cpp.clangd_completer.GetVersion',
          side_effect = [ None,
                          ( 5, 0, 0 ),
                          clangd_completer.MIN_SUPPORTED_VERSION,
                          ( 13, 0, 0 ),
                          ( 13, 10, 10 ),
                          ( 100, 100, 100 ) ] )
  def test_ClangdCompleter_CheckClangdVersion( *args ):
    assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
                  equal_to( True ) )
    assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
                 equal_to( False ) )
    assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
                 equal_to( True ) )
    assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
                 equal_to( True ) )
    assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
                 equal_to( True ) )
    assert_that( clangd_completer.CheckClangdVersion( 'clangd' ),
                 equal_to( True ) )

  def test_ClangdCompleter_ShouldEnableClangdCompleter( self ):
    user_options = DefaultOptions()

    # Clangd not in third_party (or an old version).
    with patch( 'ycmd.completers.cpp.clangd_completer.GetThirdPartyClangd',
                return_value = None ):
      # Default.
      clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
      assert_that( clangd_completer.ShouldEnableClangdCompleter( user_options ),
                   equal_to( False ) )

      # Found supported binary.
      with patch( 'ycmd.completers.cpp.clangd_completer.GetClangdCommand',
                  return_value = [ 'clangd' ] ):
        assert_that(
            clangd_completer.ShouldEnableClangdCompleter( user_options ),
            equal_to( True ) )
      # No supported binary found.
      with patch( 'ycmd.completers.cpp.clangd_completer.GetClangdCommand',
                  return_value = None ):
        assert_that(
            clangd_completer.ShouldEnableClangdCompleter( user_options ),
            equal_to( False ) )

      # Clangd is disabled.
      user_options[ 'use_clangd' ] = 0
      assert_that(
          clangd_completer.ShouldEnableClangdCompleter( user_options ),
          equal_to( False ) )

    user_options = DefaultOptions()

    # Clangd in third_party with a supported version.
    with patch( 'ycmd.completers.cpp.clangd_completer.GetThirdPartyClangd',
                return_value = 'third_party_clangd' ):
      # Default.
      clangd_completer.CLANGD_COMMAND = clangd_completer.NOT_CACHED
      assert_that( clangd_completer.ShouldEnableClangdCompleter( user_options ),
                   equal_to( True ) )

      # Enabled.
      user_options[ 'use_clangd' ] = 1
      # Found supported binary.
      with patch( 'ycmd.completers.cpp.clangd_completer.GetClangdCommand',
                  return_value = [ 'clangd' ] ):
        assert_that(
            clangd_completer.ShouldEnableClangdCompleter( user_options ),
            equal_to( True ) )
      # No supported binary found.
      with patch( 'ycmd.completers.cpp.clangd_completer.GetClangdCommand',
                  return_value = None ):
        assert_that(
            clangd_completer.ShouldEnableClangdCompleter( user_options ),
            equal_to( False ) )

      # Disabled.
      user_options[ 'use_clangd' ] = 0
      assert_that( clangd_completer.ShouldEnableClangdCompleter( user_options ),
                   equal_to( False ) )

  @patch( 'subprocess.Popen', return_value = MockPopen() )
  def test_ClangdCompleter_GetVersion( self, mock_popen ):
    assert_that( clangd_completer.GetVersion( '' ),
                 equal_to( None ) )
    mock_popen.assert_called()

  def test_ClangdCompleter_ParseClangdVersion( self ):
    cases = [
      ( 'clangd version 10.0.0 (https://github.com/llvm/llvm-project.git '
        '45be5e477e9216363191a8ac9123bea4585cf14f)', ( 10, 0, 0 ) ),
      ( 'clangd version 8.0.0-3 (tags/RELEASE_800/final)', ( 8, 0, 0 ) ),
      ( 'LLVM (http://llvm.org/):\nLLVM version 6.0.0\n'
        'Optimized build.\nDefault target: x86_64-unknown-linux-gnu\n'
        'Host CPU: haswell', ( 6, 0, 0 ) ),
    ]

    for version_str, expected in cases:
      assert_that( clangd_completer.ParseClangdVersion( version_str ),
                   equal_to( expected ) )

  @IsolatedYcmd()
  def test_ClangdCompleter_ShutdownFail( self, app ):
    completer = handlers._server_state.GetFiletypeCompleter( [ 'cpp' ] )
    with patch.object( completer, 'ShutdownServer',
                       side_effect = Exception ) as shutdown_server:
      completer._server_handle = MockPopen()
      with patch.object( completer, 'ServerIsHealthy', return_value = True ):
        completer.Shutdown()
        shutdown_server.assert_called()

  def test_ClangdCompleter_GetThirdParty( self ):
    with patch( 'ycmd.completers.cpp.clangd_completer.GetExecutable',
                return_value = None ):
      assert_that( clangd_completer.GetThirdPartyClangd(),
                   equal_to( None ) )

    with patch( 'ycmd.completers.cpp.clangd_completer.GetExecutable',
                return_value = '/third_party/clangd' ):
      with patch( 'ycmd.completers.cpp.clangd_completer.CheckClangdVersion',
                  return_value = True ):
        assert_that( clangd_completer.GetThirdPartyClangd(),
                     equal_to( '/third_party/clangd' ) )

      with patch( 'ycmd.completers.cpp.clangd_completer.CheckClangdVersion',
                  return_value = False ):
        assert_that( clangd_completer.GetThirdPartyClangd(),
                     equal_to( None ) )

  @IsolatedYcmd()
  def test_ClangdCompleter_StartServer_Fails( self, app ):
    with patch( 'ycmd.completers.language_server.language_server_completer.'
                'LanguageServerConnection.AwaitServerConnection',
                side_effect = LanguageServerConnectionTimeout ):
      with patch( 'ycmd.completers.cpp.clangd_completer.ClangdCompleter.'
                  'ShutdownServer' ) as shutdown:
        resp = app.post_json( '/event_notification',
                       BuildRequest(
                         event_name = 'FileReadyToParse',
                         filetype = 'cpp',
                         filepath = PathToTestFile( 'foo.cc' ),
                         contents = ""
                       ) )
        assert_that( resp.status_code, equal_to( 200 ) )
        shutdown.assert_called()


# Cette macro permet de mettre a jour le TCP d'un robot defini par un mecanisme
#
# Press F5 to run the script
# Documentation: https://robodk.com/doc/en/RoboDK-API.html
# Reference:     https://robodk.com/doc/en/PythonAPI/index.html
# Note: It is not required to keep a copy of this file, your python script is saved with the station

# Imposer le nom du mecanisme (existant ou nouveau)
NOM_TCP_MOBILE = 'TCP Mecanisme'

# Option pour garder le TCP a jour en permanence
MISE_A_JOUR_PERMANENTE = True

#--------------------------------------------------
from robodk.robolink import *  # RoboDK API
from robodk.robomath import *  # Robot toolbox

RDK = Robolink()

mecanisme = None

# Extraire le premier mecanisme de moins de 3 axes attache a un robot
robot_list = RDK.ItemList(ITEM_TYPE_ROBOT)
for r in robot_list:
    if len(r.Joints().list()) <= 3 and r.Parent().Type() == ITEM_TYPE_ROBOT:
        mecanisme = r

if not mecanisme:
    raise Exception("Mecanisme pas trouve")

robot = mecanisme.Parent()
if not robot.Valid() or robot.Type() != ITEM_TYPE_ROBOT:
    raise Exception("Le mecanisme " + mecanisme.Name() + " n'est pas attache a un robot")

# Extraire le TCP existant, s'il y a lieu, ou en créer un de nouveau
tcp = RDK.Item(NOM_TCP_MOBILE, ITEM_TYPE_TOOL)
if not tcp.Valid():
    tcp = robot.AddTool(eye(4), NOM_TCP_MOBILE)

# Boucle infini pour garder le TCP à jour:
while True:
    # Extraire la position absolue du flange robot
    robot_flange_abs = robot.PoseAbs() * robot.SolveFK(robot.Joints())
    # Extraire la position absolue du flange mecanisme
    mechanisme_flange_abs = mecanisme.PoseAbs() * mecanisme.SolveFK(mecanisme.Joints())

    # Calculer le TCP (relation entre les 2 derniers)
    pose_tcp = invH(robot_flange_abs) * mechanisme_flange_abs

    # Mettre à jour le TCP
    tcp.setPoseTool(pose_tcp)

    # Arreter a la premiere iteration:
    if not MISE_A_JOUR_PERMANENTE:
        break