"""empty message

Revision ID: 97f6e102bccf
Revises: 6c4d9d4a8de3
Create Date: 2023-07-15 00:22:20.205512

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '97f6e102bccf'
down_revision = '6c4d9d4a8de3'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('invokation', sa.Column('starttime', sa.DateTime(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('invokation', 'starttime')
    # ### end Alembic commands ###


import sys
argCount = len(sys.argv) - 1

if argCount == 1:
    expectedVersion = sys.argv[1]
    versions = len(expectedVersion.split("."))
    majorMinor = str(sys.version_info[0]) + '.' + str(sys.version_info[1])

    if versions == 2:
        # Test only major and minor version
        if expectedVersion != majorMinor:
            raise Exception("Incorrect major + minor version detected\nExpected: " + expectedVersion + "\nActual: " + majorMinor)
    elif versions == 3:
        # Test major, minor and micro version
        majorMinorMicro = majorMinor + '.' + str(sys.version_info[2])
        if expectedVersion != majorMinorMicro:
            raise Exception("Incorrect major + minor + micro version detected\nExpected: " + expectedVersion + "\nActual: " + majorMinorMicro)
    else:
        raise Exception("Incorrect number of arguments supplied")
    print("Correct version of Python " + expectedVersion + " detected")
else:
    raise Exception("Incorrect number of arguments supplied")


#! /usr/bin/env python

import rospy
from std_msgs.msg import UInt32
import Adafruit_ADS1x15

adc = Adafruit_ADS1x15.ADS1015()
GAIN = 1
adc.start_adc(0, gain=GAIN)

print("Read the A/D")
print("Ctrl C to stop")

def talker():
    pub = rospy.Publisher('steerangle', UInt32, queue_size=50)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(5)
    while not rospy.is_shutdown():
        value = adc.get_last_result()
        rospy.loginfo(value)
        pub.publish(value)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass


"""Add Deposit.dateUpdated column."""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "98a7c44f7ca1"
down_revision = "49f58959dbd4"
branch_labels = None
depends_on = None

def upgrade():
    op.add_column("deposit", sa.Column("dateUpdated", sa.DateTime(), nullable=True))

def downgrade():
    op.drop_column("deposit", "dateUpdated")


# Inspired and based on pixegami's project:    https://github.com/pixegami-team/machine-psychology-python-art
# -----------------------------------------------------------------------------------------------------------

import art_generator_src

def menu():

    print("""

    WELCOME TO THE ART GENERATOR

    1. Enter how many images you want to crate (max. 50):
    2. Enter your name or any word:

    """)

if __name__ == '__main__':
    menu()

    images_number = input('1: ')
    try:
        images_number = int(images_number)
    except ValueError:
        print('Invalid option. Enter a number')
        images_number = input('1: ')
    if images_number > 50:
        print('The maximun images allowed to be created is 50')
        images_number = input('1: ')
    name = input('2: ')

    for i in range(1, images_number + 1):
        art_generator_src.generate(f'generated_art_image_{i}.png', name)
        print(f'Art # {i} Generated succesfully')


class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

class NodeManager:
    def __init__(self, data):
        self.head = Node(data)

    def add(self, data):
        if self.head == '':
            self.head = Node(data)
        else:
            node = self.head
            while node.next:
                node = node.next
            node.next = Node(data)

    def delete(self, data):
        # 1. delete head
        # 2. delete tail
        # 3. delete middle
        if self.head == '':
            print("No Node")
            return

        if self.head.data == data:
            tmp = self.head
            self.head = self.head.next
            del tmp
        else:
            node = self.head
            while node.next:
                if node.next.data == data:
                    tmp = node.next
                    node.next = node.next.next
                    del tmp
                else:
                    node = node.next

    def desc(self):
        node = self.head
        while node.next:
            print(node.data)
            node = node.next
        print(node.data)


#!/bin/python3

import math
import os
import random
import re
import sys

class BinarySearchTreeNode:
    def __init__(self, node_data):
        self.data = node_data
        self.left = None
        self.right = None

def insert_node_into_binary_search_tree(node, node_data):
    if node == None:
        node = BinarySearchTreeNode(node_data)
    else:
        if (node_data <= node.data):
            node.left = insert_node_into_binary_search_tree(node.left, node_data)
        else:
            node.right = insert_node_into_binary_search_tree(node.right, node_data)

    return node

def print_binary_search_tree_inorder_traversal(node, sep):
    if node == None:
        return

    print_binary_search_tree_inorder_traversal(node.left, sep)

    if node.left:
        print(sep, end='')
    print(node.data, end='')

    if node.right:
        print(sep, end='')

    print_binary_search_tree_inorder_traversal(node.right, sep)

#
# Complete the 'preorder_traversal' function below.
#
# The function accepts INTEGER_BINARY_SEARCH_TREE bst as parameter.
#

#
# For your reference:
#
# BinarySearchTreeNode:
#     int data
#     BinarySearchTreeNode left
#     BinarySearchTreeNode right
#
#

def preorder_traversal(bst):
    # Write your code here
    print (bst.data)
    if bst.left is not None:
        preorder_traversal(bst.left)
    if bst.right is not None:
        preorder_traversal(bst.right)

if __name__ == '__main__':
    input_bst_count = int(input().strip())

    input_bst = None

    for _ in range(input_bst_count):
        input_bst_item = int(input().strip())
        input_bst = insert_node_into_binary_search_tree(input_bst, input_bst_item)

    preorder_traversal(input_bst)


import math

from fxpmath import Fxp

lut_s = []
lut_c = []

# X.HHH HHH LLLL LLLL LLLL LLLL LL

for i in range(25):
    print("O"+str(i),end=",")

for i in range(2**6):
    lut_s.append(Fxp(math.sin(i*2*math.pi/(2**6)), signed=True, n_word=18+25+1, n_frac=18+25))
    lut_c.append(Fxp(math.cos(i*2*math.pi/(2**6)), signed=True, n_word=25+1, n_frac=16))

print(math.cos(0*2*math.pi/(2**6)))
for input, c in enumerate(lut_s):
    print(Fxp(input, signed=False, n_word=6).bin(),end="")
    print(c.bin())
print(lut_c[32])


n = int(input())
rows = []

for i in range(n):
    row = list(map(int, input().split()))
    rows.append(row)

destroyed = 0
attacks = input().split()

for attack in attacks:
    attack = attack.split("-")
    index_of_row = int(attack[0])
    index_of_element = int(attack[1])

    for row in rows:
        for ind in row:
            if rows.index(row) == index_of_row and row.index(ind) == index_of_element:
                if row[ind] > 0:
                    row[ind] -= 1
                    if row[ind] <= 0:
                        destroyed += 1

print(destroyed)

Fundamentals with Python/T07 - Lists Basics/moreExercise/04. Battle Ships.py


# Given a binary tree, flatten it to a linked list in -place.

# For example, given the following tree:

#     1
#    / \
#   2   5
#  / \   \
# 3   4   6
# The flattened tree should look like:

# 1
#  \
#   2
#    \
#     3
#      \
#       4
#        \
#         5
#          \
#           6

# 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 flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return None

        stack = [root]

        while stack:
            curr = stack.pop()

            if curr.right:
                stack.append(curr.right)
            if curr.left:
                stack.append(curr.left)

            if stack:
                curr.right = stack[-1]

            curr.left = None

"""
    create stack with root in stack

    traverse through the tree inorder (append right, append left)

    if there's anything in the stack, then set curr.right to last element in stack

    set curr.left to None

"""


# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5QSEhaA5sDFAUq
import sys
sys.stdin = open('input.txt')

# Test Case 개수
T = int(input())

for tc in range(1, T+1):
    total = 0
    numbers = list(map(int, input().split()))
    for num in numbers:
        if num % 2:
            total += num

    print(f'#{tc} {total}')


import time
import torch
import torch.utils.data
import torch.optim as optim
from loss import *
from torch.autograd import Variable
from model import model
from Evaluation import evaluation
from torchvision import transforms
from sklearn.datasets import fetch_lfw_people
from utils import GenIdx,IdentitySampler, prepare_dataset, prepare_set, \
                    prepare_data_ids,LFW_training_Data
import numpy as np

#### Fonction utiles ####

# Fonction d'entraînement
def train(epoch, criterion, optimizer, trainloader, device, net):

    """

    Se réferer éventuellement au laboratoire 5
    On pensera à mettre les données sur 3 canaux au lieux de 1 via expand :
    https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html

    """

# Fonction permettant la validation
def valid(query_gall_loader, query_gallery_labels):

    # Extraire les features pour chaque image de la base de données
    query_gall_feat_pool, query_gall_feat = extract_query_gall_feat(query_gall_loader, n_query_gall, net, test_batch_size)

    # Compute the similarity matrix based on the extracted features matrix:
    similarity_matrix_pool = "A définir"
    similarity_matrix_feat = "A définir"

    # Evaluation - Compute metrics (Rank-1, Rank-5, mAP)
    cmc_att, mAP_att  = evaluation(-similarity_matrix_pool, query_gallery_labels)
    cmc, mAP = evaluation(-similarity_matrix_feat, query_gallery_labels)

    return cmc, mAP, cmc_att, mAP_att

#
def extract_query_gall_feat(query_gall_loader, ngall, net, batch_size):
    """
    Fonction d'extraction des caractéristiques et création d'une matrice contenant sur chaque ligne
    le vecteur caractéristique d'une image.

    Deux matrices sont en fait produites :
        - L'une à partir du vecteur caractéristique produit après la couche average pooling
        - L'autre à partir du vecteur caractéristique produit après la couche batch normalization

    Dans la pratique, il est parfois plus intéressant de regarder les résultats de l'une ou de l'autre, donc
    on testera les deux.

    """
    net.eval()
    print('Extracting Gallery Feature...')
    # start = time.time()
    ptr = 0
    feat_size = 512
    gall_feat_pool = np.zeros((ngall, feat_size))
    gall_feat = np.zeros((ngall, feat_size))

    with torch.no_grad():
        # Boucle itérant sur chaque batch de validation à définir ici
        for A_definir in "A définir":
            feat_pool, feat = "A définir" # Extraire features pour chaque batch

        gall_feat_pool[ptr:ptr + batch_size, :] = feat_pool.detach().cpu().numpy()
        gall_feat[ptr:ptr + batch_size, :] = feat.detach().cpu().numpy()
        ptr = ptr + batch_size

    return gall_feat_pool, gall_feat

if __name__ == "__main__":

    # Work on GPU if available
    device = 'cuda' if torch.cuda.is_available() else 'cpu'

    # Import the lfw dataset - With 15 img min per person
    print("===> Loading Fetch Dataset \n")
    lfw_people = fetch_lfw_people(min_faces_per_person=15, resize=0.4)
    nb_img_per_id_to_keep = 15

    # Renvoie la base de données avec 15 images par personnes maximum
    # Vous devrez coder la fonction dans le fichier utils
    X, y, n_classes = prepare_dataset(lfw_people, nb_img_per_id_to_keep)

    # Produire les listes d'identités qui correspondront aux folds d'entraînement / validation et
    # aux identités de test.
    # train_ids_lists et val_ids_lists seront des listes de 5 listes d'identités (Une liste pour chaque fold)
    # test_ids sera une liste de 21 identités
    train_ids_lists, val_ids_lists, test_ids = prepare_data_ids(n_classes)

    # Prepare var - Batch size - On utilise 4 images par identités et 8 identités par batch (=> 32 imgs)
    num_img_of_same_id_in_batch = 4
    num_different_identities_in_batch = 8
    batch_size = num_img_of_same_id_in_batch * num_different_identities_in_batch # batch_size = 32
    test_batch_size = 32

    global_img_pos = GenIdx(y)  # Get the images positions in list for each specific identity

    folds = "A définir"  # Number of fold K for cross-validation
    epochs = "A définir" # Number of epochs

    # Augmentation de la taille des images
    img_h, img_w = 288, 144

    # Préparation des transformations appliquées aux images pour l'entraînement ou le reste (validation / test)
    transform_train = transforms.Compose([
        transforms.ToPILImage(),
        transforms.Resize((img_h, img_w)),
        transforms.Pad(10),
        transforms.RandomCrop((img_h, img_w)),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
    ])

    transform_test = transforms.Compose([
        transforms.ToPILImage(),
        transforms.Resize((img_h, img_w)),
        transforms.ToTensor(),
    ])

    # Définir votre ou vos fonctions de pertes
    # Vous pouvez définir votre/vos fonction de pertes dans le fichier loss.py
    criterion_1 = "A définir"

    for fold in range(folds):
        net = model(n_classes).to(device)

        # Définir votre optimizer :
        opt = "A définir"

        # Préparation du query / gallery set pour la validation
        # A noter que query set = gallery set si on compte comparer chaque image de la base avec toute les autres
        query_gall_set, n_query_gall = prepare_set(X, global_img_pos, val_ids_lists[fold], transform=transform_test)
        query_gall_loader = torch.utils.data.DataLoader(query_gall_set, batch_size=test_batch_size, shuffle=False)

        best_map = 0
        for epoch in range(epochs):

            trainset = LFW_training_Data(X, global_img_pos, train_ids_lists[fold], transform=transform_train)

            img_pos = GenIdx(trainset.train_labels)  # Get the images positions in list for each specific identity

            # Permet de sampler la base de données par batch contenant le bon nombre d'identités et d'images par identités
            sampler = IdentitySampler(trainset.train_labels, img_pos, num_img_of_same_id_in_batch,
                                      num_different_identities_in_batch)

            trainset.cIndex = sampler.index

            trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, \
                                                      sampler=sampler, drop_last=True)

            train(epoch, criterion_1, opt, trainloader, device, net)

            # Call the validation every two epochs
            if epoch != 0 and epoch % 2 == 0:
                cmc, mAP, cmc_att, mAP_att = valid(query_gall_loader, query_gall_set.val_test_label)

                # Save model based on validation mAP
                if mAP > best_map:  # Usual saving

                    best_map = mAP
                    best_epoch = epoch
                    state = {
                        'net': net.state_dict(),
                        'cmc': cmc,
                        'mAP': mAP,
                        'epoch': epoch,
                    }
                    torch.save(state, f'model_fold({fold})_best.t')

                print('fc : Rank-1: {:.2%} | Rank-5: {:.2%} | mAP: {:.2%}'.format(cmc[0], cmc[4], mAP ))
                print('att : Rank-1: {:.2%} | Rank-5: {:.2%} | mAP: {:.2%}'.format(cmc_att[0], cmc_att[4], mAP_att))

    # Tester ici ou dans un fichier à part votre modèle sur les données de test.


import re
import datetime
import csv
from os import getcwd
from os import listdir
from os.path import isfile, join

def check(files_list):
    if type(files_list) != list:
        return 1
    if len(files_list) < 2:
        return 1
    for file in files_list:
        if type(file) != str:
            return 1
    return 0

def script(files_list):
    if check(files_list):
        raise Exception

    with open("report.csv", "w") as report:
        csv_report = csv.writer(report, delimiter=';')

        csv_report.writerow(["company", "metric_id", "metric_desc", "metric_value", "metric_date", "generation_date"])

        for file_string in files_list:
            f = open(file_string, "r")
            csv_list = list(csv.reader(f, delimiter=';'))

            for row in csv_list[1:]:
                row.append(str(datetime.date.today()))
                csv_report.writerow(row)
            f.close()
    report.close()

if __name__ == "__main__":
    cwd = getcwd()
    files_list = [
        f for f in listdir(cwd) if (isfile(join(cwd, f)) and re.fullmatch("^data_[0-9]{4}-[0-9]{2}-[0-9]{2}\.csv$", f))
    ]
    files_list.sort()
    script(files_list)


# 494. 目标和
"""
给定一个非负整数数组，a1, a2, ..., an, 和一个目标数，S。现在你有两个符号 + 和 -。对于数组中的任意一个整数，你都可以从 + 或 -中选择一个符号添加在前面。

返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

示例 1:

输入: nums: [1, 1, 1, 1, 1], S: 3
输出: 5
解释:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

一共有5种方法让最终目标和为3。
"""
import json

class Solution:

    def findTargetSumWays(self, nums: list, S: int) -> int:
        # 方法一 递归法 + 备忘录
        memo = {}
        res = self.helper(0, 0, nums, S, 0, memo)
        return res

    def helper(self, index, sum, nums, target, res, memo):
        if (index, sum) in memo.keys():
            return memo[(index, sum)]
        if index == len(nums):
            if sum == target:
                res += 1
        else:
            res = self.helper(index+1, sum+nums[index], nums, target, res, memo) + self.helper(index+1, sum-nums[index], nums, target, res, memo)
        memo[(index, sum)] = res
        return res

    # 动态规划
    def findTargetSumWays2(self, nums: list, S: int) -> int:
        dp = [[0 for _ in range(S)] for _ in range(len(nums)+1)]
        dp[0][0] = 0
        for i in range(1, len(nums)+1):
            for j in range(S):
                dp[i][j] = dp[i-1][j+nums[i]] + dp[i-1][j-nums[i]]
        return dp[-1][-1]

def stringToIntegerList(input):
    return json.loads(input)

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            nums = stringToIntegerList(line);
            line = next(lines)
            S = int(line);

            ret = Solution().findTargetSumWays(nums, S)

            out = str(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()


from confiDB import Database

def verificarRegistrosSinProveedor():
    database = Database()
    cursor = database.connection.cursor()

    # Obtener los RUTs de la tabla "registro"
    sql_registro = "SELECT DISTINCT rutempresa FROM registro"
    cursor.execute(sql_registro)
    ruts_registro = [row[0] for row in cursor.fetchall()]

    count_ruts_sin_proveedor = 0
    count_ruts_pendientes = 0

    # Verificar cada RUT en la tabla "proveedores"
    for rut in ruts_registro:
        sql_proveedores = "SELECT COUNT(*) FROM proveedores WHERE rutempresa = %s"
        cursor.execute(sql_proveedores, (rut,))
        count_proveedores = cursor.fetchone()[0]

        if count_proveedores == 0:
            count_ruts_sin_proveedor += 1
        else:
            count_ruts_pendientes += 1

    return count_ruts_sin_proveedor


from fbs_runtime.application_context import ApplicationContext
from PyQt5.QtWidgets import (QMainWindow, QMessageBox)
from PyQt5.QtCore import (QThread, pyqtSignal)
from PyQt5.QtGui import (QIcon)
from decimal import Decimal, ROUND_FLOOR
from logger import log
from pprint import pprint
from steam import steam
from math import ceil, floor
from gui import (mainwindow, resources)

import urllib.request
import qdarkstyle
import subprocess
import webbrowser
import speedtest
import win32api
import ctypes
import psutil
import xerox
import time
import yaml
import sys
import os

VERSION = "1.0.0"

launchOptions = [
    "-novid", "-nojoy", "-nosteamcontroller", "-softparticlesdefaultoff",
    "-reuse", "-nohltv"
]

dxlevels = ["80", "81", "90", "92", "95 (default)", "98"]

def is_admin():
  try:
    return ctypes.windll.shell32.IsUserAnAdmin()
  except:
    return False

class SpeedTest(QThread):
  signal = pyqtSignal("PyQt_PyObject")

  def __init__(self):
    QThread.__init__(self)

  def run(self):
    s = speedtest.Speedtest()
    s.get_best_server()
    s.download()
    s.upload()
    s.results.share()

    results_dict = s.results.dict()
    # results_dict = {"download": 0, "upload": 0}
    log.debug(results_dict)
    self.signal.emit(results_dict)

class App(QMainWindow):

  def __init__(self, parent=None):
    super(App, self).__init__(parent)
    self.ui = mainwindow.Ui_MainWindow()
    self.ui.setupUi(self)
    self.setWindowTitle("configuraTed v{v}".format(v=VERSION))
    self.ui.nextButton.clicked.connect(self.onNextClick)
    self.ui.prevButton.clicked.connect(self.onPrevClick)
    self.ui.autoRefreshRate.clicked.connect(self.getRefreshRate)
    self.ui.copyBackupPath.clicked.connect(self.copyBackupPath)
    self.ui.copyConfiguratedPath.clicked.connect(self.copyConfiguratedPath)
    self.ui.toggleRefreshRate.stateChanged.connect(self.onToggleRefreshRate)
    self.ui.refreshConnectionSpeed.clicked.connect(self.getConnectionSpeed)
    self.ui.refreshConnectionSpeed.setIcon(QIcon(":/icons/icons/refresh.png"))
    self.toggleButton(self.ui.nextButton, "show")
    self.toggleButton(self.ui.prevButton, "hide")
    self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())

    self.custom = ""
    self.configs = {}
    self.backupPath = ""
    log.debug("loading configs.yml")
    try:
      with open("configs.yml", encoding="utf8") as f:
        self.configs = yaml.safe_load(f)
    except Exception as e:
      msg = "Error while trying to get configs.yml: %s" % e
      log.error(msg, exc_info=True)
      QMessageBox.critical(self, "Error", msg)
    log.debug("configs.yml loaded")

    self.ui.configList.addItem("TF2's Default")

    for id, cfg in self.configs["list"].items():
      log.debug("%s = %s" % (id, cfg))
      self.ui.configList.addItem(cfg["name"])

    self.ui.configList.setCurrentIndex(5)

    for dxl in dxlevels:
      self.ui.dxlevelList.addItem(dxl)

    self.ui.connectionType.addItem("Cable")
    self.ui.connectionType.addItem("Wifi")
    self.ui.connectionType.addItem("Mobile")

    self.ui.dxlevelList.setCurrentIndex(4)
    self.ui.pages.setCurrentIndex(0)
    self.shouldTestConnection = True
    self.getRefreshRate()

  def openBackupPath(self):
    subprocess.Popen("explorer /select, \"%s\"" % self.backupPath)

  def openConfiguratedPath(self):
    subprocess.Popen("explorer /select, \"%s\"" % self.configuratedPath)

  def copyBackupPath(self):
    xerox.copy(self.backupPath)

  def copyConfiguratedPath(self):
    xerox.copy(self.configuratedPath)

  def getRefreshRate(self):
    log.debug("getting refresh rate...")
    try:
      displayfrequency = getattr(
          win32api.EnumDisplaySettings(win32api.EnumDisplayDevices().DeviceName,
                                       -1), 'DisplayFrequency')
      self.ui.refreshRate.setText(str(displayfrequency))
      log.debug("refresh rate: %s" % displayfrequency)
    except Exception as e:
      msg = "Error while trying to get the refresh rate: %s" % e
      log.error(msg, exc_info=True)
      QMessageBox.critical(self, "Error", msg)

  def onToggleRefreshRate(self):
    self.ui.refreshRate.setDisabled(self.ui.toggleRefreshRate.isChecked())

  def clamp(self, actual, mi, ma):
    return max(min(actual, ma), mi)

  def onSpeedTestDone(self, data):
    self.shouldTestConnection = False
    self.ui.statusbar.showMessage("Done, click next to continue.")
    log.debug("done: %s" % data)
    self.toggleButton(self.ui.nextButton, "show")
    self.ui.refreshConnectionSpeed.setEnabled(True)

    d = str(data["download"] / 1000000)
    d = d[0:d.index(".") + 2]

    u = str(data["upload"] / 1000000)
    u = u[0:u.index(".") + 2]
    self.ui.connectionSpeed.setText("{down} Down / {up} Up (Mbps)".format(
        down=d, up=u))

    speed = min(float(d), float(u))

    # rate
    rate = float(speed * 125000)
    rate = self.clamp(rate, 40000, 324192)
    self.custom_net = "\nrate " + str(rate)

    # net split
    net_split = float(speed * 125000)
    net_split = self.clamp(net_split, 3500, 324192)
    self.custom_net += "\nnet_splitpacket_maxrate " + str(net_split)

    # net clear
    self.custom_net += "\nnet_maxcleartime " + str(
        max(4000 / 786432, 4000 / (float(u) * 125000)))
    log.debug(self.custom_net)

  def toggleButton(self, btn, state):
    if state == "hide":
      btn.setStyleSheet(
          "background-color: rgba(0, 0, 0, 0); color: rgba(0, 0, 0, 0);")
      btn.setEnabled(False)
    else:
      btn.setStyleSheet("")
      btn.setEnabled(True)

  def getConnectionSpeed(self):
    try:
      self.st = SpeedTest()
      self.st.signal.connect(self.onSpeedTestDone)
      self.st.start()
      self.ui.statusbar.showMessage("Testing connection speed...")
      self.toggleButton(self.ui.nextButton, "hide")
      self.ui.refreshConnectionSpeed.setEnabled(False)
    except:
      e = sys.exc_info()[0]
      log.error("Error while trying to get the connection speed: %s" % e)
      QMessageBox.critical(self, "Error", "%s" % e)

  def onNextClick(self):
    log.debug("next")
    c = self.ui.pages.currentIndex()
    if c == 0 and self.shouldTestConnection:
      self.getConnectionSpeed()
      return
    elif c == 3:
      self.Install()

    self.ui.pages.setCurrentIndex(c + 1)
    self.toggleButton(self.ui.prevButton, "show")

    if (c + 1) == 3:
      self.ui.nextButton.setText("Install")
    else:
      self.ui.nextButton.setText("Next")

  def onPrevClick(self):
    log.debug("prev")
    c = self.ui.pages.currentIndex()
    if c > 0:
      self.ui.pages.setCurrentIndex(c - 1)
      if c - 1 == 0:
        self.ui.prevButton.setEnabled(False)

      self.ui.nextButton.setText("Next")

  def Install(self):
    log.debug("install")
    self.toggleButton(self.ui.prevButton, "hide")
    self.toggleButton(self.ui.nextButton, "hide")

    buttonReply = QMessageBox.question(
        self, "Confirmation", "Do you wanna proceed with the installation?",
        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
    if buttonReply == QMessageBox.No:
      return

    self.ui.statusbar.showMessage("Installing...")
    shouldReset = self.ui.resetBox.isChecked()
    shouldLaunch = self.ui.launchBox.isChecked()
    dxlevel = self.ui.dxlevelList.currentText()
    cfg = self.ui.configList.currentText()

    try:
      if shouldReset:
        self.ui.statusbar.showMessage("Reset TF2: finding steam's path...")
        self.errorMessage = "steam.findGame()"
        steam.findGame()

        self.ui.statusbar.showMessage("Reset TF2: backing up user's config...")
        self.errorMessage = "steam.backupUserConfig()"
        self.backupPath = steam.backupUserConfig()

        self.ui.statusbar.showMessage(
            "Reset TF2: disabling steam's cloud for tf2...")
        self.errorMessage = "steam.disableCloud()"
        steam.disableCloud()

        self.ui.statusbar.showMessage("Reset TF2: validating tf2's files...")
        self.errorMessage = "steam.validateGameFiles()"
        steam.validateGameFiles()

        self.ui.statusbar.showMessage(
            "Reset TF2: generating tf2's default config...")
        self.errorMessage = "steam.autoConfig()"
        steam.autoConfig()

        time.sleep(4)

      if shouldLaunch or dxlevel[0:2] != "95":
        self.ui.statusbar.showMessage(
            "Setting tf2's dxlevel to {dxlevel}...".format(dxlevel=dxlevel))
        self.errorMessage = "steam.autoConfig set_dxlevel"
        steam.autoConfig(mode="set_dxlevel", dxlevel=dxlevel[0:2])

        self.ui.statusbar.showMessage(
            "Setting tf2's launch options".format(dxlevel=dxlevel))
        launchOptions.append("-freq " + self.ui.refreshRate.text())
        self.errorMessage = "steam.setLaunchOptions()"
        steam.setLaunchOptions(launchOptions)

      self.ui.statusbar.showMessage("Installing config: {cfg}".format(cfg=cfg))
      self.errorMessage = "installConfig()"
      self.installConfig()

      self.ui.backupPath.setText(self.backupPath)
      self.ui.statusbar.showMessage("Done, you can play tf2 now.")
      self.ui.pages.setCurrentIndex(self.ui.pages.currentIndex() + 1)
    except Exception as e:
      msg = "%s: %s" % (self.errorMessage, e)
      log.error(msg, exc_info=True)
      QMessageBox.critical(self, "Error", msg)

  def installConfig(self):
    log.debug("installing config")
    current = self.ui.configList.currentText()
    if current == "TF2's Default":
      self.configuratedPath = steam.findGame() + "cfg\\"
      return

    cfg = {}
    for _id, c in self.configs["list"].items():
      if c["name"] == current:
        cfg = c
        break

    customPath = steam.findGame() + "custom\\"
    self.configuratedPath = customPath + "configurated\\"

    log.debug("downloading cfg")
    ndir = self.configuratedPath + "cfg\\"
    log.debug("making dirs: %s" % ndir)
    os.makedirs(ndir, exist_ok=True)

    # when type is autoexec it downloads directly to: tf/custom/configurated/
    if cfg["type"] == "autoexec":
      urllib.request.urlretrieve(cfg["url"] + cfg["file"], ndir + cfg["file"])
    else:
      urllib.request.urlretrieve(cfg["url"] + cfg["file"],
                                 customPath + cfg["file"])

    customPath = self.configuratedPath
    self.ui.configuratedPath.setText(customPath)

    if "mastercomfig" in cfg["name"].lower():
      log.debug(
          "cfg is mastercomfig, creating cfg's custom files at tf/custom/configurated/cfg"
      )
      files = [
          "custom", "scout", "soldier", "demoman", "engineer", "heavyweapons",
          "medic", "pyro", "sniper", "spy", "game_overrides", "listenserver"
      ]

      if not ("experimental" in cfg["name"].lower()):
        log.debug("adding _c to cfg file names")
        for i in range(len(files)):
          if files[i] != "custom":
            files[i] = files[i] + "_c"

      for name in files:
        open(customPath + "cfg\\" + name + ".cfg", "w", encoding="utf8").close()

      f = open(customPath + "cfg\\" + "custom.cfg", "w", encoding="utf8")
      f.write(self.custom + self.custom_net)
      f.close()

if __name__ == "__main__":
  appctxt = ApplicationContext()  # 1. Instantiate ApplicationContext
  window = App()
  window.show()
  exit_code = appctxt.app.exec_()  # 2. Invoke appctxt.app.exec_()
  sys.exit(exit_code)


#!/usr/bin/python3
# -*- encoding:utf-8 -*-

import socket
import time
import threading

def startSock():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((socket.gethostname(), 9000))

    print(s.recv(1024).decode('utf-8'))

    for data in [b'A', b'B', b'C', b'D', b'E', b'F', b'G', b'H']:
        s.send(data)
        print(s.recv(1024).decode('utf-8'))

    # time.sleep(1)
    s.send(b'exit')
    s.close()

for i in range(1000):
    t = threading.Thread(target=startSock)
    # time.sleep(1)
    t.start()
    # t.join()


import os

def create_main_dir(dir_name):
    try:
        os.mkdir(dir_name)
    except FileExistsError as er:
        print(f'dir exists: {er.filename}')
    return 0

def create_child_dirs(parent, *dirs):
    for el in dirs:
        try:
            dir_path = os.path.join(parent, el)
            os.mkdir(dir_path)
        except FileExistsError as er:
            print(f'dir exists: {er.filename}')
        return 0

def create_starter(main_dir):
    create_main_dir(main_dir)
    create_child_dirs('settings', 'mainapp', 'adminapp', 'authapp')

if __name__ == '__main__':
    create_starter('my_project')


#! /usr/bin/env python
# vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 filetype=python :
top = '../..'

def build(self):
    if "LIB_SDL" in self.env:
        self(
            target          = 'ahbdisplay',
            features        = 'cxx cxxstlib',
            source          = 'ahbdisplay.cpp yuv_viewer.cpp',
            export_includes = ['.',self.top_dir,self.repository_root.abspath()],
            includes        = ['.',self.top_dir,self.repository_root.abspath()],
            use             = 'sr_signal common BOOST SYSTEMC TLM AMBA GREENSOCS SDL',
            install_path    = '${PREFIX}/lib',
        )


#!/usr/local/bin/python3

import pdb
import json
import datetime
import sys
import zeep
import copy

from lxml import etree
from zeep import Plugin

ZUORA_CHUNKSIZE = 50

class MyLoggingPlugin(Plugin):
    def ingress(self, envelope, http_headers, operation):
        print(etree.tostring(envelope, pretty_print=True))
        return envelope, http_headers

    def egress(self, envelope, http_headers, operation, binding_options):
        print(etree.tostring(envelope, pretty_print=True))
        return envelope, http_headers

zeepPlugins =[
    # MyLoggingPlugin()
]

class Zuora():
    def __init__(self, config):
        if isinstance(config, dict):
            self.config = config
        else:
            configfile = open(config)
            self.config = json.load(configfile)

        self.client = zeep.Client(wsdl=self.config['wsdl'])
        # self.client = zeep.Client(wsdl=self.config['wsdl'], plugins=zeepPlugins)

        response = self.client.service.login(self.config['user'], self.config['password'])
        sessionid = response.Session

        sessionheader_cls = self.client.get_element('ns1:SessionHeader')
        self.sessionheader = sessionheader_cls(session=sessionid)

        self.batchSize = 2000
        self.caseSensitive = False

    def query(self, query):
        queryoptions_cls = self.elementFactory('QueryOptions')
        queryoptions = queryoptions_cls(batchSize=self.batchSize, caseSensitive=self.caseSensitive)

        query_response = self.client.service.query(
                        queryString=query,
                        _soapheaders={'QueryOptions': queryoptions, 'SessionHeader': self.sessionheader})
        return query_response

    def typeFactory(self, type, ns='ns0'):
        return self.client.get_type(ns + ':' + type)

    def elementFactory(self, element, ns='ns1'):
        return self.client.get_element(ns + ':' + element)

    # wsdl:
    # create(zObjects: zObject[], _soapheaders={CallOptions: CallOptions(), SessionHeader: SessionHeader()})
    # -> Errors: Error[], Id: xsd:ID, Success: xsd:boolean

    def create(self, records):
        saveResults = []

        calloptions_cls = self.elementFactory('CallOptions')
        calloptions = calloptions_cls(useSingleTransaction=False)

        chunks = [records[i:i + ZUORA_CHUNKSIZE] for i in range(0, len(records), ZUORA_CHUNKSIZE)]

        # For some reason, the create service mangles the records passed into it
        # We work around that by using deepcopy
        for chunk in chunks:
            saveResults += self.client.service.create(
                                zObjects=copy.deepcopy(chunk),
                                    _soapheaders={'CallOptions': calloptions, 'SessionHeader': self.sessionheader})
        return saveResults

    # wsdl:
    # subscribe(subscribes: SubscribeRequest[], _soapheaders={SessionHeader: SessionHeader()}) -> AccountId: xsd:ID,
    # AccountNumber: xsd:string, ChargeMetricsData: ChargeMetricsData, Errors: Error[], GatewayResponse: xsd:string,
    # GatewayResponseCode: xsd:string, InvoiceData: InvoiceData[], InvoiceId: xsd:ID, InvoiceNumber: xsd:string,
    # InvoiceResult: InvoiceResult, PaymentId: xsd:ID, PaymentTransactionNumber: xsd:string, SubscriptionId: xsd:ID,
    # SubscriptionNumber: xsd:string, Success: xsd:boolean, TotalMrr: xsd:decimal, TotalTcv: xsd:decimal

    def subscribe(self, subscribeRequests):
        subscribeResults = []

        for chunk in [subscribeRequests[i:i + ZUORA_CHUNKSIZE] for i in range(0, len(subscribeRequests), ZUORA_CHUNKSIZE)]:
            results = self.client.service.subscribe(
                                subscribes=chunk,
                                _soapheaders={'SessionHeader': self.sessionheader})
            subscribeResults += results
        return subscribeResults

    def amend(self, amendRequest):
        return self.client.service.amend(
                                requests=amendRequest,
                                _soapheaders={'SessionHeader': self.sessionheader})

    # wsdl:
    # delete(type: xsd:string, ids: xsd:ID[], _soapheaders={SessionHeader: SessionHeader()})
    # -> errors: Error[], id: xsd:ID, success: xsd:boolean
    #
    # 50 objects are supported in a single call.
    # 1,000 calls are supported per 10-minute time window per tenant

    def delete(self, type, ids):
        assert len(ids) <= 50
        response = self.client.service.delete(
                type=type,
                ids=ids,
                _soapheaders={'SessionHeader': self.sessionheader})
        return response

    def updateRecords(self, records):
        saveResults = []
        for chunk in [records[i:i + ZUORA_CHUNKSIZE] for i in range(0, len(records), ZUORA_CHUNKSIZE)]:
            saveResults += self.client.service.update(
                        zObjects=chunk,
                        _soapheaders={'SessionHeader': self.sessionheader})
        return saveResults

    # generate(zObjects: zObject[], _soapheaders={SessionHeader: SessionHeader()}) -> Errors: Error[], Id: xsd:ID, Success: xsd:boolean
    # https://knowledgecenter.zuora.com/DC_Developers/SOAP_API/E_SOAP_API_Calls/generate_call
    def generate(self, invoices):
        results = []
        chunks = [invoices[i:i + ZUORA_CHUNKSIZE] for i in range(0, len(invoices), ZUORA_CHUNKSIZE)]
        for chunk in chunks:
            results += self.client.service.generate(
                    zObjects=chunk,
                    _soapheaders={'SessionHeader': self.sessionheader})

        return results


import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

from .plotting_disease import setup_x_axis

mpl.rcParams['xtick.major.pad'] = '8'
mpl.rcParams['ytick.major.pad'] = '8'

try:
    import brewer2mpl as brew

    colors = ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69']
    #colors = brew.get_map('Pastel2', 'qualitative', 7).mpl_colors
    #colors = ['k'] + brew.get_map('Pastel2', 'qualitative', 7).mpl_colors
    #colors[6] = 'c' # replace invisible yellow
    rb_colors = ['k'] + brew.get_map('YlOrRd', 'sequential', 9).mpl_colors
except ImportError:
    colors = ['k', 'r', 'b', 'g', 'm', 'c', '0.5']

## -------------------------------------------------------------------------------------------
## from http://www.sron.nl/~pault/
## -------------------------------------------------------------------------------------------

# colour table in HTML hex format
hexcols = ['#332288', '#88CCEE', '#44AA99', '#117733', '#999933', '#DDCC77',
           '#CC6677', '#882255', '#AA4499', '#661100', '#6699CC', '#AA4466',
           '#4477AA']

greysafecols = ['#809BC8', '#FF6666', '#FFCC66', '#64C204']

xarr = [[12],
        [12, 6],
        [12, 6, 5],
        [12, 6, 5, 3],
        [0, 1, 3, 5, 6],
        [0, 1, 3, 5, 6, 8],
        [0, 1, 2, 3, 5, 6, 8],
        [0, 1, 2, 3, 4, 5, 6, 8],
        [0, 1, 2, 3, 4, 5, 6, 7, 8],
        [0, 1, 2, 3, 4, 5, 9, 6, 7, 8],
        [0, 10, 1, 2, 3, 4, 5, 9, 6, 7, 8],
        [0, 10, 1, 2, 3, 4, 5, 9, 6, 11, 7, 8]]

# get specified nr of distinct colours in HTML hex format.
# in: nr - number of colours [1..12]
# returns: list of distinct colours in HTML hex
def get_distinct(nr, bw=False, br=False):
    # check if nr is in correct range

    if nr <= 2 and bw:
        return ['#333333', '#AAAAAA']

    if nr <= 2 and br:
        print("BBBBBBB")
        return ['#FFFFFF', '#FF0000']

#    if nr <= 2 and br:
#        return ['#333333', '#CC6677']

    if nr < 1 or nr > 12:
        print("wrong nr of distinct colours!")
        return
    # get list of indices
    lst = xarr[nr - 1]
    # generate colour list by stepping through indices and looking them up
    # in the colour table
    i_col = 0
    col = [0] * nr
    for idx in lst:
        col[i_col] = hexcols[idx]
        i_col += 1
    return col

## -------------------------------------------------------------------------------------------

# ideally this should be expanded, and be settable by main.py
class lp(object):
    lw = 1
    fs = 16 # 16 is very big (John thinks 12 looks better)

def plot_lines(ax, x_values, y_values, x_label, y_label, y_errs=None, series_labels=None, legend_title=None,
               legend_loc='upper left', linestyle='-', lineweight=None, bw=False, br=False, reversed=False, xmin=None):
    """
    Plotting function for lines, with or without error bars.
    """

    # if data values submitted as a single series, wrap in list
    if not (isinstance(y_values[0], list)
            or isinstance(y_values[0], np.ndarray)
            or isinstance(y_values[0], tuple)):
        y_values = [y_values]

    #print len(x_values), len(y_values[0])
    assert len(x_values) == len(y_values[0])

    if len(y_values) <= 12:
        loc_colors = get_distinct(len(y_values), bw, br)
    else:
        # get max number of colours
        loc_colors = get_distinct(12)

    # same with error values
    if y_errs is not None and (not isinstance(y_errs[0], (list, np.ndarray, tuple))):
        y_errs = [y_errs]

    # expand y_errs and series_labels if not present
    if not y_errs:
        y_errs = [None] * len(y_values)
    if not series_labels:
        series_labels = [None] * len(y_values)

    if reversed:
        y_values.reverse()
        loc_colors.reverse()

    # plot lines
    for i, (cur_values, cur_errs, cur_label) in enumerate(zip(y_values, y_errs, series_labels)):
        #print bw, cur_label, loc_colors[i]
        if cur_errs is not None:
            ax.errorbar(x_values, cur_values, yerr=cur_errs, label=cur_label, color=loc_colors[i],
                        lw=lp.lw if not lineweight else lineweight, ls=linestyle)
        else:
            #print len(x_values), len(cur_values)
            ax.plot(x_values, cur_values, label=cur_label, color=loc_colors[i % len(loc_colors)],
                    lw=lp.lw if not lineweight else lineweight, ls=linestyle)

    # set labels and legend
    ax.set_xlabel(x_label, fontsize=lp.fs)
    ax.set_ylabel(y_label, fontsize=lp.fs)

    if xmin is not None:
        ax.set_xlim(xmin=xmin)

    if series_labels[0]:
        leg = ax.legend(scatterpoints=1, numpoints=1, ncol=2,
                        title=legend_title, labelspacing=0.1, columnspacing=1,
                        loc=legend_loc)
        plt.setp(leg.get_texts(), fontsize='small')
        leg.get_frame().set_alpha(0.0)

    plt.setp(ax.get_xticklabels(), fontsize=lp.fs)
    plt.setp(ax.get_yticklabels(), fontsize=lp.fs)

def plot_points_lin_reg(ax, times, y_values, x_label, y_label, series_labels=None, y_min=None, y_max=None,
                        x_offset=None, align=None,
                        legend_title=None, legend_loc='upper left', plot_title=None, bw=False):
    """
    Plot a set of data points together with a line of best fit.
    """
    if not (isinstance(y_values[0], (list, np.ndarray, tuple))):
        y_values = [y_values]

    if not series_labels:
        series_labels = [None] * len(y_values)

    loc_colors = get_distinct(len(y_values), bw)

    if align == 'centre':
        offset = (times['et'] - times['st']) / (len(y_values[0]) + 1) / 2.0
        #print times['st'], times['et'], offset
        x_values = np.linspace(times['st'] + offset, times['et'] - offset, len(y_values[0])) / times['t_per_year']
        #print xvals
    else:
        x_values = np.linspace(times['st'], times['et'], len(y_values[0])) / times['t_per_year']
        #x_values = np.linspace(times['st'], times['et'], len(y_values[0])) / times['t_per_year']

    for i, (cur_values, cur_label) in enumerate(zip(y_values, series_labels)):
        p = np.polyfit(x_values[~np.isnan(cur_values)], cur_values[~np.isnan(cur_values)], 1)
        #print cur_values
        ax.plot(x_values, cur_values, color=loc_colors[i], marker='x', lw=0)
        ax.plot(x_values, p[0] * x_values + p[1], label=cur_label, color=loc_colors[i], linestyle='-', lw=lp.lw)

    if plot_title:
        ax.set_title(plot_title, fontsize=lp.fs)
    ax.set_xlabel(x_label, fontsize=lp.fs)
    ax.set_ylabel(y_label, fontsize=lp.fs)
    ncol = 2 if len(y_values) > 5 else 1
    if series_labels[0]:
        leg = ax.legend(scatterpoints=1, numpoints=1, ncol=ncol, title=legend_title, labelspacing=0.1, columnspacing=1,
                        loc=legend_loc)
        plt.setp(leg.get_texts(), fontsize='small')
        leg.get_frame().set_alpha(0.0)

    if y_min is not None:
        ax.set_ylim(ymin=y_min)
    if y_max is not None:
        ax.set_ylim(ymax=y_max)

    plt.setp(ax.get_xticklabels(), fontsize=lp.fs)
    plt.setp(ax.get_yticklabels(), fontsize=lp.fs)

    setup_x_axis(ax, times, x_offset, set_xlim=False)

def plot_stacked_area(ax, x_values, y_values, x_label, y_label, series_labels=None,
                      legend_title=None, plot_title=None, bw=False):
    if not series_labels:
        series_labels = [None] * len(y_values)

    #print series_labels

    p = []

    colors = get_distinct(len(y_values), bw)

    ax.fill_between(x_values, 0, y_values[0], lw=0, edgecolor='grey', facecolor=colors[0])
    p.append(Rectangle((0, 0), 1, 1, lw=0, edgecolor='grey', facecolor=colors[0]))  # for legend
    for i, (cur_bottom, cur_top) in enumerate(zip(y_values[:-1], y_values[1:])):
        ax.fill_between(x_values, cur_bottom, cur_top, lw=0, edgecolor='grey', facecolor=colors[i + 1])
        p.append(Rectangle((0, 0), 1, 1, lw=0, edgecolor='grey', facecolor=colors[i + 1]))

    ax.set_ylim(ymax=1.0)

    # set labels and legend
    if plot_title:
        ax.set_title(plot_title, fontsize=lp.fs)
    ax.set_xlabel(x_label, fontsize=lp.fs)
    ax.set_ylabel(y_label, fontsize=lp.fs)
    if series_labels[0]:
        leg = ax.legend(p, series_labels, ncol=2, title=legend_title, labelspacing=0.1, columnspacing=1,
                        loc='upper right')
        plt.setp(leg.get_texts(), fontsize='small')
        leg.get_frame().set_alpha(0.8)
        leg.get_frame().set_linewidth(0.0)
        #leg = ax.legend(p, series_labels)

    plt.setp(ax.get_xticklabels(), fontsize=lp.fs)
    plt.setp(ax.get_yticklabels(), fontsize=lp.fs)

def output_bars(ofile, x_values, y_values, x_label, y_label, x_ticklabels=None, y_errs=None, ymin=0.0, ymax=None,
                series_labels=None,
                legend_loc=2, rotate_ticks=False, plot_title=None, bw=False):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    plot_bars(ax, x_values, y_values, x_label, y_label, x_ticklabels, y_errs, ymin, ymax, series_labels,
              legend_loc, rotate_ticks, plot_title, bw)

    fig.tight_layout()
    fig.savefig(ofile)

def plot_bars(ax, x_values, y_values, x_label, y_label, x_ticklabels=None, y_errs=None, ymin=0.0, ymax=None,
              series_labels=None,
              legend_loc=2, rotate_ticks=False, plot_title=None, bw=False):
    # if data values submitted as a single series, wrap in list
    if not (isinstance(y_values[0], list)
            or isinstance(y_values[0], np.ndarray)
            or isinstance(y_values[0], tuple)):
        y_values = [y_values]

    #print len(x_values), len(y_values[0])
    assert len(x_values) == len(y_values[0])

    loc_colors = get_distinct(len(y_values), bw)

    # same with error values
    if y_errs is not None and (not isinstance(y_errs[0], (list, np.ndarray, tuple))):
        y_errs = [y_errs]

    # expand y_errs and series_labels if not present
    if not y_errs:
        y_errs = [None] * len(y_values)
    if not series_labels:
        series_labels = [None] * len(y_values)

    width = 0.8 / len(y_values)

    x_values = np.array(x_values)

    # plot bars
    for i, (cur_values, cur_errs, cur_label) in enumerate(zip(y_values, y_errs, series_labels)):
        ax.bar(x_values + i * width, cur_values, width, lw=0, edgecolor='grey', color=loc_colors[i], ecolor='dimgrey',
               align='center', yerr=cur_errs, label=cur_label)

    if plot_title:
        ax.set_title(plot_title, fontsize=lp.fs)
    ax.set_ylabel(y_label, fontsize=lp.fs)
    ax.set_xlabel(x_label, fontsize=lp.fs)
    if len(y_values) == 1:
        ax.set_xlim(xmin=-1, xmax=len(x_values))
    else:
        ax.set_xlim(xmin=-0.5, xmax=len(x_values))

    ax.set_ylim(ymin=ymin)
    if ymax is not None:
        ax.set_ylim(ymax=ymax)

    if x_ticklabels:
        ax.set_xticks(np.array(x_values) + len(y_values) / 2 * width)
        ax.set_xticklabels(tuple(x_ticklabels), rotation=(20 if rotate_ticks else 0))

    ax.xaxis.set_ticks_position('none')

    if series_labels[0]:
        leg = ax.legend(loc=legend_loc)
        leg.get_frame().set_alpha(0.0)

    plt.setp(ax.get_xticklabels(), fontsize=lp.fs)
    plt.setp(ax.get_yticklabels(), fontsize=lp.fs)

def plot_statistics(ofile, x_values, y_values, x_label, y_label, y_errs=None, series_labels=None,
                    ymin=None, xmax=None, xlogscale=False, ylogscale=False, title=None, bw=False,
                    legend_loc=None, legend_title=None):
    # create figure
    fig = plt.figure()
    ax = fig.add_subplot(111)

    plot_lines(ax, x_values, y_values, x_label, y_label, y_errs, series_labels, bw=bw,
               legend_loc=legend_loc, legend_title=legend_title)

    if xlogscale:
        ax.set_xscale('log')
    if ylogscale:
        ax.set_yscale('log')

    if ymin:
        if isinstance(ymin, (int, float)):
            ax.set_ylim(ymin=ymin)
        elif ymin == 'zero':
            ax.set_ylim(ymin=0)

    if title:
        ax.set_title(title, fontsize=lp.fs)

    fig.tight_layout()
    fig.savefig(ofile)


import sys

input = sys.stdin.readline

n, m = map(int, input().split())

pokemon_name = {}
pokemon_num = {}

for i in range(1, n + 1):
    name = input().strip()
    pokemon_name[name] = i
    pokemon_num[str(i)] = name

for _ in range(m):
    cmd = input().strip()
    if cmd.isdigit():
        print(pokemon_num[cmd])
    else:
        print(pokemon_name[cmd])


#This is a python code to implement linked lists in python
#Implementation of linked list in python gives you the advantage of storing any type of data in the data field of the node
#Code by Akshat Aryan
import os

class Node():
    #node contains data and link
    def __init__(self, data):
        self.data = data
        self.__link = None

class Llist(Node):
    #inititalising head. You can only access the other elements from the head
    def __init__(self):
        self.head = None

    #returns true is list is empty, else returns False
    def isempty(self):
        if (self.head == None):
            return True
        else:
            return False

    #traverses and returns the last element and its previous element of the list
    def traverse(self):
        if(self.isempty()):
            return None
        else:
            curr = self.head
            prev = self.head
            while(curr.link != None):
                prev = curr
                curr = curr.link
            if(prev == curr):
                return(None, curr)
            else:
                return(prev, curr)

    #inserts element at the front of the list, changes head
    def insert_front(self, ele):
        newnode = Node(ele) # Initialising node
        if(self.isempty()): #when list is empty
            self.head = newnode
        else: #when list is not empty
            newnode.link = self.head
            self.head = newnode

    #traverses and inserts the element to the end of the list
    def insert_rear(self, ele):
        newnode = Node(ele) # Initialising node
        if(self.isempty()): #when list is empty
            self.head = newnode
        else: #when list is not empty
            temp = self.traverse()[1]
            temp.link = newnode

    #inserts the element after the specified data node. If data node is not found, does nothing
    def insert_after(self, prev_data, ele):
        newnode = Node(ele) # Initialising node
        if(self.isempty()): #when list is empty
            return -1
        else: #when list is not empty
            if (self.head.link == None): #if there is only one element in list
                if(self.head.data == prev_data):
                    self.head.link = newnode
                else:
                    return -1
            else: #when there are more than 1 element in the list
                found = -1
                curr = self.head
                prev = self.head
                while(curr != None):
                    prev = curr
                    curr = curr.link
                    if(prev.data == prev_data):
                        found = 1
                        prev.link = newnode
                        newnode.link = curr
                        break
                if(found != 1):
                    return -1

    #deletes the head element of the list
    def delete_front(self):
        if(self.isempty()): #when list is empty
            return None
        else: #when list is not empty
            x = self.head.data
            self.head = self.head.link
            return x

    #deletes the last element of the list
    def delete_rear(self):
        if(self.isempty()): #when list is empty
            return None
        else: #when list is not empty
            if(self.head.link == None): #if there is only one element in list
                x = self.head.data
                self.head = None
                return x
            else: #when there are more than 1 element in the list
                curr = self.traverse()[1]
                prev = self.traverse()[0]
                x = curr.data
                prev.link = None
                del curr
                return x

    #deletes the specified element from the list
    def delete_pos(self, ele):
        if(self.isempty()): #when list is empty
            return None
        elif(self.head.link == None): #if there is only one element in list
            if(self.head.data == ele):
                x = self.head.data
                self.head = None
                return x
            else:
                return None
        else: #when there are more than 1 element in the list
            curr = self.head
            prev = None
            while(curr != None):
                if(curr.data == ele):
                    x = curr.data
                    if(curr != self.head):
                        prev.link = curr.link
                    else:
                        self.head = curr.link
                    return x
                prev = curr
                curr = curr.link
            if(curr == None):
                return None

    #returns 1 if the searched element is found. else returns 0
    def search(self, ele):
        if(self.isempty()): #when list is empty
            return 0
        else: #when list is not empty
            temp = self.head
            while(temp != None and temp.data != ele):
                temp = temp.link
            if (temp == None):
                return -1
            else:
                return 1

    #displays the list in linear form
    def display(self):
        if(self.isempty()):
            print("List empty")
        else:
            print("Your linked list is:")
            temp = self.head
            while(temp.link != None):
                print(temp.data, end = "\t")
                temp = temp.link
            print(temp.data)

#functions to clear screen for the menu driven program
def clear():
    os.system("cls")
def pausenclear():
    input("Press enter to continue:")
    os.system("cls")

if __name__ == "__main__":
    #creating the linked list object
    l1 = Llist()

    #Menu: (self explanatory)
    while True:
        clear()
        print("Your choices are: 1. Insert 2. Delete 3. Search 4. Display 5. Exit")
        ch = int(input("Enter your choice(1/2/3/4/5):"))
        if(ch == 1):
            while True:
                clear()
                print("Your choices are: 1. Insert Front 2. Insert Rear 3. Insert after 4. Back")
                ch2 = int(input("Enter your choice(1/2/3/4/5):"))
                if(ch2 == 1):
                    a = input("Enter data:")
                    l1.insert_front(a)
                    print(a, "Inserted successfully")
                elif(ch2 == 2):
                    a = input("Enter data:")
                    l1.insert_rear(a)
                    print(a, "Inserted successfully")
                elif(ch2 == 3):
                    a = input("Enter data:")
                    b = input("Enter the data after which you want to insert:")
                    x = l1.insert_after(b, a)
                    if(x == -1):
                        print("Specified Node doesn't exist. Insert Unsuccessful")
                    else:
                        print(a, "Inserted successfully")
                elif(ch2 == 4):
                    pausenclear()
                    break
                pausenclear()
        elif(ch == 2):
            while True:
                clear()
                print("Your choices are: 1. Delete Front 2. Delete Rear 3. Delete specified 4. Back")
                ch2 = int(input("Enter your choice(1/2/3/4/5):"))
                if(ch2 == 1):
                    x = l1.delete_front()
                elif(ch2 == 2):
                    clear()
                    x = l1.delete_rear()
                elif(ch2 == 3):
                    clear()
                    b = input("Enter the data you want to delete:")
                    x = l1.delete_pos(b)
                elif(ch2 == 4):
                    pausenclear()
                    break
                if(x != None):
                    print(x, "Deleted successfully")
                else:
                    print("Delete Unsuccessful")
                pausenclear()
        elif(ch == 3):
            clear()
            a = input("Enter the element you want to search:")
            x = l1.search(a)
            if(x == -1):
                print("Element not found")
            elif(x == 0):
                print("List empty")
            else:
                print("Element found")
            pausenclear()
        elif(ch == 4):
            clear()
            l1.display()
            pausenclear()
        elif(ch == 5):
            break


#!/usr/bin/env python3
"""
Contains function to sum a list of integers and floats

function:
 * sum_mixed_list: sums up a list
"""

from typing import List, Union

def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float:
    """Sums up a list of integers and floats"""
    total_sum: float = 0.0
    for i in mxd_lst:
        total_sum += i
    return total_sum


#!/usr/bin/env python3

"""
Mono camera control demo:
  Control:      key[dec/inc]  min..max
  exposure time:     I   O      1..33000 [us]
  sensitivity iso:   K   L    100..1600
Back to autoexposure: 'E'
"""

import cv2
import depthai as dai

# Start defining a pipeline
pipeline = dai.Pipeline()

# Define a source - two mono (grayscale) cameras
camLeft = pipeline.createMonoCamera()
camLeft.setBoardSocket(dai.CameraBoardSocket.LEFT)
camLeft.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)

camRight = pipeline.createMonoCamera()
camRight.setBoardSocket(dai.CameraBoardSocket.RIGHT)
camRight.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)

# Create outputs
xoutLeft = pipeline.createXLinkOut()
xoutLeft.setStreamName('left')
camLeft.out.link(xoutLeft.input)
xoutRight = pipeline.createXLinkOut()
xoutRight.setStreamName('right')
camRight.out.link(xoutRight.input)

# Create and link control input
control_in = pipeline.createXLinkIn()
control_in.setStreamName('control')
control_in.out.link(camLeft.inputControl)
control_in.out.link(camRight.inputControl)

def clamp(num, v0, v1): return max(v0, min(num, v1))

# Pipeline is defined, now we can connect to the device
with dai.Device(pipeline) as device:
    # Start pipeline
    device.startPipeline()

    # Output queues will be used to get the grayscale frames from the outputs defined above
    qLeft = device.getOutputQueue(name="left", maxSize=4, blocking=False)
    qRight = device.getOutputQueue(name="right", maxSize=4, blocking=False)
    # Input queue for control commands
    controlQueue = device.getInputQueue('control')

    # Manual exposure: key-press step, defaults and limits
    EXP_STEP = 500  # us
    ISO_STEP = 50

    exp_time = 20000
    expMin = 1
    expMax = 33000

    sensIso = 800
    sensMin = 100
    sensMax = 1600

    frameLeft = None
    frameRight = None

    while True:
        # Instead of get (blocking), we use tryGet (nonblocking) which will return the available data or None otherwise
        inLeft = qLeft.tryGet()
        inRight = qRight.tryGet()

        if inLeft is not None:
            frameLeft = inLeft.getCvFrame()

        if inRight is not None:
            frameRight = inRight.getCvFrame()

        # show the frames if available
        if frameLeft is not None:
            cv2.imshow("left", frameLeft)
        if frameRight is not None:
            cv2.imshow("right", frameRight)

        key = cv2.waitKey(1)
        if key == ord('q'):
            break
        elif key in [ord('i'), ord('o'), ord('k'), ord('l')]:
            if key == ord('i'):
                exp_time -= EXP_STEP
            if key == ord('o'):
                exp_time += EXP_STEP
            if key == ord('k'):
                sensIso -= ISO_STEP
            if key == ord('l'):
                sensIso += ISO_STEP
            exp_time = clamp(exp_time, expMin, expMax)
            sensIso = clamp(sensIso, sensMin, sensMax)
            print("Setting manual exposure, time:", exp_time, "iso:", sensIso)
            ctrl = dai.CameraControl()
            ctrl.setManualExposure(exp_time, sensIso)
            controlQueue.send(ctrl)
        elif key == ord('e'):
            print("Autoexposure enable")
            ctrl = dai.CameraControl()
            ctrl.setAutoExposureEnable()
            controlQueue.send(ctrl)


# -*- coding: utf-8 -*-
# @Time : 2020/8/18 21:47
# @Author : sml
# @File : 34.数组中的逆序对.py

#没看明白

# -*- coding:utf-8 -*-
class Solution:
    def InversePairs(self, data):
    # write code here
        if len(data) == 0:
            return 0

        def mergeSort(data, begin, end):
            if begin == end - 1:
                return 0
            mid = int((begin + end) / 2)
            left_count = mergeSort(data, begin, mid)
            right_count = mergeSort(data, mid, end)
            merge_count = merge(data, begin, mid, end)
            return left_count + right_count + merge_count

        def merge(data, begin, mid, end):
            i = begin
            j = mid
            count = 0
            temp = []
            while i < mid and j < end:
                if data[i] <= data[j]:
                    temp.append(data[i])
                    i += 1
                else:
                    temp.append(data[j])
                    j += 1
                    count += mid - i
            while i < mid:
                temp.append(data[i])
                i += 1
            while j < end:
                temp.append(data[j])
                j += 1
            data[begin: end] = temp
            del temp
            return count

        begin = 0
        end = len(data)
        ans = mergeSort(data, begin, end)
        return ans % 1000000007

        # write code here

34.数组中的逆序对.py


from branca.element import MacroElement
from jinja2 import Template

from folium.elements import JSCSSMixin
from folium.utilities import parse_options

class MousePosition(JSCSSMixin, MacroElement):
    """Add a field that shows the coordinates of the mouse position.

    Uses the Leaflet plugin by Ardhi Lukianto under MIT license.
    https://github.com/ardhi/Leaflet.MousePosition

    Parameters
    ----------
    position : str, default 'bottomright'
        The standard Control position parameter for the widget.
    separator : str, default ' : '
        Character used to separate latitude and longitude values.
    empty_string : str, default 'Unavailable'
       Initial text to display.
    lng_first : bool, default False
        Whether to put the longitude first or not.
        Set as True to display longitude before latitude.
    num_digits : int, default '5'
        Number of decimal places included in the displayed
        longitude and latitude decimal degree values.
    prefix : str, default ''
        A string to be prepended to the coordinates.
    lat_formatter : str, default None
        Custom Javascript function to format the latitude value.
    lng_formatter : str, default None
        Custom Javascript function to format the longitude value.

    Examples
    --------
    >>> fmtr = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};"
    >>> MousePosition(
    ...     position="topright",
    ...     separator=" | ",
    ...     prefix="Mouse:",
    ...     lat_formatter=fmtr,
    ...     lng_formatter=fmtr,
    ... )

    """

    _template = Template(
        """
        {% macro script(this, kwargs) %}
            var {{ this.get_name() }} = new L.Control.MousePosition(
                {{ this.options|tojson }}
            );
            {{ this.get_name() }}.options["latFormatter"] =
                {{ this.lat_formatter }};
            {{ this.get_name() }}.options["lngFormatter"] =
                {{ this.lng_formatter }};
            {{ this._parent.get_name() }}.addControl({{ this.get_name() }});
        {% endmacro %}
    """
    )

    default_js = [
        (
            "Control_MousePosition_js",
            "https://cdn.jsdelivr.net/gh/ardhi/Leaflet.MousePosition/src/L.Control.MousePosition.min.js",
        )
    ]
    default_css = [
        (
            "Control_MousePosition_css",
            "https://cdn.jsdelivr.net/gh/ardhi/Leaflet.MousePosition/src/L.Control.MousePosition.min.css",
        )
    ]

    def __init__(
        self,
        position="bottomright",
        separator=" : ",
        empty_string="Unavailable",
        lng_first=False,
        num_digits=5,
        prefix="",
        lat_formatter=None,
        lng_formatter=None,
        **kwargs
    ):
        super().__init__()
        self._name = "MousePosition"

        self.options = parse_options(
            position=position,
            separator=separator,
            empty_string=empty_string,
            lng_first=lng_first,
            num_digits=num_digits,
            prefix=prefix,
            **kwargs
        )
        self.lat_formatter = lat_formatter or "undefined"
        self.lng_formatter = lng_formatter or "undefined"


# coding=utf-8
import os

from PyQt4 import QtGui, uic
from PyQt4.QtCore import QFile
from PyQt4.QtGui import QAbstractItemView

from QTwrap import qtmodel, qtMenu, qtTreeModel, Qt

"""编译UI文件"""

def ui_compile(uifile):
    if os.path.isfile(uifile + '.ui'):
        ui = QFile(uifile + '.ui')
        py = QFile('ui' + uifile + '.py')
        ui.open(QFile.ReadOnly)
        py.open(QFile.WriteOnly)
        uic.compileUi(ui, py)
        ui.close()
        py.close()

class guiUtil():
    def load_buttons(self, buttons):
        for btn in buttons:
            btn['widget'].clicked.connect(btn['call'])
            if btn.has_key('singal'):
                btn['singal'].connect(btn['enCall'])
                btn['enCall']()

    def load_tableviews(self, tableviews, db):
        for tableview in tableviews:
            if tableview.has_key('showGrid'):
                tableview['widget'].setShowGrid(tableview['showGrid'])
            tableview['widget'].setSelectionBehavior(QAbstractItemView.SelectRows)  # 整行选中的方式
            model = qtmodel(tableview['model'], db, tableview['widget'])
            if tableview.has_key('menu'):
                menu = qtMenu(tableview['menu'], tableview['name'], tableview['widget'])
            if tableview.has_key('doubleClick'):
                tableview['widget'].doubleClicked.connect(tableview['doubleClick'])
            if tableview.has_key('clicked'):
                tableview['widget'].clicked.connect(tableview['clicked'])
            model.load()

    def load_treeviews(self, treeviews, db):
        for treeview in treeviews:
            model = qtTreeModel(treeview['model'], db, [["id", ">", 0]], treeview['widget'])
            treeview['widget'].setSelectionBehavior(QAbstractItemView.SelectRows)  # 整行选中的方式
            if treeview.has_key('menu'):
                menu = qtMenu(treeview['menu'], treeview['name'], treeview['widget'])
            if treeview.has_key('doubleClick'):
                treeview['widget'].doubleClicked.connect(treeview['doubleClick'])
            if treeview.has_key('clicked'):
                treeview['widget'].clicked.connect(treeview['clicked'])

    def loadCheckboxs(self, checkBoxs):
        for checkbox in checkBoxs:
            box = checkbox['widget']
            box.setTristate(False)
            val = checkbox['init']()
            box.setCheckState(val)
            box.stateChanged.connect(checkbox['save'])

class guiqt(QtGui.QMainWindow, guiUtil):
    def __init__(self, *args):
        QtGui.QMainWindow.__init__(self, *args)
        self.setupUi(self)
        self.show()
        # self.win = uic.loadUi(ui, self)

class guiDialog(QtGui.QDialog, guiUtil):
    def __init__(self, *args):
        QtGui.QDialog.__init__(self, *args)

        self.setupUi(self)
        # self.setWindowModality(Qt.WindowModal)
        self.setModal(True)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)


#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt
import os

def amplitude(a):
	a							=	(a.imag**2+a.real**2)**0.5
	return a

def mean(a):
	mean_a						=	np.zeros(256)
	for i in range(256):
		for j in range(len(a)):
			mean_a[i]			+=	amplitude(a[j][i])
		mean_a[i]				=	mean_a[i]/len(a)
	return mean_a

def reject_matrix(XX_m):
	R		=	np.zeros(256)
	for i in range(256):
		if(np.abs(amplitude(XX_m[i])-np.mean(XX_m))>np.std(XX_m)*n_s):
			R[i]	=	1
	return R

def reject(R,corr):
	for j in range(256):
		if(R[j]==1):
			for i in range(i_n):
				corr[i][j]=0

def corr_read(s1,fopen,XX_1):
	j	=	0
	i	=	0
	while(i<int(s1)):
		p		=	fopen.read(1)
		ctr1	=	-1
		ctr2	=	-1
		e_flag	=	0
		while(p!='(' or p=='0' and i<int(s1)):
			if(p=='0'):
				#print p
				XX_1.append(complex(0,0))
				i	+=	2
				fopen.read(2)
			if(not(i<int(s1))):
				break
			p	=	fopen.read(1)
			i	+=	1
		if(not(i<int(s1))):
			break
		while((p!='+' or e_flag) and (p!='-' or ctr1==0 or e_flag)):
			p	=	fopen.read(1)
			ctr1	+=	1
			if(not(e_flag-ctr1)):
				e_flag	=	0
			if(p=='e'):
				e_flag	=	ctr1+2
		while(p!='j'):
			p	=	fopen.read(1)
			ctr2	+=	1
		fopen.seek(-ctr1-ctr2-2,1)
		r	=	float(fopen.read(ctr1))
		fopen.read(1)
		im	=	float(fopen.read(ctr2))
		#print complex(r,im)
		XX_1.append(complex(r,im))
		fopen.read(3)
		i	+=	ctr1+ctr2+5
		j	+=	1

file_name	=	'ch00_CASA_20170602_234118_000_cross_corr.txt'
#file_name	=	raw_input('File: ')
n_s		=	2
fopen	=	open(file_name,'r')
size	=	os.path.getsize(file_name)
s1		=	float(size)/4
ARR		=	[]

corr_read(size,fopen,ARR)

l	= int(float(len(ARR)))

n	=	int(l/4)
i_n	=	int(n/256)

ARR_256	=	np.zeros((4,i_n,256),dtype='complex')
XX		=	np.zeros((i_n,256),dtype='complex')
XY		=	np.zeros((i_n,256),dtype='complex')
YX		=	np.zeros((i_n,256),dtype='complex')
YY		=	np.zeros((i_n,256),dtype='complex')

for k in range(4):
	for i in range(i_n):
		for j in range(256):
			ARR_256[k][i][j]	=	ARR[(k*n)+(i*256)+j]

XX	=	ARR_256[0]
XY	=	ARR_256[1]
YY	=	ARR_256[2]
YX	=	ARR_256[3]

XX_m	=	mean(XX)
XY_m	=	mean(XY)
YY_m	=	mean(YY)
YX_m	=	mean(YX)

R_XX	=	reject_matrix(XX_m)
R_XY	=	reject_matrix(XY_m)
R_YY	=	reject_matrix(YY_m)
R_YX	=	reject_matrix(YX_m)

reject(R_XX,XX)
reject(R_XY,XY)
reject(R_YY,YY)
reject(R_YX,YX)

fig1	=	plt.figure(1)
plt.subplot(221)
plt.imshow(amplitude(XX.T),interpolation='bilinear',aspect='auto')
plt.ylabel('XX')
plt.subplot(222)
plt.imshow(amplitude(XY.T),interpolation='bilinear',aspect='auto')
plt.ylabel('XY')
plt.subplot(223)
plt.imshow(amplitude(YY.T),interpolation='bilinear',aspect='auto')
plt.ylabel('YY')
plt.subplot(224)
plt.imshow(amplitude(YX.T),interpolation='bilinear',aspect='auto')
plt.ylabel('YX')
fig1.savefig(file_name[:-4]+'_im(clean).png')

fig11	=	plt.figure(11)
plt.subplot(221)
plt.plot(amplitude(XX_m))
plt.plot([np.mean(XX_m)-n_s*np.std(XX_m) for i in range(len(XX_m))])
plt.plot([np.mean(XX_m)+n_s*np.std(XX_m) for i in range(len(XX_m))])
plt.ylabel('XX')
plt.subplot(222)
plt.plot(amplitude(XY_m))
plt.plot([np.mean(XY_m)-n_s*np.std(XY_m) for i in range(len(XY_m))])
plt.plot([np.mean(XY_m)+n_s*np.std(XY_m) for i in range(len(XY_m))])
plt.ylabel('XY')
plt.subplot(223)
plt.plot(amplitude(YY_m))
plt.plot([np.mean(YY_m)-n_s*np.std(YY_m) for i in range(len(YY_m))])
plt.plot([np.mean(YY_m)+n_s*np.std(YY_m) for i in range(len(YY_m))])
plt.ylabel('YY')
plt.subplot(224)
plt.plot(amplitude(YX_m))
plt.plot([np.mean(YX_m)-n_s*np.std(YX_m) for i in range(len(YX_m))])
plt.plot([np.mean(YX_m)+n_s*np.std(YX_m) for i in range(len(YX_m))])
plt.ylabel('YX')
fig11.savefig(file_name[:-4]+'1(clean).png')

plt.figure()
plt.subplot(221)
plt.plot(R_XX)
plt.subplot(222)
plt.plot(R_XY)
plt.subplot(223)
plt.plot(R_YY)
plt.subplot(224)
plt.plot(R_YX)

plt.show()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import json
import subprocess

cached_functions = {}

def getMetricsJson(src_url):
    if src_url.startswith("http"):
        print("Fetching source for function extraction: {}".format(src_url))
        metrics = subprocess.check_output(["./fetch_fn_names.sh", src_url])
    else:
        print("Skip fetching source: {}".format(src_url))
        metrics = ""

    try:
        return json.loads(metrics)
    except ValueError:
        return {"kind": "empty", "name": "anonymous", "spaces": []}

def getSpaceFunctionsRecursive(metrics_space):
    functions = []
    if (
        metrics_space["kind"] == "function"
        and metrics_space["name"]
        and metrics_space["name"] != "<anonymous>"
    ):
        functions.append(
            {
                "name": metrics_space["name"],
                "start_line": int(metrics_space["start_line"]),
                "end_line": int(metrics_space["end_line"]),
            }
        )
    for space in metrics_space["spaces"]:
        functions += getSpaceFunctionsRecursive(space)
    return functions

def getSourceFunctions(src_url):
    if src_url not in cached_functions:
        metrics_space = getMetricsJson(src_url)
        cached_functions[src_url] = getSpaceFunctionsRecursive(metrics_space)

    return cached_functions[src_url]

def getFunctionName(location):
    location.replace("annotate", "raw-file")
    pieces = location.split("#l")
    src_url = pieces[0]
    line = int(pieces[1])
    closest_name = "<Unknown {}>".format(line)
    closest_start = 0
    functions = getSourceFunctions(src_url)
    for fn in functions:
        if (
            fn["start_line"] > closest_start
            and line >= fn["start_line"]
            and line <= fn["end_line"]
        ):
            closest_start = fn["start_line"]
            closest_name = fn["name"]
    return closest_name


import sys
import time
import os
sys.path.append('./admin')
sys.path.append('./user')
os.system("cls")
print("wait for some second we are opening your terminal !")
for i in range(0, 110,10) :
    for y in range(1,5) :
        loading= f"|{'#'*int(i/10)}"
        if y == 1 :
            c = "/"
        elif y == 2 :
            c = "|"
        elif y == 3 :
            c = "\\"
        else :
            c = "-"
        print(loading.ljust(12),'|',c ,i, "%")
        time.sleep(0.1/3)
        os.system("cls")

# for i in range(0, 100,10) :
#     for y in range(1,4) :
#         loading= f"Loading{'.'*y}"
#         print(loading.ljust(10) ,i, "%")
#         time.sleep(0.1/3)
#         os.system("cls")

time.sleep(1.5)
VL = "VoltLibrary"
heading = "Welcome to " + "\033[1m" + VL + "\033[0m" + " portal !!!"
print(heading)
print("Select you are Admin or User")
print("1 = Admin\n2 = User")
auth = int(input("select : "))

if auth == 1:
    print("I am Admin")
    import admin
elif auth == 2:
    print("I am User")
    import user


import sys
from enum import Enum
import cv2
import matplotlib.pyplot as plt
from .setting import *

class DectionMethod(Enum):
    ColorFilter = 1

class ProcessType(Enum):
    CenterCoordinate = 1
    Bound = 2

###########################################
class CamerSystem:
    # 网络摄像头URL示例 r"http://192.168.0.120:8080/?action=stream"
    cameraMainURL = r"C:\Users\Arnoliu\PycharmProjects\opecvtry\toolbox\demoVideo.mp4"
    cameraViceURL = 0

    def __init__(self, oneOrTwoCamera=1):
        # 根据用户的选择开启几个摄像头
        self.CameraNumber = oneOrTwoCamera
        assert oneOrTwoCamera != 1 or oneOrTwoCamera != 2
        if oneOrTwoCamera >= 1:
            self.cap_l = cv2.VideoCapture(CamerSystem.cameraMainURL)
        if oneOrTwoCamera == 2:
            self.cap_r = cv2.VideoCapture(CamerSystem.cameraViceURL)

    # 读取配置文件
    def loadConfigue(self):
        self.lower_red, self.upper_red = readColorIni()

    def takeImg(self):
        ret, frame = self.cap_l.read()
        if not ret:
            print("No Stream or stream stopped!")
            return None
        return frame

    def getFPS(self):
        return self.cap_l.get(propId=cv2.CAP_PROP_FPS)

    def releasCam(self):
        if self.CameraNumber >= 1:
            self.cap_l.release()
        if self.CameraNumber == 2:
            self.cap_r.release()

    # MotionDect
    # 有固定的背景https://www.yyearth.com/article/18-09/242.html

    fgbg = cv2.createBackgroundSubtractorKNN(history=100, detectShadows=False)

    def MotionThreshold(self, img=None, keepOrigin=False):
        if img is None:
            frame = self.takeImg()
            if frame is None:
                return None
        else:
            frame = img
        blured = cv2.GaussianBlur(frame, (3, 3), 0)
        knersize, iterations = readMotionIni()

        fgmask = self.fgbg.apply(blured)
        fgmask = open_mor(fgmask, knersize, iterations)
        if keepOrigin:
            return frame, fgmask
        return fgmask

    def ColorThreshold(self, img=None, blurKernelSize=5, colorBound=None, showSource=True, keepOrigin=False):
        self.loadConfigue()
        if colorBound == None:
            lower_bound = self.lower_red
            upper_bound = self.upper_red
        else:
            lower_bound = colorBound[0]
            upper_bound = colorBound[1]

        if img is None:
            frame = self.takeImg()
            if frame is None:
                return None
        else:
            frame = img
        if showSource:
            cv2.imshow("source", frame)
        blured = cv2.GaussianBlur(frame, (blurKernelSize, blurKernelSize), 0)
        color_fliter = cv2.inRange(blured, lower_bound, upper_bound)
        color_fliter = cv2.erode(color_fliter, (10, 10), iterations=3)
        color_fliter = open_mor(color_fliter, 5, 1)

        if keepOrigin:
            return frame, color_fliter
        return color_fliter

    matchImg = cv2.imread("obj.jpg")

    def GetCenterByMatchTemplet(self, img=None,method=1):
        if img is None:
            frame = self.takeImg()
            if frame is None:
                return -1,-1
        else:
            frame = img
        match = cv2.matchTemplate(frame, self.matchImg, method=method)
        min_val, max_val, min_loc, max_loc =cv2.minMaxLoc(match)
        # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
        if method in [0, 1]:
            top_left = min_loc
        else:
            top_left = max_loc
        drawPointonImg(frame,top_left[0],top_left[1])
        return top_left

    def GetCenterByLongestContour(self, img, type=ProcessType.CenterCoordinate, debug=False):
        if sys.platform.startswith('win'):
            contours_m, hierarchy_m = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        else:
            h, contours_m, hierarchy_m = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        areas = [cv2.contourArea(c) for c in contours_m]
        if len(areas) == 0:
            return (-1, -1, -1, -1)
        longestArea = contours_m[np.nanargmax(areas)]

        if type == ProcessType.CenterCoordinate:
            hull = cv2.convexHull(longestArea)

            if debug:
                debugImg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
                length = len(hull)
                for i in range(len(hull)):
                    cv2.line(debugImg, tuple(hull[i][0]), tuple(hull[(i + 1) % length][0]), (0, 255, 0), 2)
                cv2.imshow("Debug", debugImg)
            return hull.mean(axis=0).tolist()[0]
            # return round((2 * x + w) / 2), round((2 * y + h) / 2)
        else:
            (x, y, w, h) = cv2.boundingRect(longestArea)
            return x, y, w, h

# region Open And Close
def open_mor(src, kernelsize, iter):
    kernel = np.ones((kernelsize, kernelsize), np.uint8)
    opening = cv2.morphologyEx(src, cv2.MORPH_OPEN, kernel, iterations=iter)
    return opening

# ! Do not use this
def close_mor(src, kernelsize: int, iter):
    kernel = np.ones((kernelsize, kernelsize), np.uint8)
    opening = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel, iterations=iter)
    return opening

# endregion
# 直接计算图像的重心
def centerPoint(thimg):
    mom = cv2.moments(thimg)
    if mom["m00"] == 0:
        return 0, 0
    center_x = round(mom["m10"] / mom["m00"])
    center_y = round(mom["m01"] / mom["m00"])
    return center_x, center_y

# Draw Tool
def drawPointonImg(img, px, py):
    if img.shape[2]!=3:
        img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    else:
        img_rgb=img.copy()
    cv2.circle(img_rgb, (px, py), 3, (0, 0, 255))
    cv2.imshow("centerPoint", img_rgb)

def drawCenterPoint(img, imgName):
    meanX, meanY = centerPoint(img)
    img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    cv2.circle(img_rgb, (meanX, meanY), 3, (0, 0, 255))
    cv2.imshow("centerPoint" + str(imgName), img_rgb)
    return meanX, meanY

def drawCont(thimg):
    tempimg = thimg.copy()
    contours = cv2.findContours(tempimg)
    img_rgb = cv2.cvtColor(tempimg, cv2.COLOR_GRAY2BGR)
    for point in contours:
        cv2.circle(tempimg, point, 1, (0, 0, 255))
    cv2.imshow("Cont", tempimg)


from ariadne import convert_kwargs_to_snake_case

def shopping_list_items_resolver(obj, info):
    from api.models import ShoppingListItem
    try:
        items = [item.to_dict() for item in ShoppingListItem.query.all()]
        print(items)
        payload = {
            "success": True,
            "shopping_list_items": items
        }
    except Exception as error:
        payload = {
            "success": False,
            "errors": [str(error)]
        }
    return payload

@convert_kwargs_to_snake_case
def get_shopping_list_item_resolver(obj, info, uid):
    from api.models import ShoppingListItem
    try:
        item = ShoppingListItem.query.get(uid)
        print(item)
        payload = {
            "success": True,
            "shopping_list_item": item.to_dict()
        }
    except AttributeError as error:
        payload = {
            "success": False,
            "errors": [f"Не найден uid {uid}"]
        }
    except Exception as error:
        payload = {
            "success": False,
            "errors": [str(error)]
        }
    return payload


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

import json
import time
from pyspark.ml import Pipeline
from pyspark.ml.feature import StringIndexer
from pyspark.sql import SparkSession, DataFrame as SparkDataFrame
from pyspark.sql.functions import mean as _mean, col, sort_array, collect_list, struct, udf
from pyspark.mllib.evaluation import RankingMetrics
from pyspark.sql.types import StringType, ArrayType, StructType, StructField, FloatType, IntegerType
import argparse

class Bias:
    '''
        popularity baseline model.

        The predictor is based on the following algorithm:
        𝑏𝑢𝑖=𝜇+𝑏𝑢+𝑏𝑖

        where 𝜇 is the global mean rating. 𝑏𝑖 is the item bias, and 𝑏𝑢 is the user bias.
        hey are computed as follows:

        𝑏𝑖=∑𝑢∈R(𝑖)(𝑟𝑢𝑖−𝜇) / 𝜆2+|R(𝑖)|.

        𝑏𝑢=∑𝑖∈R(𝑢)(𝑟𝑢𝑖−𝜇−𝑏𝑖) / 𝜆3+|R(𝑢)|.

        Args:
            item: whether to compute item biases
            users: whether to compute user biases
            damping(number or tuple):
                Bayesian damping to apply to computed biases.  Either a number, to
                damp both user and item biases the same amount, or a (user,item) tuple
                providing separate damping values.
        Attributes:
            mean: The global mean rating.
            item_offsets_(DataFrame): The item offsets (𝑏𝑖 values)
            user_offsets_(DataFrame): The user offsets (𝑏𝑢 values)
    '''

    def __init__(self, item=True, users=True, damping=0.0):
        self.item = item
        self.users = users
        if isinstance(damping, tuple):
            self.damping = damping
            self.user_damping, self.item_damping = damping
        else:
            self.damping = damping
            self.user_damping = damping
            self.item_damping = damping

        if self.user_damping < 0:
            raise ValueError("user damping must be non-negative")
        if self.item_damping < 0:
            raise ValueError("item damping must be non-negative")

    def torating(self, data):
        describe = data.describe(['count']).collect()
        stddev = float(describe[2]['count'])
        mean = float(describe[1]['count'])
        max = mean + 2 * stddev
        min = mean - 2 * stddev
        mul = float((max - min) / 100)

        @udf(FloatType())
        def counttrans(count):
            if count < min:
                count = min
            elif count > max:
                count = max

            percentiles = (count - min) / mul
            if percentiles > 100:
                percentiles = 100
            elif percentiles < 0:
                percentiles = 0
            result = percentiles / 100 * 5

            return result if result > 0 else 0.05

        result = data.withColumn('count', counttrans(col('count')))

        return result

    def fit(self, ratings):
        """
        Train the bias model on some rating data.
        Args:
            ratings (DataFrame): the dataframe of song dataset.
        Returns:
            Bias: the fit bias object.
        """
        ratings_stat = ratings.select(_mean(col('count'))).collect()
        self.mean = ratings_stat[0]['avg(count)']
        print(f'global mean: {self.mean}')
        nrate = ratings.withColumn('minus', col('count') - self.mean).select('minus', 'user_id', 'track_id')

        if self.item:
            self.item_offsets_ = self._group(nrate.groupby('track_id'), self.item_damping, 'track_id')
        else:
            self.item_offsets_ = None

        if self.users:
            if self.item_offsets_ is not None:
                nrate \
                    .join(self.item_offsets_, on='track_id', how='inner') \
                    .withColumn('minus', col('minus') - col('track_id_off')) \
                    .select('minus', 'user_id', 'track_id')

                self.user_offsets_ = self._group(nrate.groupby('user_id'), self.user_damping, 'user_id')
        else:
            self.user_offsets_ = None

        return self

    def predict(self, ratings):
        """
        Do predict for the giving item and user.
        The method use the result of fit() and do not recalculate the 𝑏𝑖 and 𝑏𝑢
        Args:
            ratings (DataFrame): the dataframe of song dataset you want to predict,
                            must have track_id column and user_id column.
        Returns:
            rvsp(DataFrame): the DataFrame with predict result, which in prediction column
        """

        if self.item_offsets_ is not None:
            rvsp = self.item_offsets_.join(ratings, on='track_id', how='left') \
                .fillna({'track_id_off': 0}) \
                .withColumn('prediction', self.mean + col('track_id_off'))
        if self.user_offsets_ is not None:
            rvsp = self.user_offsets_.join(rvsp, on='user_id', how='left') \
                .fillna({'user_id_off': 0}) \
                .withColumn('prediction', col('prediction') + col('user_id_off')) \
                .select('prediction', 'user_id', 'track_id', 'count')
        return rvsp

    def recommendForUserSubset(self, data: SparkDataFrame, k: int = 50, colName: str = 'prediction'):

        stringIndexer = StringIndexer(inputCol="track_id", outputCol="track_id_indexed", handleInvalid="skip", stringOrderType="frequencyDesc")
        model = stringIndexer.fit(data)
        data = model.transform(data).withColumn('track_id_indexed', col('track_id_indexed').cast(IntegerType()))

        limit = udf(lambda z: z[0:k], ArrayType(IntegerType(), True))
        if colName == 'count':
            recommend = data.groupBy('user_id').agg(
                sort_array(collect_list(struct(colName, 'track_id_indexed')), asc=False).alias('list')) \
                .withColumn('labels', col('list.track_id_indexed')).drop('list')
        else:
            recommend = data.groupBy('user_id').agg(
                sort_array(collect_list(struct(colName, 'track_id_indexed')), asc=False).alias('list')) \
                .withColumn('labels', col('list.track_id_indexed')).drop('list')

        return recommend

    def score(self, data: SparkDataFrame, k: int = 50) -> dict:
        predictions = self.recommendForUserSubset(self.predict(data), k, 'prediction') \
            .withColumnRenamed('labels', 'prediction')
        label = self.recommendForUserSubset(data, k, 'count')
        results = label.join(predictions, on='user_id', how='left')
        # results.select('prediction', 'labels').show(n=30, truncate=False, vertical=True)
        _array = udf(lambda z: list() if z is None else z, ArrayType(IntegerType(), True))
        result_rdd = results.select('prediction', 'labels').withColumn('labels', _array(col('labels'))).withColumn('prediction', _array(col('prediction'))).rdd
        # print(results.select('prediction', 'labels').rdd.take(5))
        metrics = RankingMetrics(result_rdd)

        ###
        ## NOTE: RankingEvaluator does not work with PySpark 2.4.0.
        ## See https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.evaluation.RankingEvaluator.html

        # evaluator = RankingEvaluator(predictionCol='predictions', labelCol='labels')
        # value = evaluator.evaluate(results,
        #                            {evaluator.metricName: 'precisionAtK', evaluator.k: k})

        return {
            'map': metrics.meanAveragePrecision,
            f'ndcgAt{k}': metrics.ndcgAt(k),
            f'precisionAt{k}': metrics.precisionAt(k)
        }

    def save(self, spark, path):
        data = ([(self.mean,)])

        schema = StructType([StructField("mean", FloatType(), True)])

        df = spark.createDataFrame(data=data, schema=schema)
        df.write.mode('overwrite').parquet(path + 'mean.parquet')
        self.user_offsets_.write.mode('overwrite').parquet(path + 'user_offsets_.parquet')
        self.item_offsets_.write.mode('overwrite').parquet(path + 'item_offsets_.parquet')
        print(f'save {self.mean}, {self.user_offsets_}, {self.item_offsets_} to {path}')

    def load(self, spark, path):
        model = spark.read.parquet(path + 'mean.parquet')
        model_stat = model.select('*').collect()
        self.mean = model_stat[0]['mean']
        self.user_offsets_ = spark.read.parquet(path + 'user_offsets_.parquet')
        self.item_offsets_ = spark.read.parquet(path + 'item_offsets_.parquet')
        print(f'load {self.mean}, {self.user_offsets_}, {self.item_offsets_} from {path}')

        return self

    def _group(self, group, damping, id):
        if damping is not None and damping > 0:
            count = group \
                .count() \
                .withColumn('add', col('count') + self.item_damping)

            sum = group \
                .sum('minus') \
                .withColumnRenamed('sum(minus)', 'sum')

            off = sum \
                .join(count, on=id, how='inner') \
                .withColumn(id + '_off', col('sum') / col('add')) \
                .select(id, id + '_off')

            return off
        else:
            return group.mean('minus')

def main(spark, train_dir, test_dir, val_dir, damping, k, save_dir, load_dir, torating: bool=False):
    """
    test of Class Bias
    """
    test = Bias(item=True, users=True, damping=damping)
    raw_train_data = spark.read.parquet(train_dir)
    train_data = test.torating(raw_train_data) if torating else raw_train_data
    if (load_dir is not None):
        predictions = test.load(spark, load_dir)
    else:
        start = time.time()
        predictions = test.fit(train_data)
        end = time.time()
        print(f'fit function spends {end - start}')
        if (save_dir is not None):
            predictions.save(spark, save_dir)

    results = {}

    train_metrics = predictions.score(train_data, k)
    for m, v in train_metrics.items():
        results[f'train/{m}'] = v

    if val_dir:
        val_metrics = predictions.score(spark.read.parquet(val_dir), k)
        for m, v in val_metrics.items():
            results[f'val/{m}'] = v

    if test_dir:
        test_metrics = predictions.score(spark.read.parquet(test_dir), k)
        for m, v in test_metrics.items():
            results[f'test/{m}'] = v

    print(json.dumps(results, indent=2))

if __name__ == "__main__":
    '''

    test of Class Bias
  use this command to run this script
  ```shell
  spark-submit --conf spark.executor.memory=4g bias.py \
   -tr hdfs:/user/${USER}/quarantini/${TrainFile} \
    -te hdfs:/user/${USER}/quarantini/${TestFile} \
     -du ${USER_DAMPING} -di ${ITEM_DAMPING}
  ```
  '''
    parser = argparse.ArgumentParser(description='popularity baseline model bias.py test')
    parser.add_argument('-tr', '--train', type=str, dest='train_dir', metavar='',
                        default=None, help='Train data directory')
    parser.add_argument('-te', '--test', type=str, dest='test_dir', metavar='',
                        default=None, help='Test data directory')
    parser.add_argument('-v', '--val', type=str, dest='val_dir', metavar='',
                        default=None, help='Val data directory')
    parser.add_argument('-du', '--user_dampling', type=int, dest='user_damping', metavar='',
                        default=None,
                        help='damping of bias model')
    parser.add_argument('-di', '--item_dampling', type=int, dest='item_damping', metavar='',
                        default=None,
                        help='item damping of bias model')
    parser.add_argument('-k', '--k', type=int, dest='k', metavar='',
                        default=None,
                        help='top k recommendation')
    parser.add_argument('-l', '--load', type=str, dest='load_dir', metavar='',
                        default=None,
                        help='load file directory')
    parser.add_argument('-s', '--save', type=str, dest='save_dir', metavar='',
                        default=None,
                        help='save  file directory')
    parser.add_argument('-r', '--rating', type=int, dest='rating', metavar='',
                        default=None,
                        help='transfer to rating or not 1 for ture')
    args = parser.parse_args()

    spark = SparkSession.builder.appName('bias_test').config('spark.blacklist.enabled', False).getOrCreate()

    damping = (args.user_damping, args.item_damping)

    transferrate = True if args.rating == 1 else False

    main(spark=spark, train_dir=args.train_dir, test_dir=args.test_dir, val_dir=args.val_dir, damping=damping, k=args.k,
         save_dir=args.save_dir, load_dir=args.load_dir, torating=transferrate)