"""
Changing storage values
"""
import json
import math
import re
import traceback
from datetime import datetime, timedelta

import requests
from matplotlib import pyplot as plt

from .command_custom import DwgbCmdConst, DwgbCmdCustom
from ..classes import DwgbDatabase, DwgbTransport, DwgbMessage, DwgbStorage

class DwgbCmdAdminStorage(DwgbCmdCustom):
    """ Администрирование хранилища """

    # Имя файла плоттера
    __PLOT_IMAGE = "./storagecost.png"

    #: Добавление элемента склада
    __QUERY_STORAGE_ADD = "INSERT INTO dwgb_storages (owner, item) VALUES (%(owner)s, %(item)s) ON CONFLICT DO NOTHING"

    #: Настройка элемента склада
    __QUERY_STORAGE_SET = "UPDATE dwgb_storages SET {0} WHERE owner=%(owner)s AND item=%(item)s"

    #: Удаление позиции
    __QUERY_STORAGE_DEL = "DELETE FROM dwgb_storages WHERE owner=%(owner)s AND item=%(item)s"

    def __init__(self, database: DwgbDatabase, transport: DwgbTransport):
        """ Конструктор """
        super().__init__(database, transport)
        self.date = datetime.min
        self.regItem = self.getRegex(r"(?:^склад (\d+)?\s*предмет ([\(\)\w|\s]+))")
        self.regDelete = self.getRegex(r"^склад (\d+)?\s*удалить (\D+)")
        self.regItems = self.getRegex(r"(?: -(\S+) (\S+))")
        self.regPercent = self.getRegex(r"^склад процент (\d+) (\d+)")
        self.regReload = self.getRegex(r"^склад обновить")
        self.regInfo = self.getRegex(r"^склад цену(.+)?")
        self.regSave = self.getRegex(r"^(хорошо|\d+)")
        self.regBag = self.getRegex(r"^золота - \d+\.")
        self.regInventory = self.getRegex(r"^(.+?) - (\d+)\.$")
        self.message = None

    def work(self, message: DwgbMessage):
        """ Обработка выражения """
        if datetime.today() > self.date:
            self.setcostchange(message)
        # Самопроверка инвентаря
        if (message.user == self._GAME_BOT_ID) and (self.regBag.match(message.text)):
            return self.rebag(message)
        # Auth
        if (message.user != 384297286) and (message.user != 66313242) and (message.user != 38752464):
            return False
        # Сохранение цены
        tmp_match = self.regSave.match(message.text)
        if tmp_match:
            return self.save(tmp_match, message)
        # Удаление позиции
        tmp_match = self.regDelete.match(message.text)
        if tmp_match:
            return self.delete(tmp_match, message)
        # Просмотр просрочки
        tmp_match = self.regInfo.match(message.text)
        if tmp_match:
            return self.getInfo(tmp_match, message)
        # Перезагрузка склада
        tmp_match = self.regReload.match(message.text)
        if tmp_match:
            return self.reloadStorages(message)
        # Установка скидки
        tmp_match = self.regPercent.match(message.text)
        if tmp_match:
            return self.percent(tmp_match, message)
        # Проверка наличия предмета для обновления
        tmp_match = self.regItem.match(message.text)
        if tmp_match is None:
            return False
        # Поиск всех параметров
        tmp_raw = self.regItems.findall(message.text)
        if tmp_raw is None:
            return True
        # Проверим владельца
        tmp_owner = tmp_match[1]
        if tmp_owner is None:
            tmp_owner = self.transport.getOwnerId()
        # Определим имя предмета
        tmp_name = tmp_match[2].strip().lower()
        tmp_params = []
        # Переберем все поля
        for tmp_row in tmp_raw:
            self.read(tmp_row, tmp_params)
        # Проверим
        if not tmp_params:
            return True
        # Запишем
        tmp_value = ",".join(tmp_params)
        self.database.exec(self.__QUERY_STORAGE_ADD, {"owner": tmp_owner, "item": tmp_name})
        self.database.exec(self.__QUERY_STORAGE_SET.format(tmp_value), {"owner": tmp_owner, "item": tmp_name})
        # Перезагрузим
        self.reloadStorages()
        # Ответим
        self.transport.writeChannel("Сохранено", message, True)
        return True

    def read(self, data: list, params: list):
        """ Чтение параметров """
        tmp_field = data[0]
        tmp_value = data[1]
        # Лимит предметов
        if tmp_field == "лим":
            params.append("maxlimit=%s" % int(tmp_value))
        elif tmp_field == "цена":
            params.append("cost=%s" % int(tmp_value))
            params.append("date=now()")
        elif tmp_field == "кол":
            params.append("value=%s" % int(tmp_value))
        elif tmp_field == "сток":
            params.append("trade=%s" % int(tmp_value))
        elif tmp_field == "доп":
            params.append("valueex=%s" % int(tmp_value))
        elif tmp_field == "код":
            params.append("code=%s" % int(tmp_value))
        elif tmp_field == "иконка":
            params.append("icon='%s'" % tmp_value)
        elif tmp_field == "тег":
            params.append("short='%s'" % tmp_value)
        return True

    def save(self, match: list, message: DwgbMessage):
        """ Сохранение прошлой цены """
        if not DwgbCmdConst.ITEM:
            return False
        # Определим тип
        if str(match[1]).lower() == "хорошо":
            tmp_cost = str(DwgbCmdConst.ITEM.average)
        else:
            tmp_cost = str(match[1])
        self.setcostdb(tmp_cost)
        # Ответим
        self.transport.writeChannel("Сохранено %s" % tmp_cost, message, True)
        # Вернем
        return True

    def percent(self, match: list, message: DwgbMessage):
        """ Установка процента """
        DwgbCmdConst.PERCENT_BUY = int(match[1]) / 100
        DwgbCmdConst.PERCENT_SELL = int(match[2]) / 100
        # Ответим
        self.transport.writeChannel("Установлено скупка %s%% продажа %s%% " % (int(match[1]), int(match[2])), message, True)
        return True

    def delete(self, match: list, message: DwgbMessage):
        """ Удаление позиции """
        tmpOwner = match[1]
        if tmpOwner is None:
            tmpOwner = self.transport.getOwnerId()
        # Удалим
        self.database.exec(self.__QUERY_STORAGE_DEL, {"owner": tmpOwner, "item": match[2].strip().lower()})
        # Перезагрузим
        self.reloadStorages()
        # Ответим
        self.transport.writeChannel("Удалено %s для %s" % (match[2], tmpOwner), message, True)
        return True

    def getInfo(self, match: list, message: DwgbMessage):
        """ Отображение цен """
        DwgbCmdConst.ITEM = None
        if match[1]:
            tmp_item = str(match[1]).lower().strip()
            for tmpItem, tmp_storage in DwgbCmdConst.STORE_DATA.items():
                if (tmp_item == tmpItem) or (tmp_item == tmp_storage.short):
                    DwgbCmdConst.ITEM = tmp_storage
                    break
        else:
            self.setcostlast()
        # Нет совпадения
        if not DwgbCmdConst.ITEM:
            self.transport.writeChannel("Нет записи в реестре", message, True)
            return True
        # Отправим
        self.setcostgraph(message, True)
        # Не удалось совершить операцию
        return True

    def setcostgraph(self, message: DwgbMessage, showgraph: bool):
        """ View a graph of cost """
        tmp_url = self._API_URL % (self._ACT_TYPE_ITEM % DwgbCmdConst.ITEM.code, self.transport.api)
        try:
            tmp_response = requests.post(tmp_url, headers=self.apiHeaders())
            tmp_match = re.search("graph_data = (.+?);", tmp_response.text)
            if not tmp_match:
                self.transport.writeChannel("Нет данных для %s" % DwgbCmdConst.ITEM.id, message, True)
                return True
            tmp_params = json.loads(tmp_match[1])
            tmp_label = []
            tmp_data = []
            for tmp_param in tmp_params:
                tmp_label.append(datetime.fromtimestamp(tmp_param[0]).strftime('%H:%M'))
                tmp_data.append(tmp_param[1])
                DwgbCmdConst.ITEM.average += tmp_param[1]
            DwgbCmdConst.ITEM.average //= len(tmp_params)
            # Сейв и отправка
            if showgraph:
                plt.plot(tmp_label, tmp_data, "o-", markersize=4)
                plt.xticks(rotation=90)
                plt.rc("grid", lw=0.2)
                plt.grid(True)
                plt.savefig(self.__PLOT_IMAGE)
                plt.cla()
                self.transport.writeChannel("%s%s\nСредняя: %s, в базе: %s, сток: %s, срок: %s" % (DwgbCmdConst.ITEM.icon, DwgbCmdConst.ITEM.id.capitalize(), DwgbCmdConst.ITEM.average, DwgbCmdConst.ITEM.cost, DwgbCmdConst.ITEM.trade, (datetime.today() - DwgbCmdConst.ITEM.date).days), message, False, 120, self.__PLOT_IMAGE)
        except Exception as e:
            print("Read failed %s %s" % (e, traceback.format_exc().replace("\n", " ")))

    def setcostdb(self, cost: str):
        """ Set cost of good """
        tmp_params = []
        tmp_name = DwgbCmdConst.ITEM.id
        self.read(["цена", cost], tmp_params)
        DwgbCmdConst.ITEM = None
        # Запишем
        tmp_value = ",".join(tmp_params)
        self.database.exec(self.__QUERY_STORAGE_SET.format(tmp_value), {"owner": self.transport.getOwnerId(), "item": tmp_name})
        # Перезагрузим
        self.reloadStorages()

    def setcostlast(self):
        """ Search a last day good """
        tmp_min = datetime.max
        for tmp_key, tmp_item in DwgbCmdConst.STORE_DATA.items():
            if tmp_item.icon != "📕" and tmp_item.icon != "📘":
                continue
            if tmp_item.date < tmp_min:
                tmp_min = tmp_item.date
                DwgbCmdConst.ITEM = tmp_item

    def setcosttime(self):
        """ Time to auto showing """
        return datetime.today() + timedelta(minutes=30)

    def setcostchange(self, message: DwgbMessage):
        """ Change cost of last time good """
        self.date = self.setcosttime()
        # Установим новую цену
        self.setcostlast()
        self.setcostgraph(message, False)
        # Проверим цену
        tmp_item = DwgbCmdConst.ITEM
        if tmp_item.average <= 0:
            self.setcostdb(DwgbCmdConst.ITEM.cost)
            DwgbCmdConst.ITEM = None
            return self.transport.writeChannel("Аукцион недоступен для %s%s" % (tmp_item.icon, tmp_item.id.capitalize()), message, False)
        # Цена
        tmp_cost = str(tmp_item.average)
        self.setcostdb(tmp_cost)
        # Ответим
        self.transport.writeChannel("Установлено 🌕%s для %s%s" % (tmp_cost, tmp_item.icon, tmp_item.id.capitalize()), message, False)
        # Запросим инвентарь
        self.loadbag(message)

    def loadbag(self, message: DwgbMessage):
        """ Загрузка сумки для сверки значений """
        self.message = DwgbMessage()
        self.message.channel = self._GAME_BOT_ID
        self.transport.writeChannel("Мой инвентарь", self.message, False)
        # Сохраним для приема
        self.message.channel = message.channel

    def rebag(self, message: DwgbMessage):
        """ Проверка предметов """
        tmp_bags = self.regInventory.findall(message.text)
        tmp_item: DwgbStorage
        tmp_key: str
        tmp_dict = {}
        # Соберем с регулярки
        for tmp_bag in tmp_bags:
            tmp_dict[str(tmp_bag[0]).lower()] = int(tmp_bag[1])
        # Проверим совпадение
        for tmp_key, tmp_item in DwgbCmdConst.STORE_DATA.items():
            # Обработаем простой товар
            if tmp_key == self._ITEM_SHARDS:
                tmp_find = "осколки сердца"
            else:
                tmp_find = tmp_key
            tmp_book = "книга - " + tmp_find
            # Поищем
            if tmp_find in tmp_dict:
                tmp_count = tmp_dict[tmp_find]
            elif tmp_book in tmp_dict:
                tmp_count = tmp_dict[tmp_book]
            else:
                tmp_count = 0
            # Установим
            if tmp_item.count != tmp_count:
                self.setStorage(0, tmp_key, -tmp_item.count + tmp_count)
                self.transport.writeChannel("🐼Восстановлено количество %s для %s%s" % (tmp_count, tmp_item.icon, tmp_item.id.capitalize()), self.message, False)
            # Страница
            tmp_page = "страница - " + tmp_key
            if tmp_page in tmp_dict:
                tmp_count = math.trunc(tmp_dict[tmp_page] / 5)
            else:
                tmp_count = 0
            # Сохраним
            if tmp_item.valueex != tmp_count:
                self.setStorage(0, tmp_key, -tmp_item.valueex + tmp_count, -tmp_item.valueex + tmp_count)
                self.transport.writeChannel("🐼Восстановлены страницы %s для %s%s" % (tmp_count, tmp_item.icon, tmp_item.id.capitalize()), self.message, False)
        # Все хорошо
        return True


import numpy as np
from scipy.signal import fftconvolve
from skimage.measure import block_reduce
from math import ceil
from sklearn import datasets

"""
    Classes for different types of layer for a CNN
"""

class ConvLayer():
    """
    Convolutional layer class
    """
    def __init__(self, n_filters, kernel_size, eta = 0.0001, activation='linear', input_shape=(28, 28, 1), padding='same'):
        self.a_in = None
        np.random.seed(100)

        # Initialize filters
        self.filters = self.initialize_filter(f_size=[n_filters, kernel_size[0], kernel_size[1]])
        self.n_filters = n_filters
        self.kernel_size = kernel_size[0]
        self.biases = np.zeros(n_filters)

        self.out = None
        self.z = []
        self.activation = activation

        # Learning rate
        self.eta = eta

    def feed_forward(self, images):
        """
        Feed forward for convolution layer
        :param images: input matrices/images
        :return: input convolved with the filters in convolution layer
        """
        self.a_in = images
        n_images, img_size, _ = np.shape(images)

        stride = 1
        out_img_size = int((img_size-self.kernel_size)/stride + 1)
        self.out = np.zeros(shape=[n_images*self.n_filters, out_img_size, out_img_size])
        self.z = []

        out_nr = 0

        for img_nr in range(n_images):
            image = self.a_in[img_nr, :, :]
            for filter_nr, filter in enumerate(self.filters):
                z = self.convolution2D(image, filter, self.biases[filter_nr])
                self.z.append(self.convolution2D(image, filter, self.biases[filter_nr]))
                self.out[out_nr, :, :] = self.activation_func(z)
                out_nr += 1

        return self.out

    def activation_func(self, a):
        """
        ReLU activation function
        """
        a[a <= 0] = 0
        return a

    def convolution2D(self, image, filter, bias, stride=1, padding=0):
        '''
        Convolution of 'filter' over 'image' using stride length 'stride'
        Param1: image, given as 2D np.array
        Param2: filter, given as 2D np.array
        Param3: bias, given as float
        Param4: stride length, given as integer
        Return: 2D array of convolved image
        '''

        h_filter, _ = filter.shape  # get the filter dimensions

        if padding > 0:
            image = np.pad(image, pad_width=padding, mode='constant')
        in_dim, _ = image.shape  # image dimensions (NB image must be [NxN])

        out_dim = int(((in_dim - h_filter) / stride) + 1)  # output dimensions
        out = np.zeros((out_dim, out_dim))  # create the matrix to hold the values of the convolution operation

        # convolve each filter over the image
        # Start at y=0
        curr_y = out_y = 0
        # move filter vertically across the image
        while curr_y + h_filter <= in_dim:
            curr_x = out_x = 0
            # move filter horizontally across the image
            while curr_x + h_filter <= in_dim:
                # perform the convolution operation and add the bias
                out[out_y, out_x] = np.sum(filter * image[curr_y:curr_y + h_filter, curr_x:curr_x + h_filter]) + bias
                curr_x += stride
                out_x += 1
            curr_y += stride
            out_y += 1
        return out

    def softmax(self, raw_preds):
        '''
        pass raw predictions through softmax activation function
        Param1: raw_preds - np.array
        Return: np.array
        '''
        out = np.exp(raw_preds)  # exponentiate vector of raw predictions
        return out / np.sum(out)  # divide the exponentiated vector by its sum. All values in the output sum to 1.

    def initialize_filter(self, f_size, scale=1.0):
        """
        Initialize filters with random numbers
        """
        stddev = scale / np.sqrt(np.prod(f_size))
        return np.random.normal(loc=0, scale=stddev, size=f_size)

    def back_propagation(self, error):
        """
        Backpropagation in convolution layer
        :param error: error from layer L+1
        F = filter
        d_F = derivative with regards to filter
        d_X = error in input, input for backpropagation in layer L-1
        """
        error_out = np.zeros(shape=np.shape(self.a_in))
        n_images, _, _ = np.shape(self.a_in)

        # Backpropagate through activation function part
        for img_nr in range(n_images):
            image = self.a_in[img_nr, :, :]
            for filter_nr in range(len(self.filters)):
                prop_error = error[filter_nr, :, :]*self.d_activation(self.z[filter_nr])
                d_F = self.convolution2D(image, np.rot90(prop_error, 2), bias=0)

                # Update weights
                self.filters[filter_nr] += self.eta*d_F/np.shape(self.a_in)[0]
                self.biases[filter_nr] += self.eta*np.sum(prop_error)/np.shape(self.a_in)[0]

                error_out[img_nr, :, :] += self.convolution2D(prop_error, np.rot90(self.filters[filter_nr], 2), bias=0, padding=1)
        return error_out

    def d_activation(self, a):
        # Return ReLU derivative
        a[a <= 0] = 0
        a[a > 0] = 1
        return a

class MaxPoolLayer():
    """
    Max pool layer
    """
    def __init__(self, stride):
        self.a_in = None
        self.stride = stride
        self.a_out = None

    def feed_forward(self, a_in):
        """
        Max pooling of input a_in
        """
        self.a_in = a_in
        n_images, img_size, _ = np.shape(self.a_in)
        self.a_out = np.zeros(shape=[n_images, int(ceil(img_size/self.stride)), int(ceil(img_size/self.stride))])
        for img_nr in range(n_images):
            self.a_out[img_nr, :, :] = block_reduce(self.a_in[img_nr, :, :], (self.stride, self.stride), np.max, cval=-np.inf)

        return self.a_out

    def back_propagation(self, d_error):
        """
        Backpropagation on max pool layer
        :param d_error: error from subsequent layer
        :return: error of input to max pool layer
        """
        # Pass error to pixel with largest value
        e_i = 0
        e_j = 0
        i = 0
        j = 0

        d_p = np.zeros(self.a_in.shape)
        for img_nr in range(np.shape(self.a_in)[0]):
            while i + self.stride <= np.shape(d_p)[1]:
                e_j = 0
                j = 0

                while j + self.stride <= np.shape(d_p)[2]:
                    block = self.a_in[img_nr, i:i+self.stride, j:j+self.stride]
                    x, y = np.unravel_index(block.argmax(), [self.stride, self.stride])
                    d_p[img_nr, x+i, y+j] = d_error[img_nr, e_i, e_j]
                    e_j += 1
                    j += self.stride

                e_i += 1
                i += self.stride

        return d_p

class FullyConnectedLayer:
    """
    Fully connected layer class
    """
    def __init__(self, n_categories, n_images, eta=0.001, activation='softmax'):
        # Input
        self.a_in = None

        # Vectorized
        self.S = None

        # Weights
        self.weights = None
        self.bias = np.random.randn(n_categories)
        self.n_categories = n_categories
        self.n_images = n_images
        self.activation = activation
        self.out = None

        # Learning rate
        self.eta = eta

    def update_images(self, n_images):
        """
        Change nr of outputs
        """
        self.n_images = n_images

    def new_shape(self, a):
        """
        Vectorize input to FC layer
        """
        # Vectorize step
        lengde, size, size = np.shape(a)
        per_image = int(lengde / self.n_images)

        reshaped = np.zeros(shape=[self.n_images, per_image*size*size])

        count = 0
        img_count = per_image

        for img in range(self.n_images):
            vec = np.zeros(per_image*size*size)
            pos = 0
            while count < img_count:
                vec[pos:pos + size*size] = (np.ravel(a[count].T))
                count += 1
                pos += size*size
            reshaped[img, :] = vec
            img_count += per_image
        return reshaped

    def reshape_back(self, a):
        """
        Undo vectorization
        """
        out = np.zeros(np.shape(self.a_in))
        length, size, size = np.shape(self.a_in)

        l = 0
        for i in range(np.shape(a)[0]):
            pos = 0
            while pos < np.shape(a)[1]:
                out[l, :, :] = a[i, pos:pos+size*size].reshape((size, size)).T
                pos += size*size
                l += 1

        return out

    def feed_forward(self, a_in):
        """
        Feed forward step in FC layer
        """
        # Vectorize step
        self.a_in = a_in
        self.S = self.new_shape(a_in)

        if self.weights is None:
            # initialize weights
            self.weights = np.random.randn(self.n_categories, np.shape(self.S)[1])

        self.out = self.activation_function(np.matmul(self.S, self.weights.T) + self.bias)
        return self.out

    def activation_function(self, a):

        if self.activation == 'softmax':
            return np.exp(a) / (np.exp(a).sum(axis=1))[:, None]

    def back_propagation(self, error):
        """
        Backpropagation of Fully Connected layer
        :param error: Error in final output w.r.t softmax
        :return: error in input to FC layer
        """
        # Error w.r.t weights
        w_d = np.matmul(error.T, self.S)
        b_d = np.sum(error)/len(error)

        # Calculate error in input
        d_S = np.matmul(error, self.weights)

        # Reshape
        d_a_in = self.reshape_back(d_S)

        # Update weights & bias
        self.weights -= self.eta*w_d/np.shape(error)[0]
        #print(self.weights)
        self.bias -= self.eta*b_d/np.shape(error)[0]

        return d_a_in


from dbutils.panama import *
import pandas as pd
from sqlalchemy import create_engine

roll_df = pd.read_csv("admin/roll_history.csv", dtype={'CARVER':str, 'PRICE_CONTRACT': str} )
#print(roll_df)
symbols_sr = roll_df['CARVER'].copy()
symbols_sr.drop_duplicates(inplace=True)
symbols_df = pd.DataFrame(symbols_sr).sort_values('CARVER')
engine = create_engine('mysql+pymysql://root:admin@0.0.0.0/pkdemo')
market = "EDOLLAR"
update_data_tbls(engine, market)


#!/usr/bin/env python3

import sys

try:
    salary = int(sys.argv[1])
except:
    print('Parameter Error')

need_tax = salary - 3500

if need_tax < 0:
    tax_rate = 0
    dute = 0
elif need_tax < 1500:
    tax_rate = 0.03
    dute = 0
elif need_tax < 4500:
    tax_rate = 0.1
    dute = 105
elif need_tax < 9000:
    tax_rate = 0.2
    dute = 555
elif need_tax < 35000:
    tax_rate = 0.25
    dute = 1005
elif need_tax < 55000:
    tax_rate = 0.3
    dute = 2755
elif need_tax < 80000:
    tax_rate = 0.35
    dute= 5505
else:
    tax_rate = 0.45
    dute = 13505

tax = need_tax * tax_rate - dute
print(format(tax,".2f"))


#!/usr/bin/env python
import json
import sys
import math
import random

def gen_g(w, symmetric):
    t = random.randrange(0, 3 if symmetric else 5)
    if t == 0: # center one
        w1 = random.randrange(1, w // 3)
        return [[0] * w1 + [1] * (w - 2 * w1) + [0] * w1]
    elif t == 1: # double side
        w1 = random.randrange(2, w // 3)
        w2 = (w - w1) // 2
        return [[1] * w2 + [0] * w1 + [1] * (w - w1 - w2)]
    elif t == 2: # random two holes
        ret = [1] * w
        s1 = random.randrange(1, w - 3)
        if symmetric:
            s2 = w - 2 - s1
        else:
            s2 = random.randrange(1, w - 3)
        ret[s1] = 0
        ret[s1 + 1] = 0
        ret[s2] = 0
        ret[s2 + 1] = 0
        return [ret]
    elif t == 3: # right one
        w1 = random.randrange(2, w // 3)
        return [[0] * w1 + [1] * (w - w1)]
    elif t == 4: # left one
        w1 = random.randrange(2, w // 3)
        return [[1] * (w - w1) + [0] * w1]
    else: # random size 2
        s = random.randrange(1, w - 3)
        return [[1] * s + [0] * 2 + [1] * (w - s - 2)]

def gen_pond(w, symmetric):
    d = random.randrange(1, 5)
    m = [[2] * w for i in range(d)]
    r = random.random() * 0.3
    r = r * (0.5 if symmetric else 1.0)
    for i in range(int(r * d * w)):
        y = random.randrange(0, d)
        x = random.randrange(0, w)
        m[y][x] = 0
        if symmetric:
            m[y][w - 1 - x] = 0
    return m

def gen_one_rocks(w, symmetric):
    d = random.randrange(1, 5)
    m = [[0] * w for i in range(d)]
    r = 0.1 + random.random() * 0.8
    r = r * (0.5 if symmetric else 1.0)
    for i in range(int(r * d * w)):
        y = random.randrange(0, d)
        x = random.randrange(0, w)
        m[y][x] = 1
        if symmetric:
            m[y][w - 1 - x] = 1
    return m + [[0] * w]

# dy = abs(

def make_shape(w, h):
    shape = [[True] * w for y in range(h)]
    for dy in (-1, 1):
        y1 = h // 2 + dy
        xlow, xhigh = 0, w
        while y1 >= 0 and y1 < h:
            d = abs(y1 - h // 2) / (h - h // 2)
            xlow += int(0.5 + w * random.random() * math.sqrt(1 - d * d) / 2.0)
            xhigh -= int(0.5 + w * random.random() * math.sqrt(1 - d * d) / 2.0)
            for x in range(0, min(w, xlow)):
                shape[y1][x] = 0
            for x in range(max(0, xhigh), w):
                shape[y1][x] = 0
            y1 += dy
    return shape

def put_shape(m, shape, sx, sy, color, symmetric):
    sw, sh = len(shape[0]), len(shape)
    w, h = len(m[0]), len(m)
    for y in range(sh):
        y1 = sy + y
        if y1 < 0 or y1 >= h: continue
        for x in range(sw):
            x1 = sx + x
            if x1 < 0 or x1 >= w: continue
            if not shape[y][x]: continue
            m[y1][x1] = color
            if symmetric:
                m[y1][len(m[y1]) - 1 - x1] = color

def gen_areas(w, symmetric):
    h = random.randrange(3, 10)
    m = [[0] * w for i in range(h)]
    n_r = random.randrange(2, 5)
    if symmetric:
        n_r = (n_r + 1) // 2
    for i in range(n_r):
        shape = make_shape(random.randrange(w // 6, w // 2 ),
                           random.randrange(2, h + 1))
        sw, sh = len(shape[0]), len(shape)
        sx = random.randrange(-sw // 4, w - sw // 4)
        sy = random.randrange(-sh // 4, h - sh // 4)
        put_shape(m, shape, sx, sy, 1, symmetric)
    n_p = random.randrange(0, 4)
    for i in range(n_r):
        shape = make_shape(random.randrange(w // 8, w // 4 ),
                           random.randrange(2, h + 1))
        sw, sh = len(shape[0]), len(shape)
        sx = random.randrange(-sw // 4, w - sw // 4)
        sy = random.randrange(-sh // 4, h - sh // 4)
        put_shape(m, shape, sx, sy, 2, symmetric)
    return m + [[0] * w]

def paint_block(x, y, w, d, block, visited):
    if x < 0 or w <= x or y < 0 or d <= y:
        return
    if block[y][x] == 1 or visited[y][x]:
        return
    visited[y][x] = True
    for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        paint_block(x + dx, y + dy, w, d, block, visited)

def check_block(m, w, d):
    visited = [[False] * w for i in range(d)]
#    print(m, visited, file=sys.stderr)
    for x in range(w):
        paint_block(x, 0, w, d, m, visited)
    for x in range(w):
        if not visited[d - 1][x]:
            return False
    for y in range(1, d - 1):
        for x in range(w):
            if not visited[y][x]:
                m[y][x] = 1
    return True

def next_block(m, w, symmetric):
    while True:
        sym = symmetric or (random.random() < 0.5)
        r1 = random.randrange(0, 4)
        # r1 = 2
        if r1 == 0:
            block = gen_pond(w, sym)
        elif r1 == 1:
            block = gen_g(w, sym) + [[0] * w]
        elif r1 == 2:
            block = gen_areas(w, sym)
        else:
            block = gen_one_rocks(w, sym)

        if check_block(block, w, len(block)):
            return block

def make_course(w, l, v, sym):
    results = {}
    results['filetype'] = 'race course 2018'
    results['width'] = w
    results['length'] = l
    results['vision'] = v
    m = [[0] * w]
    while True:
        block = next_block(m, w, sym)
        if len(m) + len(block) > l:
            m += [[0] * w] * (l - len(m))
            break
        else:
            m += block
    squares = sum(m, [])
    results['squares'] = squares
    tt = 120
    sl = l
    x0 = int(math.floor(w / 3))
    x1 = int(math.floor(w * 2 / 3))
    results['thinkTime'] = tt
    results['stepLimit'] = sl
    results['x0'] = x0
    results['x1'] = x1
    return results

wmin = 10
wmax = 30
lmin = 40
lmax = 200
vmin = 3
vmax = 20
width = int(sys.argv[1]) if len(sys.argv) > 1 else random.randrange(wmin, wmax + 1)
length = int(sys.argv[2]) if len(sys.argv) > 2 else random.randrange(lmin, lmax + 1)
vision = int(sys.argv[3]) if len(sys.argv) > 3 else random.randrange(vmin, vmax + 1)
sym = random.random() < 0.3
print('w = %s, l = %s, v = %s' % (width, length, vision), file=sys.stderr)
print(json.dumps(make_course(width, length, vision, sym), separators=(',', ':')))


# coding=utf-8

from ha import *

# A View describes how the value of a sensor's state should be displayed.  It contains a mapping of
# state values to display values, an optional format string, and an optional transform function.
# Reverse mappings of display values to state values may also be specified.
class View(object):
    def __init__(self, values={None:"--", 0:"Off", 1:"On"}, format="%s", transform=None, setValues=None, toggle=False):
        self.values = values
        self.format = format
        self.transform = transform
        if setValues == None:
            self.setValues = {0:"Off", 1:"On"}
        else:
            self.setValues = OrderedDict(setValues) # preserve the order of set values for display purposes
        self.toggle = toggle

    # Return the printable string value for the state of the sensor
    def getViewState(self, sensor, state=None):
        if sensor != None:
            state = sensor.getState()
        try:    # run it through the transformation function
            state = self.transform(state)
        except:
            pass
        try:    # look it up in the values table
            return self.format % (self.values[state])
        except:
            if state != None:
                try:    # apply the format
                    return self.format % (state)
                except: # worst case, return the string of the state
                        return str(state)
            else:   # None means sensor isn't reporting
                return "--"

    # Set the state of the control to the state value corresponding to the specified display value
    def setViewState(self, control, dispValue):
        try:
            value = list(self.setValues.keys())[list(self.setValues.values()).index(dispValue)]
            if dispValue in ["-", "v", "+", "^"]:   # increment or decrement current state by the value
                debug("debugState", "View", "setViewState", "incrementing", control.name, str(value))
                newState = control.getState() + value
                if newState < 0:                    # don't allow negative states
                    newState =  0
                control.setState(newState)
            else:
                debug("debugState", "View", "setViewState", "setting", control.name, str(value))                                   # set it to the value
                control.setState(value)
        except ValueError:                      # display value isn't in the list of valid states for the control
            debug("debugState", "View", "setViewState", "setting", control.name, str(dispValue))
            try:                                # attempt to use it as a number
                control.setState(int(dispValue))
            except ValueError:                  # use the value that was passed
                control.setState(dispValue)

# Dictionary of views keyed by sensor type
class ViewDict(dict):
    def __init__(self, views):
        dict.__init__(self, views)
        self.__setitem__("", View())    # default View

    # Return the printable string value for the state of the sensor
    def getViewState(self, sensor=None, type=None, state=None):
        try:
            if sensor:
                return self.__getitem__(sensor.type).getViewState(sensor)
            else:
                return self.__getitem__(type).getViewState(None, state)
        except KeyError:
            if sensor:
                return self.__getitem__("").getViewState(sensor)
            else:
                return self.__getitem__("").getViewState(None, state)

    # Return the printable string values for the states that can be set on the control
    def getSetValues(self, control):
        try:
            return list(self.__getitem__(control.type).setValues.values())
        except KeyError:
            return list(self.__getitem__("").setValues.values())

    # Set the state of the control to the state value corresponding to the specified display value
    def setViewState(self, control, value):
        try:
            return self.__getitem__(control.type).setViewState(control, value)
        except KeyError:
            return self.__getitem__("").setViewState(control, value)

# transform functions
def intFormat(value):
    return int(value+.5)

def ctofFormat(value):
    return tempFormat(value*9/5+32)

def kiloFormat(value):
    return (value + 0.0)/1000.0

def megaFormat(value):
    return (value + 0.0)/1000000.0

def negativeZeroFormat(value):
    return value + 0.0

def seqCountdownFormat(resource):
    pass

def tempFormat(value):
    if value == 0:
        return "--"
    else:
        return "%d F"%(int(value+.5))

def timeFormat(value):
    return "%d:%02d"%(int(value)/60, value%60)

def secsFormat(value):
    (m, s) = divmod(value, 60)
    (h, m) = divmod(m, 60)
    return "%d:%02d:%02d" % (h, m, s)

def latFormat(value):
    return "%9.5f %s" % (abs(value), "N" if value > 0.0 else "S")

def longFormat(value):
    return "%9.5f %s" % (abs(value), "E" if value > 0.0 else "W")

def hdgFormat(value):
    dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
    direction = dirs[int((value+11.25)%360/22.5)]
    return "%03d %s" % (int(value), direction)

def deciVoltsFormat(value):
    return value/10.

# view definitions
views = ViewDict(  {"none": View(),
#         "tempC": View({}, "%d °", ctofFormat),
#         "tempF": View({}, "%d °", tempFormat),
         "tempC": View({}, "%d F", ctofFormat),
         "tempF": View({}, "%d F", tempFormat),
         "tempFControl": View({}, "%d F", tempFormat, OrderedDict([(-1,"v"), (+1,"^")])),
         "timeControl": View({}, "%d:%d", timeFormat, OrderedDict([(-60,"v"), (+60,"^")])),
         "audioVolume": View({}, "%d%%", None, OrderedDict([(-5,"v"), (+5,"^")])),
         "audioMute": View({0:"X", 1:"*"}, "%s", None, {0:"*", 1:"X"}, True),
         "wifi": View({0:"Off", 1:"On"}, "%s", None, {0:"On", 1:"Off"}, True),
         "in": View({}, "%5.2f in"),
         "barometer": View({}, "%5.2f in"),
         "humidity": View({}, "%d %%"),
         "service": View({0:"Down", 1:"Up"}, "%s"),
         "light": View({0:"Off", 1:"On"}, "%s", None, {0:"Off", 1:"On"}),
         "plug": View({0:"Off", 1:"On"}, "%s", None, {0:"Off", 1:"On"}),
         "nightLight": View({0:"Off", 1:"On", 2:"Sleep", 10:"Sleep", 30:"On", 100:"On"}, "%s", None, OrderedDict([(2,"Sleep"), (1,"On")])),
         "led": View({0:"Off", 1:"On", 2:"Flickr"}, "%s", None, OrderedDict([(0,"Off"), (1,"On"), (2,"Flickr")])),
         "dimmer": View(OrderedDict([(0,"Off"), (10,"Lo"), (30,"Med"), (60,"Hi"), (100,"On")]), "%s", None, OrderedDict([(0,"Off"), (10,"Lo"),
                                                                                (30,"Med"), (60,"Hi"),
                                                                                (100,"On")])),
         "motion": View({0:"Off", 1:"Motion"}, "%s"),
         "hotwater": View({0:"Off", 1:"On"}, "%s", None, {0:"Off", 1:"On"}),
         "door": View({0:"Closed", 1:"Open"}, "%s", None, {0:"Close", 1:"Open"}),
         "shade": View({None:"", 0:"Up", 1:"Down", 2:"Raising", 3:"Lowering"}, "%s", None, {0:"Up", 1:"Down"}),
         "spa": View({0:"Off", 1:"On", 2:"Starting", 3:"Warming", 4:"Standby", 5:"Stopping"}, "%s", None, {0:"Off", 1:"On", 4:"Stby"}),
         "poolValve": View({0:"Pool", 1:"Spa", 2:"Off", 4:"Moving"}, "%s", None, OrderedDict([(0,"Pool"), (1,"Spa"), (2,"Off")])),
         "valveMode": View({0:"Pool", 1:"Spa", 2:"Drain", 3:"Fill"}, "%s", None, OrderedDict([(0,"Pool"), (1,"Spa"), (2,"Drain"), (3,"Fill")])),
         "fire": View({0:"Out", 1:"Lit"}, "%s", None, OrderedDict([(0,"Douse"), (1,"Light")])),
         "pump": View({0:"Off", 1:"Lo", 2:"Med", 3:"Hi", 4:"Max"}, "%s", None, {0:"Off", 1:"Lo", 2:"Med", 3:"Hi", 4:"Max"}),
         "pumpSpeed": View({}, "%d RPM"),
         "pumpFlow": View({}, "%d GPM"),
         "cleaner": View({0:"Off", 1:"On", 2:"Ena"}, "%s", None, {0:"Off", 1:"On"}),
         "tempControl": View({0:"Off", 1:"Ena"}, "%s", None, {0:"Off", 1:"Ena"}),
         "thermostat": View({0:"Off", 1:"Heat", 2:"Cool", 3:"Fan", 4:"Auto"}, "%s", None, {0:"Off", 1:"Heat", 2:"Cool", 3:"Fan", 4:"Auto"}),
         "thermostatSensor": View({0:"Off", 1:"Heating", 2:"Cooling", 3:"Fan", 5:"Hold"}, "%s"),
         "cameraMode": View({0:"Still", 1:"Time", 2:"Video", 3:"Motion"}, "%s", None, {0:"Still", 1:"Time", 2:"Video", 3:"Motion"}),
         "cameraEnable": View({0:"Disabled", 1:"Enabled"}, "%s", None, {0:"Dis", 1:"Ena"}),
         "cameraRecord": View({0:"Stopped", 1:"Recording"}, "%s", None, {0:"Stop", 1:"Rec"}),
         "charger": View({0:"Off", 1:"Ready", 2:"Connected", 3:"Charging", 4:"Fault"}),
         "diagCode": View({}, "%d"),
         "Ft": View({}, "%d FT", intFormat),
         "MPH": View({}, "%d MPH", intFormat),
         "RPM": View({}, "%d RPM", intFormat),
         "Secs": View({}, "%s", secsFormat),
         "Lat": View({}, "%s", latFormat),
         "Long": View({}, "%s", longFormat),
         "Deg": View({}, "%s", hdgFormat),
         "nSats": View({}, "%d", intFormat),
         "power": View({}, "%d W", negativeZeroFormat),
         "KVA": View({}, "%7.3f KVA", kiloFormat),
         "KVAh": View({}, "%7.3f KVAh", kiloFormat),
         "W": View({}, "%7.1f W", negativeZeroFormat),
         "V": View({}, "%4.1f V", negativeZeroFormat),
         "A": View({}, "%6.3f A", negativeZeroFormat),
         "Ah": View({}, "%7.3f Ah", negativeZeroFormat),
         "KW": View({}, "%7.3f KW", kiloFormat),
         "KW-": View({}, "%7.3f KW", kiloFormat),
         "KWh": View({}, "%7.3f KWh", kiloFormat),
         "KWh-": View({}, "%7.3f KWh", kiloFormat),
         "MWh": View({}, "%7.3f MWh", megaFormat),
         "dBm": View({}, "%4.1f dBm"),
         "int": View({}, "%d", intFormat),
         "int2": View({}, "%02d", intFormat),
         "int3": View({}, "%03d", intFormat),
         "pct": View({}, "%3d %%"),
         "battery": View({}, "%3d %%"),
         "deciVolts": View({}, "%4.1f V", deciVoltsFormat),
         "chargeMode": View({0:"Disabled", 1:"Enabled", 2:"Bulk", 3:"Equalization", 4:"Absorbtion", 5:"Float", 6:"Constant"}, "%s"),
         "chargeSource": View({0:"Grid", 1:"Solar"}, "%s", None, {0:"Grid", 1:"Solar"}),
         "sequence": View({0:"Stopped", 1:"Running"}, "%s", None, {0:"Stop", 1:"Run"}),
         "task": View({0:"Disabled", 1:"Enabled"}, "%s", None, {0:"Dis", 1:"Ena"}),
         "tv": View({}, "%s", None, OrderedDict([("off", "Off"), ("mute", "Mute"), ("roku", "Roku"),
                                                 ("chrome", "Chrome"), ("iphone", "iPhone"),
                                                 ("hdmi", "HDMI"), ("broadcast", "Bcast"),
                                                 ("component", "Comp"), ("pc", "PC")]))
    })

# by default the UI will create a css class based on the state value. These types are the exceptions:
# types whose class does not depend on their value
staticTypes = ["time", "ampm", "date", "KVA", "W", "V", "A", "Ah", "KW", "KW-", "MW", "KWh", "KWh-", "KVAh", "sound", "select", "battery", "dBm", "tv"]
# temperatures
tempTypes = ["tempF", "tempFControl", "tempC", "spaTemp"]


from utils.strings_util import (
    convert_to_python_type,
    camel_case_to_snake_case,
    get_type_from_reference
)

response_models = {
    'base_bool_response': "base.Bool",
    'base_getUploadServer_response': "base.GetUploadServer",
    'base_ok_response': "base.Ok"
}

CLASSMETHOD_PATTERN = \
"""    async def {snake_name}(
        {args}
    ) -> {type}ResponseModel:
        {desc}
        params = self.get_set_params(locals())
        response = await self.api.request(\"{name}\", params)
        model = {type}Response
        return model(**response).response"""

class ObjectModel:
    def __init__(self, method_name: str = None, method: dict = None, **params):
        self.method = method
        self.method_name = method_name
        self.params = params

class Description(ObjectModel):
    def __str__(self):
        title = self.method.get(
            "description"
        ) or self.method_name + " method"

        description = '\n'.join(
            "\t\t:param %s: %s" % (param['name'], param.get("description", ''))
            for param in self.params['sorted_params']
        )
        if description:
            description = '\n' + description + '\n\t\t'
        return "\"\"\"%s%s\"\"\"\n" % (title, description)

class Annotation(ObjectModel):
    def __str__(self):
        items = self.params["items"]
        param_type = self.params["type"]
        param_annotate = convert_to_python_type(self.params['annotate'])

        if param_annotate == 'list' and items.get("$ref", items.get("type")):
            post_annotate = (
                get_type_from_reference(items["$ref"])
                if items.get("$ref") else
                items["type"]
            )
            param_annotate = "List[%s]" % convert_to_python_type(post_annotate)

        if param_type is False:
            return f"Optional[{param_annotate}] = None"
        return param_annotate

class ConvertToArgs(ObjectModel):
    def __str__(self):
        params = ['self']
        for param in self.params['sorted_params']:
            params.append(
                f"{param['name']}: " +
                str(Annotation(
                    annotate=param['type'],
                    type=param.get('required', False),
                    items=param.get("items", {})))
            )
        params.append('**kwargs')
        formatted = ', '.join(params)

        if len(formatted) >= 80:
            formatted = formatted.replace(', ', ',\n\t\t')

        return formatted

class MethodForm:
    def parse_return_type(m_name, type_response):
        category, name = m_name.split('.')
        method_name = f"{category}.{name[0].upper() + name[1:]}"
        return_type = type_response.split('/')[-1]
        return response_models.get(return_type, method_name)

    def costruct(**params):
        return CLASSMETHOD_PATTERN.format(**params)

class ClassForm:
    def __init__(self, classname, predproc = 'BaseCategory'):
        self.name = classname
        self.predproc = predproc
        self.constructed_methods = []

    def add_method(self, method_name, method):
        sorted_params = sorted(
            method.get('parameters', {}),
            key=lambda x: not x.get('required', False)
        )
        desc = Description(method_name, method, sorted_params=sorted_params)
        args = ConvertToArgs(sorted_params=sorted_params)
        return_type = MethodForm.parse_return_type(method_name, method['responses']['response']['$ref'])
        self.constructed_methods.append(
            MethodForm.costruct(
                name=method_name,
                snake_name=camel_case_to_snake_case(method_name.split('.')[1]),
                args=args,
                desc=desc,
                type=return_type
            )
        )

    def __str__(self):
        return (f"\n\n\nclass {self.name.capitalize()}Category({self.predproc}):\n" +
                "\n\n".join(self.constructed_methods)
            )


#coding=utf-8
#Memorycheck Ver1.1

import subprocess
import os
import time
import shutil
import threading

#定义设备连接状态
def DeviceStatus():
    global deviceArray
    deviceStatus=subprocess.Popen('adb devices',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    deviceIndexed=deviceStatus.stdout.read()
    deviceArray=deviceIndexed.split()
    return len(deviceArray)

#运行monkey
while(DeviceStatus()==4):
    print('设备未连接，请打开usb调试重新插入usb数据线连接设备')
    devices=False
    time.sleep(10)
if(DeviceStatus()==6):
    #设备连接成功，重启设备
    print(time.ctime()+'设备重启，请稍后')
    subprocess.Popen('adb reboot',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    time.sleep(90)
    #等待设备重启成功
    while(DeviceStatus()==4):
        print('等待adb连接')
        devices=False
        time.sleep(10)
    if(DeviceStatus()==6):
        #获取设备名称和版本号
        productName=os.popen('adb shell getprop ro.product.board').readline().strip('\n')
        swVersion=os.popen('adb shell getprop ro.gn.gnznvernumber').readline().strip('\n')
        #建result文件夹
        def createResultDir():
            resultpath=(".\Result")
            resultpathisExists=os.path.exists(resultpath)
            if not resultpathisExists:
                os.makedirs(resultpath)
            resultFolder=resultpath+os.path.sep+productName+os.path.sep+swVersion+os.path.sep+time.strftime("%Y-%m-%d",time.localtime())
            resultFolderIsExists=os.path.exists(resultFolder)
            if not resultFolderIsExists:
                os.makedirs(resultFolder)
            return resultFolder+os.path.sep

        #创建log文件夹
        def createadbLogDir():
            logpath=(".\Logs")
            logpathisExists=os.path.exists(logpath)
            if not logpathisExists:
                os.makedirs(logpath)
            logFolder=logpath+os.path.sep+productName+os.path.sep+swVersion+os.path.sep+time.strftime("%Y-%m-%d",time.localtime())
            logFolderIsExists=os.path.exists(logFolder)
            if not logFolderIsExists:
                os.makedirs(logFolder)
            return logFolder+os.path.sep
        #创建packageinfo存放文件夹
        def packagelistsDir():
            packagelistsPath=(".\Packagelists")
            packagelistsPathisExists=os.path.exists(packagelistsPath)
            if not packagelistsPathisExists:
                os.makedirs(packagelistsPath)
            packagelistsFolder=packagelistsPath+os.path.sep+productName+os.path.sep+swVersion
            packagelistsFolderIsExists=os.path.exists(packagelistsFolder)
            if not packagelistsFolderIsExists:
                os.makedirs(packagelistsFolder)
            return packagelistsFolder+os.path.sep
        #定义Monkey运行状态
        def MonkeyStatus():
            global monkeyArray
            monkeyStatus=subprocess.Popen('adb shell "ps | grep monkey"',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
            monkeyIndexed=monkeyStatus.stdout.read()
            monkeyArray=monkeyIndexed.split()
            return len(monkeyArray)

        #定义文件名称规则
        resultdir=createResultDir()
        adblogsdir=createadbLogDir()
        packagelistsdir=packagelistsDir()
        packagelistsfilename=packagelistsdir+productName+"_package_name_info.txt"

        #获取开机内存
        print(time.ctime()+'adb连接成功，正在获取测试前内存信息')
        subprocess.Popen('adb shell dumpsys meminfo > '+resultdir+'meminfo_before_test_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

        #连接设备，获取包名
        print(time.ctime()+'开始获取应用信息')
        os.system('adb install -r packageview.apk')
        os.system('adb shell am start -n com.gionee.packages/com.gionee.packages.MainActivity')
        os.system('adb pull /sdcard/packages_visual.txt '+packagelistsfilename)
        os.system('adb uninstall com.gionee.packages')
        print(time.ctime()+'应用信息获取成功，开始分析生成应用列表')

        #将包名导入到列表中
        openapplists=open(packagelistsfilename,'r')
        applists=openapplists.readlines()
        openapplists.close()
        applist=dict(zip(applists,applists))
        print(time.ctime()+'应用列表生成完毕，共'+str(len(applists))+'个应用')

        #开始执行不拆分测试
        testpackages=('')
        for line in applists:
            line=line.strip('\n')
            testpackages +=('-p '+line+' ')

        print(time.ctime()+'等待5分钟开始执行测试')
        time.sleep(300)
        print(time.ctime()+'开始执行monkey测试')
        subprocess.Popen('adb shell monkey -s 1 '+testpackages+'--throttle 500 --ignore-crashes --ignore-security-exceptions --ignore-timeouts --monitor-native-crashes -v -v 172800 > '+adblogsdir+'monkey_logs_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

        def monkeytest():
            while(DeviceStatus()==6):
                if(MonkeyStatus()==0):
                    print(time.ctime()+'monkey测试中断，重启monkey测试')
                    subprocess.Popen('adb shell monkey -s 1 '+testpackages+'--throttle 500 --ignore-crashes --ignore-security-exceptions --ignore-timeouts --monitor-native-crashes -v -v 172800 > '+adblogsdir+'monkey_logs_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
                    time.sleep(30)
                else:
                    print(time.ctime()+'monkey进程正常')
                    time.sleep(30)

        def memorycheckresult():
            while(DeviceStatus()==6):
                time.sleep(300)
                print(time.ctime()+'正在获取内存信息')
                subprocess.Popen('adb shell dumpsys meminfo > '+resultdir+'meminfo_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

        threads = []
        t1 = threading.Thread(target=monkeytest)
        threads.append(t1)
        t2 = threading.Thread(target=memorycheckresult)
        threads.append(t2)

        if __name__ == '__main__':
            for t in threads:
                t.setDaemon(True)
                t.start()

            t.join()

            print(time.ctime()+'测试结束')
            os.system('pause')

'''
    print(time.ctime()+'开始执行monkey测试')
        subprocess.Popen('adb shell monkey -s 1 '+testpackages+'--throttle 500 --ignore-crashes --ignore-security-exceptions --ignore-timeouts --monitor-native-crashes -v -v -v 172800 > '+adblogsdir+'monkey_logs_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
        while(DeviceStatus()==6):
            time.sleep(300)
            print(time.ctime()+'正在获取内存信息')
            subprocess.Popen('adb shell dumpsys meminfo > '+resultdir+'meminfo_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
            if(MonkeyStatus()==0):
                print(time.ctime()+'Monkey进程终止，测试停止')
                os.system('pause')
                break
'''

'''
    #开始执行单app拆分测试
    print('等待5分钟开始执行测试')
    time.sleep(300)
    print('开始执行monkey测试')
    for key in applist.keys():
        app = applist[key].split("\n")[0]
        print(time.ctime()+'正在测试应用的包名：'+app)
        os.system('adb shell monkey -s 1 -p '+app+' --throttle 500 --ignore-crashes --ignore-security-exceptions --ignore-timeouts -v -v 10000 > '+adblogsdir+app+'_monkey_logs_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt')
        while(DeviceStatus()==6):
            time.sleep(300)
            print(time.ctime()+'正在抓取内存信息')
            os.system('adb shell dumpsys meminfo > '+resultdir+'meminfo_'+time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())+'.txt')
            if(MonkeyStatus()==0):
                break
'''


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

from PIL import Image
import select
import v4l2capture
import numpy as np
import cv2
import time
import signal

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    # -- Finish Video
    out_uvc.release()
    video.close()
    cv2.destroyAllWindows()

# Open the video device.
video = v4l2capture.Video_device("/dev/video4")

# Suggest an image size to the device. The device may choose and
# return another size if it doesn't support the suggested one.
# size_x, size_y = video.set_format(1280, 1024)
size_x, size_y = video.set_format(1920, 1080)
print (size_x)
print(size_y)
# Create a buffer to store image data in. This must be done before
# calling 'start' if v4l2capture is compiled with libv4l2. Otherwise
# raises IOError.
video.create_buffers(1)

# Send the buffer to the device. Some devices require this to be done
# before calling 'start'.
video.queue_all_buffers()

# Start the device. This lights the LED if it's a camera that has one.
video.start()

# Wait for the device to fill the buffer.
select.select((video,), (), ())

fourcc_uvc = cv2.VideoWriter_fourcc('M','J','P','G')
uvc_fn = "uvc_test.avi"
fps = 15.0
out_uvc = cv2.VideoWriter(uvc_fn, fourcc_uvc, fps, (size_x, size_y), True)

signal.signal(signal.SIGINT, signal_handler)

# The rest is easy :-)
while True:
    try:
        time.sleep(1/fps)
        select.select((video,), (), ())
        image_data = video.read_and_queue()
        image = np.array(Image.frombytes("RGB", (size_x, size_y), image_data))
        out_uvc.write(image)
        cv2.imshow('frame', image)
        cv2.waitKey(1)
    except Exception as e:
        print(e)
        break

out_uvc.release()
video.close()

# def print_hi(name):
#     # Use a breakpoint in the code line below to debug your script.
#     print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.
#
#
# # Press the green button in the gutter to run the script.
# if __name__ == '__main__':
#     print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/


#
# @copyright@
# Copyright (c) 2006 - 2018 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt
# @rocks@
#

import stack.commands

class Command(stack.commands.HostArgumentProcessor,
	stack.commands.BoxArgumentProcessor, stack.commands.report.command):
	"""
	Create a report that describes the repository configuration file
	that should be put on hosts.

	<arg optional='0' type='string' name='host'>
	Host name of machine
	</arg>

	<example cmd='report host repo backend-0-0'>
	Create a report of the repository configuration file for backend-0-0.
	</example>
	"""

	def run(self, params, args):

		self.beginOutput()

		hosts = self.getHostnames(args)
		for host in hosts:
			osname = self.db.getHostOS(host)
			server = self.getHostAttr(host, 'Kickstart_PrivateAddress')

			if osname in [ 'redhat', 'sles' ]:
				self.runImplementation('repo', (host, server, osname))
			else:
				self.runImplementation(osname, (host, server))

		self.endOutput(padChar='', trimOwner=True)


import socket
server = socket.socket()
server.bind(("10.7.187.67",6666))
server.listen(1024)
print("开始监听")
while True:
    conversation,addr =server.accept()
    print(addr)
    with open("aa.html","r",encoding="utf-8")as f:
        message=f.read()
    conversation.send(message.encode("utf-8"))


# functions to run velocyto and scvelo
import numpy as np
import pandas as pd
#import velocyto as vcy
#import scvelo as scv
import scipy as scp
import matplotlib.pyplot as plt
from .moments import *
from anndata import AnnData

# code from scSLAM-seq repository
# vlm.ts: transition matrix?
# from velocitySlamSeq.slam_seq import simulate_mul

def vlm_to_adata(vlm, trans_mats = None, cells_ixs = None, em_key = None):
	""" Conversion function from the velocyto world to the scanpy world

	Parameters
	--------
	vlm: VelocytoLoom Object
	trans_mats: None or dict
		A dict of all relevant transition matrices
	cell_ixs: list of int
		These are the indices of the subsampled cells

	Output
	adata: AnnData object
	"""

	# create the anndata object
	adata = AnnData(
		vlm.Sx_sz.T, vlm.ca, vlm.ra,
		layers=dict(
			unspliced=vlm.U.T,
			spliced = vlm.S.T,
			velocity = vlm.velocity.T),
		uns = dict(velocity_graph = vlm.corrcoef, louvain_colors = list(np.unique(vlm.colorandum)))
	)

	# add uns annotations
	if trans_mats is not None:
		for key, value in trans_mats.items():
			adata.uns[key] = trans_mats[key]
	if cells_ixs is not None:
		adata.uns['cell_ixs'] = cells_ixs

	# rename clusters to louvain
	try:
		ix = np.where(adata.obs.columns == 'Clusters')[0][0]
		obs_names = list(adata.obs.columns)
		obs_names[ix] = 'louvain'
		adata.obs.columns = obs_names

		# make louvain a categorical field
		adata.obs['louvain'] = pd.Categorical(adata.obs['louvain'])
	except:
		print('Could not find a filed \'Clusters\' in vlm.ca.')

	# save the pca embedding
	adata.obsm['X_pca'] = vlm.pcs[:, range(50)]

	# transfer the embedding
	if em_key is not None:
		adata.obsm['X_' + em_key] = vlm.ts
		adata.obsm['velocity_' + em_key] = vlm.delta_embedding

	# make things sparse
	adata.X = scp.sparse.csr_matrix(adata.X)
	adata.uns['velocity_graph'] =scp.sparse.csr_matrix(adata.uns['velocity_graph'])

	# make the layers sparse
	adata.layers['unspliced'] = scp.sparse.csr_matrix(adata.layers['unspliced'])
	adata.layers['spliced'] = scp.sparse.csr_matrix(adata.layers['unspliced'])
	adata.layers['velocity'] = scp.sparse.csr_matrix(adata.layers['unspliced'])

	return adata

def converter(data_in, from_type = 'adata', to_type = 'vlm', dir = '.'):
	"""
	convert adata to loom object
	- we may save to a temp directory automatically
	- we may write a on-the-fly converter which doesn't involve saving and reading files
	"""
	if(from_type == 'adata'):
		if(to_type == 'vlm'):
			file = dir + '/data.loom'
			data_in.write_loom(file)
			data_out = vcy.VelocytoLoom(file)
	elif(from_type == 'vlm'):
		if(to_type == 'adata'):
			data_out = vlm_to_adata(vlm)

	data_out.ra['Gene'] = data_out.ra['var_names'] # required by plot_phase_portraits
	colors20 = np.vstack((plt.cm.tab20b(np.linspace(0., 1, 20))[::2], plt.cm.tab20c(np.linspace(0, 1, 20))[1::2]))

	def colormap_fun(x: np.ndarray) -> np.ndarray:
		return colors20[np.mod(x, 20)]

	data_out.colorandum = colormap_fun([1] * data_out.S.shape[1])

	return(data_out)

def run_velocyto(adata):
	"""
	1. convert adata to vlm data
	2. set up PCA, UMAP, etc.
	3. estimate the gamma parameter
	"""
	vlm = converter(adata)

	# U_norm: log2(U_sz + pcount)
	# vlm.U_sz: norm_factor * U
	# S_norm: log2(S_sz + pcount)
	# vlm.S_sz norm_factor * S
	# vlm.Ux: smoothed unspliced
	# vlm.Sx: smoothed spliced
	# vlm.Ux_sz: smoothed unspliced -- old code
	# vlm.Sx_sz: smoothed spliced -- old code

	vlm.normalize() # add U_norm, U_sz, S_norm, S_sz
	vlm.perform_PCA()
	vlm.knn_imputation() # Ux, Sx, Ux_sz, Sx_sz
	vlm.pcs = adata.X # pcs: cell x npcs ndarray

	# vlm.Sx = vlm.S_sz
	# vlm.Ux = vlm.U_sz
	# vlm.Sx_sz = vlm.S_sz
	# vlm.Ux_sz = vlm.U_sz

	# gamma fit
	vlm.fit_gammas() # limit_gamma = False, fit_offset = True,  use_imputed_data = False, use_size_norm = False

	# estimate velocity
	vlm.predict_U()
	vlm.calculate_velocity()

	# predict future state after dt
	vlm.calculate_shift() # assumption = 'constant_velocity'
	vlm.extrapolate_cell_at_t() # delta_t = 1.

	return vlm

def run_scvelo(adata):
	"""
	1. set up PCA, UMAP, etc.
	2. estimate gamma and all other parameters
	3. return results (adata.var['velocity_gamma'])
	"""
	# scv.pp.filter_and_normalize(adata, min_counts=2, min_counts_u=1, n_top_genes=3000)
	scv.pp.moments(adata) # , n_pcs = 12, n_neighbors = 15, mode = 'distances'
	scv.tl.velocity(adata)
	scv.tl.velocity_graph(adata)

	# how to fit other parameters, beta, etc.?

	return adata

def mean_var_by_time(X, Time):
	import pandas as pd

	exp_data = pd.DataFrame(X)
	exp_data['Time'] = Time

	mean_val = exp_data.groupby(['Time']).mean()
	var_val = exp_data.groupby(['Time']).var()

	return mean_val.values, var_val.values

def run_dynamo(adata, normalize = True, init_num = 1, sample_method = 'lhs'):
	time = adata.obs['Step'].values
	uniqe_time = list(set(time))
	gene_num = adata.X.shape[1]

	# prepare data
	import numpy as np
	x_data = np.zeros((8, len(uniqe_time), gene_num)) # use unique time
	uu, ul, su, sl = adata.layers['uu'].toarray(), adata.layers['ul'].toarray(), adata.layers['su'].toarray(), adata.layers['sl'].toarray()
	uu = np.log2(uu + 1) if normalize else uu
	ul = np.log2(ul + 1) if normalize else ul
	su = np.log2(su + 1) if normalize else su
	sl = np.log2(sl + 1) if normalize else sl

	x_data[0], x_data[4] = mean_var_by_time(uu, time)
	x_data[1], x_data[5] = mean_var_by_time(ul, time)
	x_data[2], x_data[6] = mean_var_by_time(su, time)
	x_data[3], x_data[7] = mean_var_by_time(sl, time)

	# estimation all parameters
	p0_range = {'a': [0, 1], 'b': [0, 1], 'la': [0, 1], 'alpha_a': [10, 1000], \
			'alpha_i': [0, 10], 'sigma': [0, 1], 'beta': [0, 10], 'gamma': [0, 10]}

	estm = estimation(list(p0_range.values()))
	param_out = pd.DataFrame(index=adata.var.index, columns=['a', 'b', 'la', 'alpha_a', 'alpha_i', 'sigma', 'beta', 'gamma'])
	for i in range(gene_num):
		cur_x_data = x_data[:, :, i].squeeze()
		param_out.iloc[i, :], cost = estm.fit_lsq(uniqe_time, cur_x_data, p0=None, n_p0=init_num, sample_method=sample_method)

	# estimate only on the spliced and unspliced dataset

	# estimate on the labeled and unlabeled dataset

	# store the fitting result in adata.uns
	adata.uns.update({"dynamo": param_out})

	return adata

def run_dynamo_simple_fit(adata, log = True):
    ncells, gene_num = adata.X.shape

    # estimation all parameters
    param_out = pd.DataFrame(index=adata.var.index, columns=['alpha', 'gamma'])

    u, s = adata.layers['unspliced'], adata.layers['spliced']
    velocity_u, velocity_s = u, s
    for i in range(gene_num):
        cur_u, cur_s = u[:, i], s[:, i]
        gamma = fit_gamma(cur_u.toarray().squeeze(), cur_s.toarray().squeeze())
        alpha = np.mean(cur_s)

        velocity_u[:, i] = cur_u - cur_s * gamma
        velocity_s[:, i] = cur_s/(1 - np.exp(-1)) - cur_u
        param_out.iloc[i, :] = [alpha, gamma]

    adata.layers["velocity_u"] = velocity_u
    adata.layers["velocity_s"] = velocity_s
    adata.uns.update({"dynamo_simple_fit": param_out})

    return adata

def run_dynamo_labeling(adata, log = True, group = False):
    ncells, gene_num = adata.X.shape

    # estimation all parameters
    T = adata.obs['Time']

    groups = [''] if group == False else np.unique(adata.obs[group])

    param_out = pd.DataFrame(index=adata.var.index, columns=[i + '_' + j for j in groups for i in ['alpha', 'gamma', 'u0', 'l0']])
    L, U = adata.layers['L'], adata.layers['U']
    velocity_u, velocity_s = L, U

    for i in range(gene_num):
        all_parm = []
        for cur_grp in groups.tolist():
            cur_L, cur_U = (L[:, i], U[:, i]) if cur_grp == '' else (L[adata.obs[group] == cur_grp, i], U[adata.obs[group] == cur_grp, i])
            if log:
                cur_U, cur_L = np.log(cur_U.toarray().squeeze() + 1), np.log(cur_L.toarray().squeeze() + 1)
            else:
                cur_U, cur_L = cur_U.toarray().squeeze(), cur_L.toarray().squeeze()

            gamma, l0 = fit_gamma_labeling(T, cur_L, mode=None)
            alpha, u0 = fit_alpha_labeling(T, cur_U, gamma, mode=None)
            tmp = [alpha, gamma, u0, l0]
            all_parm.extend(tmp)

            velocity_u[:, i] = (cur_L - cur_U * gamma)[:, None]
            velocity_s[:, i] = (cur_U/(1 - np.exp(-1)) - cur_L)[:, None]
            adata.layers[cur_grp + "velocity_u"] = velocity_u
            adata.layers[cur_grp + "velocity_s"] = velocity_s

        param_out.iloc[i, :] = all_parm

    adata.uns.update({"dynamo_labeling": param_out})

    return adata

def compare_res(adata, velocyto_res, svelo_res, dynamo_res, a_val, b_val, la_val, alpha_a_val, alpha_i_val, sigma_val, beta_val, gamma_val):
	"""
	function to compare results from velocyto and scvelo with our new method
	0. retrieve gamm or gamma with other parameters from velocyto result or scvelo
	1. plot the correlation between parameters estimated with different methods
	2. calculate the correltion between those parameters
	"""
	# self._offset, self._offset2, self._beta, self._gamma, self._r2, self._velocity_genes

	velocyto_gammas = velocyto_res.gammas
	scvelo_gammas = svelo_res.var['velocity_gamma']

	# scatter plot the true gammas with our result
	plt.subplots(figsize = (15, 5))
	plt.plot()
	plt.subplot(131)
	plt.plot(gamma_val, velocyto_gammas, 'o')
	plt.xlabel(r'True $\gamma$')
	plt.ylabel(r'$\gamma$ (velocyto)')
	plt.subplot(132)
	plt.plot(gamma_val, scvelo_gammas, 'o')
	plt.xlabel(r'True $\gamma$')
	plt.ylabel(r'$\gamma$ (scvelo)')
	plt.subplot(133)
	plt.plot(gamma_val, dynamo_res.uns['dynamo']["gamma"], 'o')
	plt.xlabel(r'True $\gamma$')
	plt.ylabel(r'$\gamma$ (dynamo)')

    # what if we only have a small number of parameters?
	plt.subplots(figsize = (15, 5))
	plt.plot()
	plt.subplot(131)
	plt.plot(alpha_a_val, svelo_res.var['fit_alpha'], 'o')
	plt.xlabel(r'True alpha')
	plt.ylabel(r'$\alpha$ (scvelo)')
	plt.subplot(132)
	plt.plot(beta_val, svelo_res.var['fit_beta'], 'o')
	plt.xlabel(r'True $\beta$')
	plt.ylabel(r'$\beta$ (scvelo)')
	plt.subplot(133)
	plt.plot(gamma_val, svelo_res.var['fit_gamma'], 'o')
	plt.xlabel(r'True $\gamma$')
	plt.ylabel(r'$\gamma$ (scvelo)')

    #     param_out = pd.DataFrame(index=adata.var.index, columns=['a', 'b', 'la', 'alpha_a', 'alpha_i', 'sigma', 'beta', 'gamma'])
    # what if we only have a small number of parameters?
	plt.subplots(figsize = (15, 15))
	plt.subplot(331)
	plt.plot(a_val, adata.uns['dynamo']["a"], 'o')
	plt.xlabel(r'True $a$')
	plt.ylabel(r'$a$ (dynamo)')
	plt.subplot(332)
	plt.plot(b_val, adata.uns['dynamo']["b"], 'o')
	plt.xlabel(r'True $b$')
	plt.ylabel(r'$b$ (dynamo)')
	plt.subplot(333)
	plt.plot(la_val, adata.uns['dynamo']["la"], 'o')
	plt.xlabel(r'True $l_a$')
	plt.ylabel(r'$l_a$ (dynamo)')
	plt.subplot(334)
	plt.plot(alpha_a_val, adata.uns['dynamo']["alpha_a"], 'o')
	plt.xlabel(r'True $\alpha_a$')
	plt.ylabel(r'$\alpha_a$ (dynamo)')
	plt.subplot(335)
	plt.plot(alpha_i_val, adata.uns['dynamo']["alpha_i"], 'o')
	plt.xlabel(r'True $\alpha_i$')
	plt.ylabel(r'$\alpha_i$ (dynamo)')
	plt.subplot(336)
	plt.plot(sigma_val, adata.uns['dynamo']["sigma"], 'o')
	plt.xlabel(r'True $\sigma$')
	plt.ylabel(r'$\sigma$ (dynamo)')
	plt.subplot(337)
	plt.plot(beta_val, adata.uns['dynamo']["beta"], 'o')
	plt.xlabel(r'True $\beta$')
	plt.ylabel(r'$\beta$ (dynamo)')
	plt.subplot(338)
	plt.plot(gamma_val, adata.uns['dynamo']["gamma"], 'o')
	plt.xlabel(r'True $\gamma$')
	plt.ylabel(r'$\gamma$ (dynamo)')

	velocyto_coef = {"gamma": np.corrcoef(gamma_val, velocyto_gammas)[1, 0]}
	scvelo_coef = {"alpha": np.corrcoef(alpha_a_val, svelo_res.var['fit_alpha'])[1, 0],
                   "beta": np.corrcoef(beta_val, svelo_res.var['fit_beta'])[1, 0],
                   "gamma": np.corrcoef(gamma_val, svelo_res.var['fit_gamma'])[1, 0], }

	dynamo_coef = {'a': np.corrcoef(a_val, list(dynamo_res.uns['dynamo']["a"]))[1, 0],
	               'b': np.corrcoef(b_val, list(dynamo_res.uns['dynamo']["b"]))[1, 0],
	               'la': np.corrcoef(la_val, list(dynamo_res.uns['dynamo']["la"]))[1, 0],
	               'alpha_a': np.corrcoef(alpha_a_val, list(dynamo_res.uns['dynamo']["alpha_a"]))[1, 0],
	               'alpha_i': np.corrcoef(alpha_i_val, list(dynamo_res.uns['dynamo']["alpha_i"]))[1, 0],
	               'sigma': np.corrcoef(sigma_val, list(dynamo_res.uns['dynamo']["sigma"]))[1, 0],
	               'beta': np.corrcoef(beta_val, list(dynamo_res.uns['dynamo']["beta"]))[1, 0],
	               'gamma': np.corrcoef(gamma_val, list(dynamo_res.uns['dynamo']["gamma"]))[1, 0],

	              }

	return {'velocyto': pd.DataFrame.from_dict(velocyto_coef, orient = 'index').T, \
	'scvelo': pd.DataFrame.from_dict(scvelo_coef, orient = 'index').T, \
	'dynamo': pd.DataFrame.from_dict(dynamo_coef, orient = 'index').T}


import pygame as pg
from libreria import*
import random

class Fondo(pg.sprite.Sprite):
    """docstring for Fondo."""
    # /home/jorge/Escritorio/CGrafica/Sprites/Proyecto1/Fondo/fondo2.jpg
    def __init__(self, imagen):
        super(Fondo, self).__init__()
        self.arg = arg

def background(pantalla):
    x,velx = 0,0
    background=pg.image.load('/home/jorge/Escritorio/CGrafica/Sprites/Proyecto1/Fondo/fondo2.jpg')
    loop_background(pantalla,background)
    pass

def loop_background(pantalla,background):
    reloj=pg.time.Clock()
    info=background.get_rect()
    print(info)
    fondox=-100
    velx=7
    fin = False
    while not fin:
        for event in pg.event.get():
            #EVENTOS
            if event.type ==pg.QUIT:
                fin = True
        if fondox<((info[2]-ancho)*-1):
            fondox=0
        else:
            fondox-=velx
        pantalla.blit(background,[fondox,-100])
        reloj.tick(60)
        pg.display.flip()

if __name__ == '__main__':
    pg.init
    pantalla = pg.display.set_mode([ancho,alto])
    background(pantalla)


import csv

from Provisioning2.IAS import IAS

inputFile = 'C:/Users/JarrettGoldfedder/Documents/Jarrett/Testing/sample.csv'
outputFile = 'C:/Users/JarrettGoldfedder/Documents/Jarrett/Testing/sample_UID.csv'
url = "https://cacpt.csd.disa.mil:443/ECRSWebServices/uas?wsdl"
pkey = 'C:\Pentaho\projects\DHA_Provisioning\certs\keyfile-decrypted.key'
cert = 'C:\Pentaho\projects\DHA_Provisioning\certs\certfile.crt'
UID = IAS(url, pkey, cert)

with open(inputFile) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")
    line_count = 0
    with open(outputFile, mode='w', newline='\n',
              encoding='utf-8') as output_file:
        output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for row in csv_reader:
            if line_count == 0:
                print("{}, {}, {}, UID".format(row[0], row[1], row[2]))
                output_writer.writerow([row[0], row[1], row[2], 'UID'])
                line_count += 1
            else:
                iasID = UID.getUID(row[0])
                print("{}, {}, {}, {}".format(row[0], row[1], row[2], iasID))
                output_writer.writerow([row[0], row[1], row[2], "{}@example.com".format(iasID)])
                line_count += 1
print('Output saved to C:\\Users\\JarrettGoldfedder\\Documents\\Jarrett\\Testing\\sample_UID.csv' )