'''import os
import pandas as pd
import librosa
import librosa.display
import glob
import matplotlib.pyplot as plt

data, sampling_rate = librosa.load('D:\Sachin Workspace\Datasets\dev-clean\LibriSpeech\dev-clean\84\\121123\\84-121123-0001.flac')

plt.figure(figsize=(12, 4))
librosa.display.waveplot(data, sr=sampling_rate)
plt.show()
'''

import IPython.display as ipd

# % pylab inline
import os
import pandas as pd
import librosa
import glob
import librosa.display
import random

from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

from keras.utils.np_utils import to_categorical

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import LabelEncoder

import os

data = pd.read_csv('D:/Sachin Workspace/Datasets/train/train.csv')
print(data)
#Choose a random audio file and listen
i = random.choice(data.ID)
i=132
ipd.Audio('D:/Sachin Workspace/Datasets/train/Train/'+str(i)+'.wav')

def extract_features(files):
    # Sets the name to be the path to where the file is in my computer
    file_name = os.path.join(os.path.abspath('D:/Sachin Workspace/Datasets/train/Train') + '/' + str(files.ID) + '.wav')

    # Loads the audio file as a floating point time series and assigns the default sample rate
    # Sample rate is set to 22050 by default
    X, sample_rate = librosa.load(file_name, res_type='kaiser_fast')

    # Generate Mel-frequency cepstral coefficients (MFCCs) from a time series
    mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)

    # Generates a Short-time Fourier transform (STFT) to use in the chroma_stft
    stft = np.abs(librosa.stft(X))

    # Computes a chromagram from a waveform or power spectrogram.
    chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T, axis=0)

    # Computes a mel-scaled spectrogram.
    mel = np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T, axis=0)

    # Computes spectral contrast
    contrast = np.mean(librosa.feature.spectral_contrast(S=stft, sr=sample_rate).T, axis=0)

    # Computes the tonal centroid features (tonnetz)
    tonnetz = np.mean(librosa.feature.tonnetz(y=librosa.effects.harmonic(X),
                                              sr=sample_rate).T, axis=0)

    # We add also the classes of each file as a label at the end
    label = files.Class

    return mfccs, chroma, mel, contrast, tonnetz, label

from numpy import genfromtxt
#my_data = genfromtxt('my_file.csv', delimiter=',')

# Applying the function to the train data by accessing each row of the dataframe
features_labels = data.apply(extract_features, axis=1)
#features_labels = genfromtxt('C:/Users/sujan/PycharmProjects/Voice_Recog/features_df.csv', delimiter=',')
#features_labels = pd.read_csv('C:/Users/sujan/PycharmProjects/Voice_Recog/features_df.csv')
print(features_labels)

features_df = pd.DataFrame(features_labels)
features_df.to_csv('features_df.csv', index=False)

# We create an empty list where we will concatenate all the features into one long feature
# for each file to feed into our neural network
features = []
for i in range(0, len(features_labels)):
    features.append(np.concatenate((features_labels[i][0], features_labels[i][1],
                features_labels[i][2], features_labels[i][3],
                features_labels[i][4]), axis=0))

print(len(features))
# Similarly, we create a list where we will store all the labels

labels = []
for i in range(0, len(features_labels)):
    labels.append(features_labels[i][5])

print(len(labels))
# to let me know when it's done
os.system('say -v Juan ya acabé');
np.unique(labels, return_counts=True)

# Setting our X as a numpy array to feed into the neural network
X = np.array(features)
y = np.array(labels)
print(y)
lb = LabelEncoder()
y = to_categorical(lb.fit_transform(y))
print(y)

# Checking our shapes
print(X.shape)
print(y.shape)

# Choosing the first 3435 files to be our train data
# Choosing the next 1000 files to be our validation data
# Choosing the next 1000 files to be our test never before seen data
# This is analogous to a train test split but we add a validation split and we are making
# we do not shuffle anything since we are dealing with several time series

X_train = X[:3435]
y_train = y[:3435]

X_val = X[3435:4435]
y_val = y[3435:4435]

X_test = X[4435:]
y_test = y[4435:]

print(data[:3435]['Class'].value_counts(normalize=True))
print(data[3435:4435]['Class'].value_counts(normalize=True))
print(data[4435:]['Class'].value_counts(normalize=True))

print(X_train.shape,y_train.shape,X_val.shape,y_val.shape)
# Scaling
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_val = ss.transform(X_val)
X_test = ss.transform(X_test)

from datetime import datetime
startTime = datetime.now()

def model_func(layer_one_neurons=128, layer_one_dropout=.5, layer_two_neurons=512,
               layer_two_dropout=.5, layer_three_neurons=128, layer_three_dropout=.5):
    model = Sequential()

    model.add(Dense(layer_one_neurons,
                    input_shape=(193,),
                    activation='relu'))
    model.add(Dropout(layer_one_dropout))
    model.add(Dense(layer_two_neurons,
                    activation='relu'))
    model.add(Dropout(layer_two_dropout))
    model.add(Dense(layer_three_neurons,
                    activation='relu'))
    model.add(Dropout(layer_three_dropout))
    model.add(Dense(10,
                    activation='softmax'))
    model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
    return model

nn = KerasRegressor(model_func, batch_size=512, verbose=2)

params = {
    'epochs': [100],
    'layer_one_neurons': [193],
    'layer_two_neurons': [64, 128],
    'layer_three_neurons': [128, 256],
    'layer_one_dropout': [.25, .5],
    'layer_two_dropout': [.5, .75],
    'layer_three_dropout': [.5, .75]
}
gs = GridSearchCV(nn, param_grid=params, cv=3)
gs.fit(X_train, y_train)
print(gs.best_score_)
print(gs.best_params_)

print(datetime.now() - startTime)
os.system('say -v Juan ya acabé');

# build a simple dense model with early stopping with softmax for categorical classification
model = Sequential()
model.add(Dense(193, input_shape=(193,), activation = 'relu'))
model.add(Dropout(0.1))
model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.25))
model.add(Dense(128, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation = 'softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=100, verbose=1, mode='auto')

# fitting the model with the train data and validation with the validation data we used early stop with patience 15
history = model.fit(X_train, y_train, batch_size=256, epochs=200,
                    validation_data=(X_val, y_val),
                    callbacks=[early_stop])

# Checking how our model looks like and how many parameters it has
model.summary()

# Check out our train accuracy and validation accuracy over epochs.
train_accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']

import matplotlib.pyplot as plt
# Set figure size.
plt.figure(figsize=(12, 8))

# Generate line plot of training, testing loss over epochs.
plt.plot(train_accuracy, label='Training Accuracy', color='#185fad')
plt.plot(val_accuracy, label='Validation Accuracy', color='orange')

# Set title
plt.title('Training and Validation Accuracy by Epoch', fontsize = 25)
plt.xlabel('Epoch', fontsize = 18)
plt.ylabel('Categorical Crossentropy', fontsize = 18)
plt.xticks(range(0,100,5), range(0,100,5))
plt.legend(fontsize = 18);

# Using our model to get the predictions for our test data
preds = model.predict_classes(X_test)
# Looking at our test data as a dataframe to be able to compare prediction values
test = data[4435:]
# Setting our predictions column
test['preds'] = preds
# Changing the prediction values to their actual labels
test['preds'] = test['preds'].map({8:'siren', 9:'street_music', 7:'jackhammer',
                   4:'drilling', 3:'dog_bark', 2:'children_playing',
                   6:'gun_shot', 5:'engine_idling', 0:'air_conditioner',
                   1:'car_horn'})

# Looking at how accurate our model is just by looking at it
print(test)

# Slicing our dataframe into the files we got wrong from our predictions
print(test[test['Class']!=test['preds']])
# Calculating the actual test accuracy
print(round((1-len(test[test['Class']!=test['preds']])/len(test)),2))
predic_nn = model.predict_proba(X_test)
predic_nn = pd.DataFrame(predic_nn)
predic_nn.to_csv('predict_nn.csv', index=False)


# 백준 10830번
import sys

def multiple(m1, m2):
    temp = [[0] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            try:
                temp[i][j] += (m1[i][0] * m2[0][j])
                temp[i][j] += (m1[i][1] * m2[1][j])
                temp[i][j] += (m1[i][2] * m2[2][j])
                temp[i][j] += (m1[i][3] * m2[3][j])
                temp[i][j] += (m1[i][4] * m2[4][j])
            except Exception:
                pass
            temp[i][j] %= R
    return temp

R = 1000
N, B = map(int, sys.stdin.readline().split())
mat = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]

def power(B):
    if B == 1:
        return mat
    else:
        if B % 2 == 0:
            temp = power(B // 2)
            return multiple(temp, temp)
        else:
            temp = power(B-1)
            return multiple(temp, mat)

res = power(B)
for i in range(N):
    for j in range(N):
        res[i][j] %= R

for row in res:
    sys.stdout.write(' '.join(map(str, row)) + '\n')


from django.shortcuts import render, redirect
from django.views import View
from .models import Product, Cart, OrderPlaced
from .forms import CoustomerRegistrationFrom, ShippingAddressForm
from django.contrib import messages
from django.db.models import Q
from django.http import JsonResponse, HttpResponseBadRequest
from django.contrib.auth.decorators import login_required
# def home(request):
#  return render(request, 'app/home.html')

class ProductView(View):
    def get(self, request):
        topwears = Product.objects.filter(category='TM')
        bottomewears = Product.objects.filter(category='BW')
        mobiles = Product.objects.filter(category='M')
        laptops = Product.objects.filter(category='L')
        totalitem = 0
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))

        context = {'topwears':topwears, 'bottomewears':bottomewears, 'mobiles':mobiles, 'laptops':laptops, 'totalitem':totalitem}

        return render(request, 'app/home.html', context)

class ProductDetailView(View):
    def get(self, request, pk):
        product = Product.objects.get(pk=pk)
        item_already_in_cart = False
        if request.user.is_authenticated:
            item_already_in_cart = Cart.objects.filter(Q(product=product.id) & Q(user=request.user)).exists()

        totalitem = 0
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))

        context = {'product':product, 'item_already_in_cart':item_already_in_cart, 'totalitem':totalitem}

        return render(request, 'app/productdetail.html', context)

@login_required
def add_to_cart(request):
    user = request.user
    product_id = request.GET.get('prod_id')
    product = Product.objects.get(id=product_id)

    if Cart.objects.filter(Q(product=product.id) & Q(user=request.user)).exists():
        return redirect(f'/product-detail/{product_id}')

    cart = Cart(user=user, product=product)
    print(cart)

    cart.save()

    return redirect(f'/product-detail/{product_id}')

@login_required
def show_cart(request):
    if request.user.is_authenticated:
        user = request.user
        carts = Cart.objects.filter(user=user)
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == user]

        totalitem = 0
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))

        if cart_product:
            for p in cart_product:
                temp_amount = (p.quantity * p.product.discounted_price)
                amount += temp_amount
        if amount == 0:
            total_amount = 0.0
        else:
            total_amount = shipping_amount + amount

    context={'carts': carts, 'amount':amount, 'total_amount':total_amount, 'totalitem':totalitem}
    return render(request, 'app/addtocart.html', context)

@login_required
def plus_cart(request):
    if request.method =="GET":
        prod_id = request.GET['prod_id']
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user))
        c.quantity+=1
        c.save()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        if cart_product:
            for p in cart_product:
                temp_amount = (p.quantity * p.product.discounted_price)
                amount += temp_amount
        if amount == 0:
            total_amount = 0.0
        else:
            total_amount = shipping_amount + amount

        data = {
            'quantity': c.quantity,
            'amount':amount,
            'total_amount':total_amount
            }
        return JsonResponse(data)

@login_required
def minus_cart(request):
    if request.method =="GET":
        prod_id = request.GET['prod_id']
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user))
        if c.quantity != 1:
            c.quantity-=1
            c.save()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        if cart_product:
            for p in cart_product:
                temp_amount = (p.quantity * p.product.discounted_price)
                amount += temp_amount
        if amount == 0:
            total_amount = 0.0
        else:
            total_amount = shipping_amount + amount

        data = {
            'quantity': c.quantity,
            'amount':amount,
            'total_amount':total_amount
            }
        return JsonResponse(data)

@login_required
def remove_from_cart(request, id):
    p = Cart.objects.get(id=id)
    print(p)
    p.delete()
    return redirect('/cart')

@login_required
def buy_now(request):
 return render(request, 'app/buynow.html')

@login_required
def orders(request):
    op = OrderPlaced.objects.filter(user= request.user)
    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))
    context={'op':op, 'totalitem':totalitem}
    return render(request, 'app/orders.html', context)

def mobile(request, data=None):
    if data == None:
        mobile = Product.objects.filter(category='M')
    elif data == 'below':
        mobile = Product.objects.filter(category='M').filter(discounted_price__lt=10000)
    elif data == 'above':
        mobile = Product.objects.filter(category='M').filter(discounted_price__gt=10000)
    else:
        mobile = Product.objects.filter(category='M').filter(brand=data)

    allmobile = Product.objects.filter(category='M').values('brand').distinct()

    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))
    context = {
        'mobile':mobile,
        'allmobile':allmobile,
        'totalitem':totalitem
        }

    return render(request, 'app/mobile.html', context)

def laptop(request, data=None):
    if data == None:
        laptop = Product.objects.filter(category='L')
    elif data == 'below':
        laptop = Product.objects.filter(category='L').filter(discounted_price__lt=35000)
    elif data == 'above':
        laptop = Product.objects.filter(category='L').filter(discounted_price__gt=35000)
    else:
        laptop = Product.objects.filter(category='L').filter(brand=data)

    alllaptop = Product.objects.filter(category='L').values('brand').distinct()

    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))

    context = {
        'laptop':laptop,
        'alllaptop':alllaptop,
        'totalitem':totalitem
        }

    return render(request, 'app/laptop.html', context)

def topwear(request, data=None):
    if data == None:
        topwear = Product.objects.filter(category='TM')
    elif data == 'below':
        topwear = Product.objects.filter(category='TM').filter(discounted_price__lt=35000)
    elif data == 'above':
        topwear = Product.objects.filter(category='TM').filter(discounted_price__gt=35000)
    else:
        topwear = Product.objects.filter(category='TM').filter(brand=data)

    alltopwear = Product.objects.filter(category='TM').values('brand').distinct()

    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))

    context = {
        'topwear':topwear,
        'alltopwear':alltopwear,
        'totalitem':totalitem
        }

    return render(request, 'app/topwear.html', context)

def bottomwear(request, data=None):
    if data == None:
        bottomwear = Product.objects.filter(category='BW')
    elif data == 'below':
        bottomwear = Product.objects.filter(category='BW').filter(discounted_price__lt=35000)
    elif data == 'above':
        bottomwear = Product.objects.filter(category='BW').filter(discounted_price__gt=35000)
    else:
        bottomwear = Product.objects.filter(category='BW').filter(brand=data)

    allbottomwear = Product.objects.filter(category='BW').values('brand').distinct()

    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))
    context = {
        'bottomwear':bottomwear,
        'allbottomwear':allbottomwear,
        'totalitem':totalitem
        }

    return render(request, 'app/bottomwear.html', context)

# def login(request):
#  return render(request, 'app/login.html')

# def customerregistration(request):
#  return render(request, 'app/customerregistration.html')

class CustomerRegistrationView(View):
    def get(self, request):
      form = CoustomerRegistrationFrom()
      context = {'form': form}
      return render(request, 'app/customerregistration.html', context)

    def post(self, request):
        form = CoustomerRegistrationFrom(request.POST)
        if form.is_valid():
           messages.success(request, 'Congratulation !! Account Registered Successfully.')
           form.save()
        context = {'form': form}
        return render(request, 'app/customerregistration.html', context)

@login_required
def checkout(request):
    if request.method == 'POST':
        user = request.user
        SAForm = ShippingAddressForm(request.POST)
        if SAForm.is_valid():
            location = SAForm.cleaned_data['location']
            name = SAForm.cleaned_data['name']
            phone_number = SAForm.cleaned_data['phone_number']
            state = SAForm.cleaned_data['state']
            payment_method = SAForm.cleaned_data['payment_method']
        else:
            messages.error(request,'Unvalid')
            return redirect("checkout")

        cart = Cart.objects.filter(user=user)
        for c in cart:
            OrderPlaced(user=user, location=location, name=name, phone_number=phone_number, state=state, payment_method=payment_method, product=c.product, quantity=c.quantity).save()
            c.delete()

        return redirect("orders")

    else:
        SAForm = ShippingAddressForm()
        user = request.user
        cart_items = Cart.objects.filter(user=user)

        totalitem = 0
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))

        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        if cart_product:
                for p in cart_product:
                    temp_amount = (p.quantity * p.product.discounted_price)
                    amount += temp_amount
                if amount == 0:
                    total_amount = 0.0
                else:
                    total_amount = shipping_amount + amount
        else:
            messages.error(request,'Please add product before order placed')
            return redirect("show-cart")

        context={'SAForm':SAForm, 'cart_items':cart_items, 'total_amount':total_amount, 'totalitem':totalitem}
        return render(request, 'app/checkout.html', context)


import cv2
import numpy as np
import os

video_capture = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier("PATH\\TO\\haarcascade_frontalface_alt.xml")
face_data = []
face_section = np.zeros((100,100),dtype='uint8')
dirpath = "PATH\\TO\\SAVE\\DATA_FOLDER"
skip = 0

cv2.namedWindow("Window")

while True:
    ret, frame = video_capture.read()
    if ret == False:
      continue
    gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray_frame,1.3,5)
    faces = sorted(faces,key=lambda f:f[2]*f[3])
    for face in faces [-1:]:
      x, y, w, h = face
      cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
      face_section = frame[y - 10:y + h + 10, x - 10:x + w + 10]
      face_section = cv2.resize(face_section, (100, 100))
    cv2.imshow("Window", frame)
    cv2.imshow("Cropped",face_section)

    skip += 1
    if (skip % 10 == 0):
      face_data.append(face_section)
      print(len(face_data))
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

####################################################################################
##############      COMMENT ALL CODE BELOW FOR TRAINING THE MODEL     ##############
##############      COMMENT ALL CODE ABOVE FOR TESTING THE MODEL      ##############
####################################################################################

import cv2
import numpy as np
import os

face_data = np.array(face_data)
print(face_data.shape)
face_data = face_data.reshape((face_data.shape[0],-1))
print(face_data.shape)

np.save(dirpath + "YOUR_NAME" + '.npy',face_data)
print("data successfully saved at " + dirpath+"YOUR_NAME"+'.npy')

def distance(v1, v2):
    # Eucledian
    return np.sqrt(((v1 - v2) ** 2).sum())

def knn(train, test, k=5):
    dist = []
    for i in range(train.shape[0]):
        ix = train[i, :-1]
        iy = train[i, -1]
        d = distance(test, ix)
        dist.append([d, iy])
    dk = sorted(dist, key=lambda x: x[0])[:k]
    labels = np.array(dk)[:, -1]
    output = np.unique(labels, return_counts=True)
    index = np.argmax(output[1])
    return output[0][index]

cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier("PATH\\TO\\haarcascade_frontalface_alt.xml")
skip = 0
dataset_path = 'PATH\\TO\\SAVE\\DATA_FOLDER'
face_data = []
labels = []
class_id = 0
names = {}

for fx in os.listdir(dataset_path):
    if fx.endswith('.npy'):
        names[class_id] = fx[:-4]
        print("Loaded " + fx)
        data_item = np.load(dataset_path + fx)
        face_data.append(data_item)
        target = class_id * np.ones((data_item.shape[0],))
        class_id += 1
        labels.append(target)
face_dataset = np.concatenate(face_data, axis=0)
face_labels = np.concatenate(labels, axis=0).reshape((-1, 1))
print(face_dataset.shape)
print(face_labels.shape)
trainset = np.concatenate((face_dataset, face_labels), axis=1)
print(trainset.shape)

while True:
    ret, frame = cap.read()
    if ret == False:
        continue
    faces = face_cascade.detectMultiScale(frame, 1.3, 5)
    if (len(faces) == 0):
        continue
    for face in faces:
        x, y, w, h = face
        offset = 10
        face_section = frame[y - offset:y + h + offset, x - offset:x + w + offset]
        face_section = cv2.resize(face_section, (100, 100))
        out = knn(trainset, face_section.flatten())
        pred_name = names[int(out)]
        cv2.putText(frame, pred_name, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 2)
    cv2.imshow("Faces", frame)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


#!/usr/bin/python
# -*- coding: utf-8 -*-
from misura.canon.logger import get_module_logging
logging = get_module_logging(__name__)
from PyQt4 import QtGui, QtCore
from traceback import format_exc
import functools

import region
import profile
import shape
import border
from overlay import Overlay

def is_hsm_sample(sample):
    r='/hsm/' in sample['fullpath']
    return r

class MetaItem(QtGui.QGraphicsSimpleTextItem):

    def contextMenuEvent(self, event):
        self.parentItem().contextMenuEvent(event)

    @property
    def menu(self):
        return self.parentItem().menu

class MetaLabel(Overlay):

    """Metadata label visualization"""

    def __init__(self, parentItem, Z=1):
        Overlay.__init__(self, parentItem, Z)
        self.label = MetaItem(parent=self)
        self.label.setText('Empty')
        self.label.setFlags(QtGui.QGraphicsItem.ItemIsSelectable |
                            QtGui.QGraphicsItem.ItemIsFocusable | QtGui.QGraphicsItem.ItemIsMovable |
                            QtGui.QGraphicsItem.ItemIgnoresTransformations)
        self.menu = QtGui.QMenu()
        self.acts = {}

    def unscale(self, factor):
        Overlay.unscale(self, factor)
        self.up()

    def up(self):
        t = ''
        for k, v in self.current.iteritems():
            t += '{}: {:.2e}\n'.format(k, v)
        if len(t) == 0:
            t = 'Empty'
        logging.debug('updating to', t, 'MetaLabels')
        self.label.setText(t)

    def add(self, name):
        logging.debug('adding name', name)
        self.opt.add(name)
        rem = functools.partial(self.remove, name)
        a = self.menu.addAction(name, rem)
        a.setCheckable(True)
        a.setChecked(True)
        self.acts[name] = a, rem
        self.parentItem().parentItem().opt_changed = True

    def remove(self, name):
        logging.debug('removing name', name)
        self.opt.remove(name)
        del self.current[name]
        self.menu.removeAction(self.acts[name][0])

class SamplePix(QtGui.QGraphicsPixmapItem):

    def __init__(self, *a, **k):
        QtGui.QGraphicsPixmapItem.__init__(self, *a, **k)
        self.setAcceptDrops(True)
        self.label = MetaLabel(self)

    def unscale(self, factor):
        self.label.unscale(factor)

    def dragEnterEvent(self, event):
        logging.debug('dragEnterEvent', event.mimeData())
        event.acceptProposedAction()
        if event.mimeData().hasFormat("text/plain"):
            event.acceptProposedAction()

    def dropEvent(self, event):
        logging.debug('DROP EVENT')
        opt = str(event.mimeData().text()).replace(
            'summary', '').replace('//', '/').split('/')[-1]
        logging.debug('Adding option:', opt)
        self.label.add(opt)
        self.parentItem().opt_changed = True

class SamplePicture(QtGui.QGraphicsItem):

    """Graphical item representing a Sample, including its image and all overlays describing geometry data"""
    overlays = []
    opt_changed = False

    def __init__(self, parentItem, smp, n):
        """`parentItem`: parent graphical item
        `smp`; remote sample object
        `n`: graphical Z layer"""
        QtGui.QGraphicsItem.__init__(self, parent=parentItem)
        self.smp = smp
        self.pixItem = SamplePix(parent=self)
        self.pix = self.pixItem.pixmap()
        self.pixItem.show()
        self.overlays = []

        # General
        # BoxRegion must have same parent as self (sensorplane)
        self.roi = region.BoxRegion(parentItem, self.smp, Z=n)
        self.overlays.append(self.roi)

        self.is_hsm = is_hsm_sample(smp)
        self.profile = profile.Profile(parentItem, self.is_hsm)
        self.overlays.append(self.profile)

        self.label = self.pixItem.label
        self.overlays.append(self.label)
        # TODO: distinguish instrument overlays based on mro!
        umpx = smp.analyzer['umpx']
        # Shape-specific
        if self.is_hsm:
            self.points = shape.SamplePoints(parentItem)
            self.overlays.append(self.points)
            self.baseHeight = shape.BaseHeight(parentItem, umpx=umpx)
            self.overlays.append(self.baseHeight)
            self.circle = shape.CircleFit(parentItem, umpx=umpx)
            self.overlays.append(self.circle)
        else:
            self.referenceLine = border.ReferenceLine(parentItem, startLine=True)
            self.overlays.append(self.referenceLine)

            self.regressionLine = border.ReferenceLine(parentItem, startLine=False)
            self.overlays.append(self.regressionLine)

            self.filteredProfile = profile.Profile(parentItem, False, profile_name='filteredProfile')
            self.overlays.append(self.filteredProfile)

        self.show()

    def boundingRect(self):
        return self.pixItem.boundingRect()

    def close(self):
        for ov in self.overlays:
            ov.hide()
            self.scene().removeItem(ov)
            del ov

    def unscale(self, factor):
        for ov in self.overlays:
            ov.unscale(factor)
        self.pixItem.unscale(factor)

    def update(self, multiget):
        """Update all visible overlay with new dictionary"""
        if len(multiget) == 0:
            return False
        roi = multiget.get('roi', False)
        if roi:
            x, y = roi[:2]
            if x < 0:
                x = 0
            if y < 0:
                y = 0
            self.setPos(x, y)
        for ov in self.overlays:
            if ov.isVisible():
                try:
                    ov.slot_update(multiget)
                except:
                    logging.debug('Overlay update error')
                    logging.debug(format_exc())
        return True

    @property
    def opt(self):
        """Return the set of all required options for overlay update"""
        r = set([])
        for ov in self.overlays:
            if not ov.isVisible():
                continue
            r = r.union(ov.opt)
        return r

    @opt.setter
    def opt(self, val):
        """Allow to reset opt by setting it to []"""
        assert val == []
        for ov in self.overlays:
            ov.hide()

    def paint(self, *a, **kw):
        return None


# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(A, K):

    if len(A) == 0:
        return A
    if K % len(A) == 0:
        return A

    K = K % len(A)

    temp = [0]*len(A)
    for i in range (0, len(A), 1):
        print(f"index{(i+K)%len(A)}")
        temp[(i+K)%len(A)] = A[i]
    return temp

if __name__ == "__main__" :
    # A = [3, 8, 9, 7, 6]
    # K = 3
    # exp = [9, 7, 6, 3, 8]

    # A = [1, 2, 3, 4]
    # K = 4
    # exp = [1, 2, 3, 4]

    # # error
    # A = [1, 2]
    # K = 1
    # exp = [2, 1]

    A = []
    K = 3
    exp = [6, 7, 1, 2, 3, 4, 5]

    res = solution(A, K)
    print(f"expected {exp}, result {res}")


import os
import time
import pickle

class State(object):
    """Simple persistence
    """
    def __init__(self, persist_file, persist_every=1000):
        self.persist_file = persist_file
        self.__persist_every = persist_every
        self.__count_since_persist = 0
        self.__state = {'data': {}, 'meta': {}}

    @property
    def data(self):
        return self.__state['data']

    @property
    def meta(self):
        return self.__state['meta']

    def update(self, data, meta={}):
        assert isinstance(data, dict), "Data must be dict."
        assert isinstance(meta, dict), "Meta data must be dict."
        self.__count_since_persist += 1
        self.__state['meta'].update(meta)
        self.__state['meta'].update({'ts_updated': time.time()})
        self.__state['data'].update(data)

        if not self.__count_since_persist % self.__persist_every:
            self.persist()
            return True

    def persist(self):
        """Simple persist of state.
        """
        self.__state['meta'].update({'ts_saved': time.time()})
        pickle.dump(self.__state,
                        open(self.persist_file, 'w'))
        self.__count_since_persist = 0

    def load(self):
        """Load persisted data.
        """
        self.__state = pickle.load(open(self.persist_file, 'r'))
        self.__state['meta'].update({'ts_loaded': time.time()})
        self.__count_since_persist = 0

    def reset(self):
        """
        """
        self.__state = {}
        if os.path.exists(self.__persist_file):
            os.unlink(self.__persist_file)
        self.__count_since_persist = 0

class Lock(object):
    pass


from django.db.models import Count

from interfaces.models import Interfaces
from testsuits.models import Testsuits

def get_count_by_project(datas):
    """
    1. 通过项目中的接口、用例、配置、套件的数量
    2. 对时间进行格式化
    :param datas:
    :return:
    """
    datas_list = []
    for item in datas:
        # create_time格式化
        create_time_list = item.get('create_time').split('T')
        first_part = create_time_list[0]
        second_part = create_time_list[1].split('.')[0]
        item['create_time'] = first_part + ' ' + second_part

        # 获取项目id值
        project_id = item['id']
        interfaces_testcases_objs = Interfaces.objects.values('id').annotate(testcases=Count('testcases')).\
            filter(project_id=project_id)
        # 获取接口总数
        interfaces_count = interfaces_testcases_objs.count()
        # 设置用例总数初始值为0
        testcases_count = 0
        for one_dict in interfaces_testcases_objs:
            testcases_count += one_dict['testcases']

        interfaces_configures_objs = Interfaces.objects.values('id').annotate(configures=Count('configures')). \
            filter(project_id=project_id)

        # 设置配置总数初始值为0
        configures_count = 0
        for one_dict in interfaces_configures_objs:
            configures_count += one_dict['configures']

        # 获取套件总数
        testsuits_count = Testsuits.objects.filter(project_id=project_id).count()

        item['interfaces'] = interfaces_count
        item['testsuits'] = testsuits_count
        item['testcases'] = testcases_count
        item['configures'] = configures_count

        datas_list.append(item)
    return datas_list


""" mimeTypeMaps.py:
    reading the JSON describing mime types and making them into
    ready-to-use maps.
"""

import json
import os

from config import resourceDirectory

mimeTypeClassification = json.load(open(os.path.join(
    resourceDirectory,
    'mimetype_classifier',
    'file_mimetype_classification.json',
)))

# in-module conversion of the loaded information (!)
# this is:
#   mimetype -> thumbnail rootname
#     ('img', 'pdf', ... one for each default thumbnail pic in <rootname>.png)
mimeTypeToDefaultThumbnailMap = {
    mimeType: fileType
    for fileType, mimeTypes in
    mimeTypeClassification['mime_types_by_filetype'].items()
    for mimeType in mimeTypes
}

imageMimeTypeToResizeMethodMap = mimeTypeClassification[
    'image_mime_types_by_thumbnail_method']

viewableMimeTypeToViewModeMap = {
    mimeType: viewMode
    for viewMode, mimeTypes in
    mimeTypeClassification['viewable_mime_types_by_view_mode'].items()
    for mimeType in mimeTypes
}

textualEditableMimeTypes = {
    mimeType
    for mimeType in
    mimeTypeClassification[
        'viewable_mime_types_by_view_mode'].get('textual', [])
}


import os, sys
from csv import reader, DictReader
from collections import defaultdict

def report_primer_match_perZMW(seen53_filename, redux_filename):
    seqid_to_primermatch = {}
    for r in DictReader(open(redux_filename), delimiter='\t'):
        seqid_to_primermatch[r['fastaid'].split()[0]] = r['barcode'] # the .split is for [revcomp]

    pm_count = defaultdict(lambda:0) # primer name --> count
    last_key = (None,None)  # (Movie, HoleNumber)
    last_len = 0
    last_pm = None
    for r in DictReader(open(seen53_filename), delimiter='\t'):
        key = r['Movie'], r['HoleNumber']
        cur_len = int(r['rEnd']) - int(r['rStart'])
        if key != last_key:
            # output from last
            if last_pm is not None: pm_count[last_pm] += 1
            last_len = cur_len
            last_key = key
        elif cur_len > last_len:
            last_len = cur_len
            seqid = r['Movie'] + '/' + r['HoleNumber'] + '/' + str(r['rStart']) + '_' + str(r['rEnd'])
            last_pm = seqid_to_primermatch[seqid]

    keys = pm_count.keys()
    keys.sort()
    for k in keys:
        print("{0}:{1}".format(k, pm_count[k]))

if __name__ == "__main__":
    report_primer_match_perZMW(sys.argv[1], sys.argv[2])


from numpy.random import beta

sites = ["var_1", "var_2", "var_3"]

class ThompsonSampling(object):

    def __init__(self, variation_list):

        self.variations = variation_list

        self.distributions = {}

        for variation in self.variations:

            self.distributions[variation] = {"alpha": 1, "beta":1}

        self.variation_selected = False

    def select_variation(self):

        highest_prob = -1

        selected = None

        for variation in self.variations:

            alpha_i, beta_i = self.distributions[variation]["alpha"], self.distributions[variation]["beta"]

            candidate_prob = beta(alpha_i, beta_i)

            if candidate_prob > highest_prob:

                highest_prob = candidate_prob

                selected = variation

        print(selected)

        self.selected = selected

        self.variation_selected = True

    def update_params(self, positive_response):

        assert self.variation_selected, "You have not selected a new variation"

        if positive_response:

            self.distributions[self.selected]["alpha"] += 1

        else:

            self.distributions[self.selected]["beta"] += 1

        self.variation_selected = False

ts_variations = ThompsonSampling(sites)

ts_variations.select_variation()

ts_variations.update_params(True)

ts_variations.update_params(True)

ts_variations.select_variation()

ts_variations.update_params(False)


import os
import unittest

from django.shortcuts import redirect, render

from media.base.BaseAdb import AndroidDebugBridge
from media.base.BaseAppiumServer import AppiumServer
from media.base.BaseRunner import ParametrizedTestCase
from media.tests.test_appium import EribankTest
from .forms import DocumentForm
from .models import Document

PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

def my_view(request):
    print(f"Great! You're using Python 3.6+. If you fail here, use the right version.")
    message = 'Upload as many files as you want!'
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['docfile'], name=request.POST['name'],
                              class_name=request.POST['class_name'])
            newdoc.save()

            # Redirect to the document list after POST
            return redirect('my-view')
        else:
            message = 'The form is not valid. Fix the following error:'
    else:
        form = DocumentForm()  # An empty, unbound form

    # Load base for the list page
    documents = Document.objects.all()

    # Render list page with the base and the form
    context = {'base': documents, 'form': form, 'message': message}
    return render(request, 'list.html', context)

def kill_adb():
    os.system(PATH("../media/base/kill5037.bat"))
    os.system("adb start-server")

def runnerPool(device):
    _initApp = {}
    _initApp['deviceName'] = device[0]
    _initApp['platformVersion'] = '10'
    _initApp["platformName"] = "android"
    _initApp["automationName"] = "uiautomator2"
    _initApp["appPackage"] = 'com.experitest.ExperiBank'
    _initApp["appActivity"] = 'com.experitest.ExperiBank.LoginActivity'
    _initApp['unicodeKeyboard'] = True
    _initApp['resetKeyboard'] = True
    _initApp['androidScreenshotPath'] = '/storage/emulated/0/Pictures/Screenshots/'

    runnerCaseApp(_initApp)

def runnerCaseApp(device):
    suite = unittest.TestSuite()
    suite.addTest(ParametrizedTestCase.parametrize(EribankTest, param=device))
    unittest.TextTestRunner(verbosity=2).run(suite)

def run_view(request):
    kill_adb()
    device = AndroidDebugBridge().attached_devices()
    appium_server = AppiumServer()
    appium_server.start_server()
    runnerPool(device)
    appium_server.stop_server()
    return render(request, 'list.html')


import logging
from argparse import ArgumentParser
from pathlib import Path

import numpy as np
import torch
import segmentation_models_pytorch as smp
from cv2 import cv2
from PIL import Image
from tqdm import tqdm

from tools import check_args
from image_utils import image_preprocessing, get_phyto_model

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
preprocessing_fn = smp.encoders.get_preprocessing_fn("se_resnext50_32x4d",
                                                     "imagenet")

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument("--cuda", action="store_true", help="use cuda")
    parser.add_argument("-m", "--model_path", type=str,
                        help="path to model checkpoint (*.ckpt)")
    parser.add_argument("-f", "--image_folder", type=str, default="examples",
                        help="path to folder contains satellite images (*.png)")
    parser.add_argument("-o", "--output_folder", type=str, default="result",
                        help="path to folder contains result images")

    args = check_args(parser.parse_args())

    target_size = (384, 608)  # width, height
    images = list(Path(args.image_folder).glob("*.png"))
    for image_filepath in tqdm(images, desc="Image processing"):
        image = cv2.imread(str(image_filepath))
        image, image_original, padded_size = image_preprocessing(image,
                                                                 target_size)
        image_trans = preprocessing_fn(x=image).transpose(2, 0, 1).astype('float32')

        device = "cpu" if not args.cuda else "cuda"
        image_tensor = torch.from_numpy(image_trans).unsqueeze(0).to(device)
        model = get_phyto_model(args.model_path, args.cuda)

        pr_mask = model(image_tensor)
        pr_mask = pr_mask.sigmoid()
        pr_mask = (pr_mask.squeeze().cpu().detach().numpy().round())

        if padded_size is None and pr_mask.shape[:2] != image_original.shape[:2]:
            pr_mask_pil = Image.fromarray(pr_mask)
            pr_mask_pil_resized = pr_mask_pil.resize(image_original.shape[:2][::-1],
                                                     resample=Image.Resampling.BICUBIC)
            pr_mask = np.array(pr_mask_pil_resized)
        elif isinstance(padded_size, tuple):
            h_pad_top, h_pad_bottom, w_pad_left, w_pad_right = padded_size
            pr_mask = pr_mask[h_pad_top:pr_mask.shape[0] - h_pad_bottom,
                              w_pad_left:pr_mask.shape[1] - w_pad_right]

        image_segm = image_original.copy()
        image_mask_red = image_segm[:, :, 2]
        image_mask_red[pr_mask == 1] = 200
        image_segm[:, :, 2] = image_mask_red

        result_image_mask_path = Path(args.output_folder) / f"{image_filepath.stem}_segm.png"
        original_image_path = Path(args.output_folder) / image_filepath.name
        cv2.imwrite(str(result_image_mask_path), image_segm)
        cv2.imwrite(str(original_image_path), image_original)
        logger.debug(f"saved result of {image_filepath.name} segmentation to "
                    f"{result_image_mask_path.parent.resolve()}")
    logger.info(f"Result was saved to {args.output_folder}")


import string
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
import shutil
import sys
hostname="localhost"
dir_path=sys.argv[1]

#print("the dir name is ", dir_path)

class Problem(BaseHTTPRequestHandler):
    def do_POST(self):
        json_data = None
        json_data = json.load(self.rfile)
        #print(json_data)
        #print(json_data['name'])
        if json_data is not None:
            json.dumps(json_data)
        else:
            print("Got no data")
        #print(json_data)
        problem_name = json_data['name']
        problem_name.translate({ord(c): None for c in string.whitespace})
        #making folder in current directory
        path_for_problem = os.path.join(dir_path, problem_name)
        path_for_problem = path_for_problem.replace(' ','_')
        path_for_problem = path_for_problem.replace('.','')
        path_for_problem = path_for_problem.replace('\'','')
        #print(path_for_problem)
        if os.path.exists(path_for_problem) and os.path.isdir(path_for_problem):
            shutil.rmtree(path_for_problem)
        os.mkdir(path_for_problem)

        input_data = json_data['tests']
        #print(input_data)
        #saving the samples in diff folders.
        #making the seperate folders for each Test

        os.mkdir(os.path.join(path_for_problem,"test_cases"))
        for idx, u in enumerate(input_data):
            #print(u['input'],"\n", u['output'],"\n")
            name = os.path.join(path_for_problem,"test_cases",str(idx))
            os.mkdir(name)
            with open(os.path.join(name,"input.txt"),'w') as f:
                f.write(u['input'])
            with open(os.path.join(name,"output.txt"),'w') as f:
                f.write(u['output'])

def run():
   port = 5001
   server = HTTPServer((hostname, port), Problem)
   server.serve_forever()

if __name__ == '__main__':
    run()


# search.py
# ---------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""

import util

class SearchProblem:
    """
    This class outlines the structure of a search problem, but doesn't implement
    any of the methods (in object-oriented terminology: an abstract class).

    You do not need to change anything in this class, ever.
    """

    def getStartState(self):
        """
        Returns the start state for the search problem.
        """
        util.raiseNotDefined()

    def isGoalState(self, state):
        """
          state: Search state

        Returns True if and only if the state is a valid goal state.
        """
        util.raiseNotDefined()

    def getSuccessors(self, state):
        """
          state: Search state

        For a given state, this should return a list of triples, (successor,
        action, stepCost), where 'successor' is a successor to the current
        state, 'action' is the action required to get there, and 'stepCost' is
        the incremental cost of expanding to that successor.
        """
        util.raiseNotDefined()

    def getCostOfActions(self, actions):
        """
         actions: A list of actions to take

        This method returns the total cost of a particular sequence of actions.
        The sequence must be composed of legal moves.
        """
        util.raiseNotDefined()

def tinyMazeSearch(problem):
    """
    Returns a sequence of moves that solves tinyMaze.  For any other maze, the
    sequence of moves will be incorrect, so only use this for tinyMaze.
    """
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    return  [s, s, w, s, w, w, s, w]

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print "Start:", problem.getStartState()
    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    print "Start's successors:", problem.getSuccessors(problem.getStartState())
    """

    "*** YOUR CODE HERE ***"

    # Create a stack for DFS traversal
    stk = util.Stack()
    # Empty list to store nodes visited and directions
    visitednodes = []

    # Get the initial state of Pacman
    startState = problem.getStartState()
    stk.push([startState, ""])

    while(True):

        if stk.isEmpty():break

        currNode = stk.pop()

        # If goal state found return the action list
        if problem.isGoalState(currNode[0]):
            # From string create a new list by splitting ',' and removing NULL values
            return filter(None, currNode[1].split(","))

        elif not currNode[0] in visitednodes:
            # Mark node as visited
            visitednodes.append(currNode[0])
            # Get all successors for the current node
            successors = (problem.getSuccessors(currNode[0]))
            for successor, action, cost in successors:
                # Add the node and the directions to the stack
                stk.push([successor, currNode[1] + "," + action])

def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    # Create a stack for DFS traversal
    queue = util.Queue()
    # Empty list to store nodes visited and directions
    visitednodes = []

    # Get the initial state of Pacman
    startState = problem.getStartState()
    queue.push([startState, ""])

    while (True):

        if queue.isEmpty(): break
        currNode = queue.pop()
        # If goal state found return the action list
        if problem.isGoalState(currNode[0]):
            # From string create a new list by splitting ',' and removing NULL values
            return filter(None, currNode[1].split(","))
        elif not currNode[0] in visitednodes:
            # Mark node as visited
            visitednodes.append(currNode[0])
            # Get all successors for the current node
            successors = (problem.getSuccessors(currNode[0]))
            for successor, action, cost in successors:
                # Add the node and the directions to the stack
                queue.push([successor, currNode[1] + "," + action])

def uniformCostSearch(problem):
    """Search the node of least total cost first."""

    priorityQ = util.PriorityQueue()
    startState = problem.getStartState()
    priorityQ.push([startState, "", 0], 0)
    # Empty list to store nodes visited and directions
    visitednodes = []

    while (True):

        if priorityQ.isEmpty():break
        currNode = priorityQ.pop()

        # If goal state found return the action list
        if problem.isGoalState(currNode[0]):
            # From string create a new list by splitting ',' and removing NULL values
            return filter(None, currNode[1].split(","))

        elif not currNode[0] in visitednodes:
            # Check node in visitednodes list or not
            visitednodes.append(currNode[0])
            # get the next successor
            successors = problem.getSuccessors(currNode[0])
            # Push the state, cost uptil now to the queue state. The cost will also be passed to Priority Q as an argument
            for successor, action, cost in successors:
                # cost + currNode[2] cost is the cost uptil now
                priorityQ.push([successor, (currNode[1] + "," + action), cost + currNode[2] ], cost + currNode[2] )

def nullHeuristic(state, problem=None):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem.  This heuristic is trivial.
    """
    return 0

def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"

    priorityQ = util.PriorityQueue()
    startState = problem.getStartState()
    priorityQ.push([startState, "", 0], 0)
    # Empty list to store nodes visited and directions
    visitednodes = []

    while (True):

        if priorityQ.isEmpty():break
        currNode = priorityQ.pop()

        # If goal state found return the action list
        if problem.isGoalState(currNode[0]):
            # From string create a new list by splitting ',' and removing NULL values
            return filter(None, currNode[1].split(","))

        elif not currNode[0] in visitednodes:
            # Check node in visitednodes list or not
            visitednodes.append(currNode[0])
            # get the next successor
            successors = problem.getSuccessors(currNode[0])
            # Push the state, cost uptil now to the queue state. The cost will also be passed to Priority Q as an argument
            # Also we need to add the heuristic cost as well because f = h + g
            for successor, action, cost in successors:
                priorityQ.push([successor, (currNode[1] + "," + action), cost + currNode[2] ], cost + currNode[2] + heuristic(successor, problem))

# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch


# coding=utf-8
import argparse
import json
import sys
from threading import Lock, Thread
import time
import traceback
import bottle
from bottle import Bottle, request, template, run, static_file
import requests
import random
from leader_election import Election
from data_processor import DataProcessor
from server_data import ServerData
# ------------------------------------------------------------------------------------------------------

def current_milli_time(): return int(round(time.time() * 1000))
def intRandomNumber(): return random.randint(1, 100)
def current_time_in_seconds(): return int(round(time.time()))

prapagation_delay = 5  # in second

class Blackboard:
    def __init__(self):
        self.content = ""
        self.lock = Lock()  # use lock when you modify the content

    def get_content(self):
        with self.lock:
            cnt = self.content
        return cnt

    def set_content(self, new_content):
        with self.lock:
            self.content = new_content
        return

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

class Server(Bottle):

    def __init__(self, ID, IP, servers_list):
        super(Server, self).__init__()
        self.blackboard = Blackboard()
        self.id = int(ID)
        self.ip = str(IP)
        self.servers_list = servers_list
        # list all REST URIs
        # if you add new URIs to the server, you need to add them here
        self.route("/", callback=self.index)
        self.get("/board", callback=self.get_board)
        self.post("/", callback=self.post_index)

        # we give access to the templates elements
        self.get("/templates/<filename:path>", callback=self.get_template)
        self.post("/board", callback=self.add_on_board)
        self.post("/board/<element_id>/", callback=self.modify_delete)
        self.post("/election", callback=self.election)
        self.post("/leader", callback=self.leader)
        self.get("/sync",callback=self.sync)
        self.time_in_seconds_of_first_message = 0
        self.time_in_seconds_of_last_message = 0

        # You can have variables in the URI, here's an example
        # self.post('/board/<element_id:int>/', callback=self.post_board) where post_board takes an argument (integer) called element_id
        # self.board = dict()  # global board
        # self.board_lock = Lock()  # Used for locking the board

        ServerData.leader_ip = self.servers_list[len(
            self.servers_list)-1]  # last ip as leader

        self.leader_id = len(self.servers_list)
        self.electionThread = None
        self.dataprocessThread = None

    def get_board_items(self):
        with ServerData.board_lock:
            board = ServerData.board
            return board

    def delete_key(self, key):
        print("[DELETE] " + str(key))
        with ServerData.board_lock:
            try:
                del ServerData.board[key]
            except KeyError as ex:
                print("[ERROR] " + str(ex))
            return

    def get_value(self, key):
        with ServerData.board_lock:
            value = ServerData.board[key]
            return value

    def insert_or_update_in_board(self, new_content, e_id):
        new_kew = e_id
        with ServerData.board_lock:
            # if len(new_kew.strip()) == 0:
            #     c_time = current_milli_time()
            #     new_kew = (
            #         str(c_time) + "_" + str(e_id)
            #     )  # id = 23423432_1 , (there same data in same mili second in all server, that's why I used _ and server id)
            self.blackboard.set_content(new_content)

            ServerData.board[new_kew] = self.blackboard.get_content()
            if(len(ServerData.board)) == 1 :
                self.time_in_seconds_of_first_message = current_time_in_seconds()
            elif(len(ServerData.board) == 40):
                print("Total time = {}".format((current_time_in_seconds() - self.time_in_seconds_of_first_message)))

        return new_kew

    def do_parallel_task(self, method, args=None):
        # create a thread running a new task
        # Usage example: self.do_parallel_task(self.contact_another_server, args=("10.1.0.2", "/index", "POST", params_dict))
        # this would start a thread sending a post request to server 10.1.0.2 with URI /index and with params params_dict
        thread = Thread(target=method, args=args)
        thread.daemon = True
        thread.start()

    def do_parallel_task_after_delay(self, delay, method, args=None):
        # create a thread, and run a task after a specified delay
        # Usage example: self.do_parallel_task_after_delay(10, self.start_election, args=(,))
        # this would start a thread starting an election after 10 seconds
        thread = Thread(
            target=self._wrapper_delay_and_execute, args=(delay, method, args)
        )
        thread.daemon = True
        thread.start()

    def _wrapper_delay_and_execute(self, delay, method, args):
        time.sleep(delay)  # in sec
        method(*args)

    def contact_another_server(self, srv_ip, URI, req="POST", params_dict=None):
        # Try to contact another serverthrough a POST or GET
        # usage: server.contact_another_server("10.1.1.1", "/index", "POST", params_dict)
        success = False
        try:
            if "POST" in req:
                res = requests.post(
                    "http://{}{}".format(srv_ip, URI), data=params_dict)
            elif "GET" in req:
                res = requests.get("http://{}{}".format(srv_ip, URI))
            # result can be accessed res.json()
            if res.status_code == 200:
                success = True
        except Exception as e:
            print("[ERROR] " + str(e))
        return success

    def propagate_to_all_servers(self, URI, req="POST", params_dict=None):
        for srv_ip in self.servers_list:
            if srv_ip != self.ip:  # don't propagate to yourself
                success = self.contact_another_server(
                    srv_ip, URI, req, params_dict)
                if not success:
                    print("[WARNING ]Could not contact server {}".format(srv_ip))

    def start_leader_election_thread(self):
        if(self.electionThread == None or (not self.electionThread.is_alive())):
            print("+=====start_leader_electionhread==================")
            electionThread = Election(self.ip, self.id, self.servers_list)
            electionThread.start()

    def start_data_processing_thread(self):
        if(self.dataprocessThread == None or not self.dataprocessThread.isRunning()):
            print("+===============start_data_processing_thread=====================")
            self.dataprocessThread = DataProcessor(
                self.id, self.ip, self.servers_list)
            self.dataprocessThread.start()

    # route to ('/')

    def index(self):
        # we must transform the blackboard as a dict for compatiobility reasons
        # board = dict()
        board = self.get_board_items()
        return template(
            "server/templates/index.tpl",
            board_title="Server {} ({})".format(self.id, self.ip),
            board_dict=board.items(),
            server_title = ServerData.server_title,
            members_name_string="Faiz Ahmed & Md Abu Noman Majumdar",
        )

    # get on ('/board')
    def get_board(self):
        # we must transform the blackboard as a dict for compatibility reasons
        # board = dict()
        board = self.get_board_items()
        return template(
            "server/templates/blackboard.tpl",
            board_title="Server {} ({})".format(self.id, self.ip),
            server_title = ServerData.server_title,
            board_dict=board.items(),
        )

    # post on ('/')
    def post_index(self):
        try:
            # we read the POST form, and check for an element called 'entry'
            new_entry = request.forms.get("entry")

            print("Received: {}".format(new_entry))
        except Exception as e:
            print("[ERROR] " + str(e))

    # post on ('/board')
    def add_on_board(self):
        try:
            text = request.forms.get("entry")

            if "id" in request.forms:  # got from Leader
                self.insert_or_update_in_board(text, request.forms.get("id"))
            else:
                if ServerData.leader_ip == self.ip:
                    self.start_data_processing_thread()
                    self.dataprocessThread.pushData(text)
                else:
                    # If Coordinator does not response start election
                    success = self.contact_another_server(
                        ServerData.leader_ip, "/board", "POST", {"entry": text})
                    print("leader : {} , text : {} , success {}".format(
                        ServerData.leader_ip, text, success))
                    if not success: # start election
                        print("Running election")
                        self.start_leader_election_thread()
        except Exception as ex:
            print("[ERROR] " + str(ex))

    # post on ('/election')
    def election(self):
        try:
            self.start_leader_election_thread()
            print("found election from : {}".format(request.forms.get("l_ip")))
        except Exception as ex:
            print("[ERROR] " + str(ex))

    # post on ('/leader')
    def leader(self):
        try:
            ServerData.leader_ip = request.forms.get("l_ip")
            self.leader_id = request.forms.get("l_id")
            print("leader_ip=> {}".format(ServerData.leader_ip))
            if(ServerData.leader_ip != self.ip):
                ServerData.server_title = "Slave"
                if self.dataprocessThread != None:
                    print("Stopping processor thread")
                    self.dataprocessThread.stop()
                    self.dataprocessThread = None

            print(True)
        except Exception as ex:
            print("[ERROR] " + str(ex))

    def modify_delete(self, element_id):
        try:
            print("modify_delete ", element_id)
            isDelete = request.forms.get("delete", type=int)
            entry = request.forms.get("entry")
            print("e_id {} isDelete {} entry {} ".format(
                element_id, isDelete, entry))
            if element_id in self.get_board_items():
                if isDelete == 1:
                    self.delete_key(element_id)
                else:
                    self.insert_or_update_in_board(entry, element_id)
            else:
                print("[ERROR] No Entry")

            # Propagate upadate to other servers, "propagated" flag is used to tackle retransmission again from server
            if not "propagated" in request.forms:
                self.do_parallel_task_after_delay(
                    prapagation_delay,
                    self.propagate_to_all_servers,
                    args=(
                        "/board/" + element_id + "/",
                        "POST",
                        {
                            "entry": entry,
                            "id": element_id,
                            "delete": isDelete,
                            "propagated": 1,
                        },
                    ),
                )
        except Exception as identifier:
            print("[ERROR] " + str(identifier))

    # get "/sync"
    def sync(self):
        return self.get_board_items()

    def get_template(self, filename):
        return static_file(filename, root="./server/templates/")

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

def main():
    PORT = 80
    parser = argparse.ArgumentParser(
        description="Your own implementation of the distributed blackboard"
    )
    parser.add_argument(
        "--id", nargs="?", dest="id", default=1, type=int, help="This server ID"
    )
    parser.add_argument(
        "--servers",
        nargs="?",
        dest="srv_list",
        default="10.1.0.1,10.1.0.2",
        help="List of all servers present in the network",
    )
    args = parser.parse_args()
    server_id = args.id
    server_ip = "10.1.0.{}".format(server_id)
    servers_list = args.srv_list.split(",")
    # lead?er_ip = servers_list[len(servers_list)-1]

    try:
        server = Server(server_id, server_ip, servers_list)
        if(server_id == len(servers_list)):
            time.sleep(3)  # for starting all servers
            ## Starting election at starting
            election = Election(server_ip, server_id, servers_list)
            election.start()
        bottle.run(server, host=server_ip, port=PORT)
    except Exception as e:
        print("[ERROR] " + str(e))

# ------------------------------------------------------------------------------------------------------
if __name__ == "__main__":
    main()


n = int(input())
b = bin(n)[2:]
new_b = ''
odd_bit_value = even_bit_value = 0
for i in range(len(b)):
    if i%2 and b[i]=='1':
        odd_bit_value+=1
    elif not i%2 and b[i]=='1':
        even_bit_value+=1
if odd_bit_value<even_bit_value:
    for i in range(len(b)):
        if i%2 and b[i]=='1':
            new_b+='0'
        else:
            new_b+=b[i]
else:
    for i in range(len(b)):
        if not i%2 and b[i]=='1':
            new_b+='0'
        else:
            new_b+=b[i]
def decimal(bin_num):
    dec_num = 0
    for i in range(len(bin_num)):
        dec_num+=int(bin_num[i])*(2**i)
    return dec_num

print(decimal(new_b[::-1]))


import discord
from discord.ext import commands
import sqlite3

class Role(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.conn = sqlite3.connect('./data/db/reactionroles.db')
        self.c = self.conn.cursor()
        self.c.execute('''CREATE TABLE IF NOT EXISTS reaction_roles
                          (message_id INTEGER, emoji TEXT, role_id INTEGER)''')

    @commands.Cog.listener()
    async def on_ready(self):
        await self.check_reaction_roles()

    async def check_reaction_roles(self):
        self.c.execute("SELECT DISTINCT message_id FROM reaction_roles")
        messages = self.c.fetchall()
        for (message_id,) in messages:
            try:
                channel = self.bot.get_channel(message_id)  # Adjust this if channel_id is different from message_id
                message = await channel.fetch_message(message_id)
                for reaction in message.reactions:
                    async for user in reaction.users():
                        self.c.execute("SELECT role_id FROM reaction_roles WHERE message_id=? AND emoji=?",
                                       (message.id, str(reaction.emoji)))
                        role_id = self.c.fetchone()
                        if role_id:
                            role = message.guild.get_role(role_id[0])
                            if role:
                                if reaction.emoji in [str(r.emoji) for r in user.reactions if r.message.id == message_id]:
                                    await user.add_roles(role)
                                else:
                                    await user.remove_roles(role)
                # Re-establish the bot's awareness of these reactions
                existing_reactions = [str(reaction) for reaction in message.reactions]
                self.c.execute("SELECT emoji FROM reaction_roles WHERE message_id=?", (message_id,))
                for (emoji,) in self.c.fetchall():
                    if emoji not in existing_reactions:
                        await message.add_reaction(emoji)
            except Exception as e:
                print(f"Failed to process message {message_id}: {e}")

    @commands.command()
    async def roles(self, ctx, words: str, *emoji_role_pairs):
        """Creates a reaction role message."""
        if len(emoji_role_pairs) % 2 != 0:
            await ctx.send("Please provide emoji and role pairs.")
            return

        message = await ctx.send(words)
        for i in range(0, len(emoji_role_pairs), 2):
            await message.add_reaction(emoji_role_pairs[i])
            self.c.execute("INSERT INTO reaction_roles VALUES (?, ?, ?)",
                           (message.id, emoji_role_pairs[i], int(emoji_role_pairs[i+1][3:-1])))
        self.conn.commit()

    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        if payload.member.bot:
            return
        self.c.execute("SELECT role_id FROM reaction_roles WHERE message_id=? AND emoji=?",
                       (payload.message_id, str(payload.emoji)))
        role_id = self.c.fetchone()
        if role_id:
            guild = self.bot.get_guild(payload.guild_id)
            role = guild.get_role(role_id[0])
            if role:
                member = guild.get_member(payload.user_id)
                await member.add_roles(role)

    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, payload):
        self.c.execute("SELECT role_id FROM reaction_roles WHERE message_id=? AND emoji=?",
                       (payload.message_id, str(payload.emoji)))
        role_id = self.c.fetchone()
        if role_id:
            guild = self.bot.get_guild(payload.guild_id)
            role = guild.get_role(role_id[0])
            if role:
                member = guild.get_member(payload.user_id)
                await member.remove_roles(role)

    @commands.Cog.listener()
    async def on_message_delete(self, message):
        self.c.execute("DELETE FROM reaction_roles WHERE message_id=?", (message.id,))
        self.conn.commit()

async def setup(bot):
    await bot.add_cog(Role(bot))


from src.models import EmailMessageModel, EmailModel, NumberModel, PhoneMessageModel

def build_email_msg(msg: EmailMessageModel) -> str:
    message = msg.body.replace("\n\n", '').replace('\xa0', '')
    words = message.split(' ')
    x = [word for word in words if word != " " and word != '']
    message = " ".join(x).replace("\n", '')
    if len(message) > 50:
        message = "Message to big, check web page!"
    return f"New message received: \n" \
           f"From :{msg.from_email}:\n" \
           f"Subject: {msg.subject}\n" \
           f"Text: \n{message}"

def build_all_emails_msg(emails: list[EmailModel], only_email=False) -> str:
    msg = ""
    if only_email:
        for email in emails:
            msg += f"{email.email_address}\n"
        return msg
    for email in emails:
        msg += f"`{email.email_address}`\n"
        if email.note:
            msg += f'{email.note}\n'
        msg += '\n'
    return msg

def build_new_emails_msg(emails: list[str]) -> str:
    if len(emails) == 1:
        return f'Email created - `{emails[0]}`'
    msg = f"Created {len(emails)} new emails:"
    for email in emails:
        msg += f'\n`{email}`\n'
    return msg

def build_all_numbers_msg(numbers: list[NumberModel]) -> str:
    if not numbers:
        return "You haven't created any numbers"
    msg = "Your active numbers:\n"
    for number in numbers:
        msg += f"Google -> `+{number.number}`\n"
    return msg

def balance_message(balance: str) -> str:
    return f"Your balance - *{balance}*\n" \
           f"Top up balance:\n " \
           f"`TT2Qx3LkQk4r5XTa9hnYTxuqbN5BCghBEe` USDT-TRX\n" \
           f"BTC -> `3BoRxs8xywdYA5NUs5MttXUZ2kkRKkzxJM`\n\n" \
           f"⚡Attention! The minimum one transaction is 500 rubles\n" \
           f"⚡Transaction less than 500 rubles will not be credited to your account!\n\n" \
           f"After payment, the cryptocurrency will be converted into rubles and credited to your account\n" \
           f"This deposit address is assigned to you, you can use it for deposits at any time"

# use when get a new message on number
def build_new_msg_number(msg: PhoneMessageModel) -> str:
    message = msg.message.replace("\n\n", '').replace('\xa0', '')
    words = message.split(' ')
    x = [word for word in words if word != " " and word != '']
    message = " ".join(x)
    return f"New message received: \n" \
           f"To: {msg.to_number}\n" \
           f"Text: \n{message}"


import os
import os.path
import torchvision.transforms.functional as TF
import util
import numpy as np
import logging
from collections import defaultdict
import torch
import random
import matplotlib
import sys
from abc import abstractmethod
matplotlib.use('agg')
np.set_printoptions(threshold=sys.maxsize)

class Dataset(torch.utils.data.Dataset):

    def __init__(self, data_dict, transform=None, normaliser=2 ** 8 - 1, is_valid=False, is_inference=False):
        """Initialisation for the Dataset object

        :param data_dict: dictionary of dictionaries containing images
        :param transform: PyTorch image transformations to apply to the images
        :returns: N/A
        :rtype: N/A

        """
        self.transform = transform
        self.data_dict = data_dict
        self.normaliser = normaliser
        self.is_valid = is_valid
        self.is_inference = is_inference

    def __len__(self):
        """Returns the number of images in the dataset

        :returns: number of images in the dataset
        :rtype: Integer

        """
        return (len(self.data_dict.keys()))

    def __getitem__(self, idx):
        """Returns a pair of images with the given identifier. This is lazy loading
        of data into memory. Only those image pairs needed for the current batch
        are loaded.

        :param idx: image pair identifier
        :returns: dictionary containing input and output images and their identifier
        :rtype: dictionary

        """
        while True:

            if self.is_inference:

                input_img = util.ImageProcessing.load_image(
                    self.data_dict[idx]['input_img'], normaliser=self.normaliser)
                output_img = util.ImageProcessing.load_image(
                    self.data_dict[idx]['output_img'], normaliser=self.normaliser)

                if self.normaliser==1:
                    input_img = input_img.astype(np.uint8)
                    output_img = output_img.astype(np.uint8)

                input_img = TF.to_pil_image(input_img)
                input_img = TF.to_tensor(input_img)
                output_img = TF.to_pil_image(output_img)
                output_img = TF.to_tensor(output_img)

                return {'input_img': input_img, 'output_img': output_img,
                        'name': self.data_dict[idx]['input_img'].split("/")[-1]}

            elif idx in self.data_dict:

                output_img = util.ImageProcessing.load_image(
                    self.data_dict[idx]['output_img'], normaliser=self.normaliser)
                input_img = util.ImageProcessing.load_image(
                    self.data_dict[idx]['input_img'], normaliser=self.normaliser)

                if self.normaliser==1:
                    input_img = input_img.astype(np.uint8)
                    output_img = output_img.astype(np.uint8)

                input_img = TF.to_pil_image(input_img)
                output_img = TF.to_pil_image(output_img)

                if not self.is_valid:

                    if random.random()>0.5:

                        # Random horizontal flipping
                        if random.random() > 0.5:
                            input_img = TF.hflip(input_img)
                            output_img = TF.hflip(output_img)

                        # Random vertical flipping
                        if random.random() > 0.5:
                            input_img = TF.vflip(input_img)
                            output_img = TF.vflip(output_img)

                # Transform to tensor
                input_img = TF.to_tensor(input_img)
                output_img = TF.to_tensor(output_img)

                return {'input_img': input_img, 'output_img': output_img,
                        'name': self.data_dict[idx]['input_img'].split("/")[-1]}

class DataLoader():

    def __init__(self, data_dirpath, img_ids_filepath):
        """Initialisation function for the data loader

        :param data_dirpath: directory containing the data
        :param img_ids_filepath: file containing the ids of the images to load
        :returns: N/A
        :rtype: N/A

        """
        self.data_dirpath = data_dirpath
        self.img_ids_filepath = img_ids_filepath

    @abstractmethod
    def load_data(self):
        """Abstract function for the data loader class

        :returns: N/A
        :rtype: N/A

        """
        pass

    @abstractmethod
    def perform_inference(self, net, data_dirpath):
        """Abstract function for the data loader class

        :returns: N/A
        :rtype: N/A

        """
        pass

class Adobe5kDataLoader(DataLoader):

    def __init__(self, data_dirpath, img_ids_filepath):
        """Initialisation function for the data loader

        :param data_dirpath: directory containing the data
        :param img_ids_filepath: file containing the ids of the images to load
        :returns: N/A
        :rtype: N/A

        """
        super().__init__(data_dirpath, img_ids_filepath)
        self.data_dict = defaultdict(dict)

    def load_data(self):
        """ Loads the Samsung image data into a Python dictionary

        :returns: Python two-level dictionary containing the images
        :rtype: Dictionary of dictionaries

        """

        logging.info("Loading Adobe5k dataset ...")

        with open(self.img_ids_filepath) as f:
            '''
            Load the image ids into a list data structure
            '''
            image_ids = f.readlines()
            # you may also want to remove whitespace characters like `\n` at the end of each line
            image_ids_list = [x.rstrip() for x in image_ids]

        idx = 0
        idx_tmp = 0
        img_id_to_idx_dict = {}

        for root, dirs, files in os.walk(self.data_dirpath):

            for file in files:

                img_id = file.split("-")[0]

                is_id_in_list = False
                for img_id_test in image_ids_list:
                    if img_id_test == img_id:
                        is_id_in_list = True
                        break

                if is_id_in_list:  # check that the image is a member of the appropriate training/test/validation split

                    if not img_id in img_id_to_idx_dict.keys():
                        img_id_to_idx_dict[img_id] = idx
                        self.data_dict[idx] = {}
                        self.data_dict[idx]['input_img'] = None
                        self.data_dict[idx]['output_img'] = None
                        idx_tmp = idx
                        idx += 1
                    else:
                        idx_tmp = img_id_to_idx_dict[img_id]

                    if "input" in root:  # change this to the name of your
                                        # input data folder

                        input_img_filepath = file

                        self.data_dict[idx_tmp]['input_img'] = root + \
                            "/" + input_img_filepath

                    elif ("output" in root):  # change this to the name of your
                                             # output data folder

                        output_img_filepath = file

                        self.data_dict[idx_tmp]['output_img'] = root + \
                            "/" + output_img_filepath

                else:

                    logging.debug("Excluding file with id: " + str(img_id))

        for idx, imgs in self.data_dict.items():
            assert ('input_img' in imgs)
            assert ('output_img' in imgs)

        return self.data_dict


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

from odoo import models, fields, api

class Saleflspwizard(models.TransientModel):
    _name = 'flspsaleapproval.saleflspwizard'
    _description = "Wizard: testing my wizard"

    @api.model
    def default_get(self, fields):
        res = super(Saleflspwizard, self).default_get(fields)
        sale_order = self.env['sale.order']
        order_id = self.env.context.get('default_order_id') or self.env.context.get('active_id')
        if order_id:
            sale_order = self.env['sale.order'].browse(order_id)
        if sale_order.exists():
            if 'order_id' in fields:
                res['order_id'] = sale_order.id
            if 'validity_date' in fields:
                res['validity_date'] = sale_order.validity_date
            if 'partner_id' in fields:
                res['partner_id'] = sale_order.partner_id.id
            #if 'order_line' in fields:
            #res['order_line'] = sale_order.order_line

        approval_list = []
        for so_line in [l for l in sale_order.order_line]:
            approval_list.append([0, 0, {
                'flsp_sale_line_product_id': so_line.id,
                'sequence': so_line.sequence,
                'product_template_id': so_line.product_template_id.id,
                'product_uom_qty': so_line.product_uom_qty,
                'product_uom': so_line.product_template_id.uom_id.id,
                'price_unit': so_line.price_unit,
                'discount': so_line.discount,
                'sale_order_line_id': so_line.id,
                'tax_id': so_line.tax_id.id,
                'order_id': so_line.order_id.id,
                'price_subtotal': so_line.price_subtotal,
            }])
        res['flsp_order_line_ids'] = approval_list
        res = self._convert_to_write(res)
        return res

    order_id = fields.Many2one('sale.order', string='Order Reference', readonly=True)
    partner_id = fields.Many2one('res.partner', string='Customer', readonly=True)
    validity_date = fields.Date(string='Expiration')
    flsp_order_line_ids = fields.One2many('flsp.so.line', 'flsp_sale_line_product_id', string='Components')

    def flsp_approve(self):
        self.ensure_one()
        for approval_line in self.flsp_order_line_ids:
            approval_line.sale_order_line_id.write({
                'discount': approval_line.discount,
            })
            approval_line.sale_order_line_id.write({
                'price_unit': approval_line.price_unit,
            })
        self.order_id.write({'flsp_state': 'approved', })
        self.order_id.write({'flsp_approval_approved': True, })
        self.env['flspautoemails.bpmemails'].send_email(self, 'SO0002')

        self.order_id.button_flsp_confirm()

        return {'type': 'ir.actions.act_window_close'}

        body = '
Hi there,
'
        body += '
'
        body += '
The discount approval requested for the quotation: '+self.order_id.name+' has been approved.
'
        body += '

'
        body += '

'
        body += '
'
        body += '  Access Sales Order'
        body += '

'
        body += '
'
        body += '
Thank you!
'

        self.env['mail.mail'].create({
            'body_html': body,
            'subject': 'Odoo - Sales Discount Approved',
            'email_to': 'alexandresousa@smartrendmfg.com; '+self.order_id.user_id.login,
            'auto_delete': True,
        }).send()

        return {'type': 'ir.actions.act_window_close'}

        #self.order_id.write({'validity_date': self.validity_date,})

    def flsp_open_sale_wizard(self):
        self.order_line.order_id |= self.order_id
        return {}

class FlspSOline(models.TransientModel):
    """Sales Approval"""
    _name = "flsp.so.line"
    _description = 'Edit Line on Sales Approval'

    flsp_sale_line_product_id = fields.Many2one('flspsaleapproval.saleflspwizard')
    sale_order_line_id = fields.Many2one('sale.order.line', string='Sales Order Line')
    order_id = fields.Many2one('sale.order', string='Order Reference', required=True, ondelete='cascade', index=True, copy=False)

    sequence = fields.Integer(string='Sequence', default=10)
    product_template_id = fields.Many2one('product.template', string='Product Template')
    product_uom_qty = fields.Float(string='Quantity', digits='Product Unit of Measure', default=1.0)
    product_uom = fields.Many2one('uom.uom', string='Unit of Measure')
    product_uom_category_id = fields.Many2one(related='product_template_id.uom_id.category_id', readonly=True)
    price_unit = fields.Float('Unit Price', digits='Product Price', default=0.0)
    discount = fields.Float(string='Discount (%)', digits='Discount', default=0.0)
    price_subtotal = fields.Monetary(compute='_compute_amount', string='Subtotal', readonly=True, store=True)
    tax_id = fields.Many2many('account.tax', string='Taxes',
                              domain=['|', ('active', '=', False), ('active', '=', True)])
    currency_id = fields.Many2one(related='order_id.currency_id', depends=['order_id'], store=True, string='Currency',
                                  readonly=True)
    def get_approval_data(self):
        self.ensure_one()
        return {
            'flsp_sale_line_product_id': self.flsp_sale_line_product_id.id,
            'product_template_id': self.product_template_id.id,
            'sequence': self.sequence,
            'product_uom_qty': self.product_uom_qty,
            'price_unit': self.price_unit,
            'discount': self.discount,
            'sale_order_id': self.flsp_sale_line_product_id.order_id.id,
            'sale_order_line_id': self.sale_order_line_id.id,
        }

    @api.depends('product_uom_qty', 'discount', 'price_unit', 'tax_id')
    def _compute_amount(self):
        """
        Compute the amounts of the SO line.
        """
        for line in self:
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_template_id, partner=line.order_id.partner_shipping_id)
            line.update({
                'price_subtotal': taxes['total_excluded'],
            })


import sys
import math
import numpy as np
import matplotlib.pyplot as plt

from pytracer.core import Camera,Scene,Material,Light
from pytracer.objects import Sphere,Plane
from pytracer.textures import PatternTexture,ImgTexture

if __name__ == '__main__':
    w = int(sys.argv[1])
    h = int(sys.argv[2])
    aa = int(sys.argv[3])
    ratio = float(w)/h

    scene = Scene()

    m1 = Material(1.,1.,50,0.2)
    m2 = Material(1.,1.,50,0.5)

    t1 = ImgTexture('earth.png',.3)
    t2 = PatternTexture(lambda u,v:  np.array([0.,0.,1.]) if int(u*10)%2==int(v*10)%2 else np.array([1.,1.,0.]))
    t3 = PatternTexture(lambda u,v:np.array([1.,0.,0.]))
    t4 = PatternTexture(lambda u,v:  np.array([0.1,0.1,0.1]) if int(u*2)%2==int(v*2)%2 else np.array([0.3,0.,0.]))

    scene.objects = [
            Sphere([ 0., 0., -4], .5, m1,t1),
            Sphere([-1., 0., -6], .5, m1,t2),
            Sphere([ 1., 0., -2], .5, m1,t3),
            Plane([0., -.5, 0.], [0., 1., 0.],m2,t4,[1.,0.,0.]),
    ]
    scene.lights = [
            Light([5., 5., -10.],[1.,1.,1.]),
            Light([-5., 5., 10.],[1.,1.,1.]),
    ]
    scene.camera = Camera([0.,3.,2.],[0., -0.5, -1],[0.,1,-0.5],math.pi/4,ratio)
    scene.ambient = 0.05

    img = scene.draw(w,h,4,aa)
    plt.imsave('fig.png', img)


#!/usr/bin/env python3

import pandas as pd
import numpy as np

data = {"Name": ["James", "Alice", "Phil", "James","Mark"],
		"Age": [24, 28, 40, 24,48],
		"Sex": ["Male", "Female", "Male", "Male",""]}

df = pd.DataFrame(data)
print(df,"\n")

column = "Sex"
df2 = df[df[column] != ""]
print(df2)


from enum import Enum
import itertools
from typing import Any, Dict, List, Tuple

from ._ruleset import dnd5e

class _DnDRuleset(Enum):
    alignments: object = dnd5e["alignments"]
    backgrounds: object = dnd5e["backgrounds"]
    classes: object = dnd5e["classes"]
    feats: object = dnd5e["feats"]
    languages: object = dnd5e["languages"]
    metrics: object = dnd5e["metrics"]
    multiclasses: object = dnd5e["multiclasses"]
    proficiencies: object = dnd5e["proficiencies"]
    races: object = dnd5e["races"]
    skills: object = dnd5e["skills"]
    spell_lists: object = dnd5e["spell_lists"]
    subclasses: object = dnd5e["subclasses"]
    subraces: object = dnd5e["subraces"]

class DnDRuleset:
    def __init__(self):
        self.rs = self._read()

    @staticmethod
    def _read() -> Dict[str, Any]:
        rulesets = dict()
        for ruleset in _DnDRuleset:
            value = ruleset.value
            if isinstance(value, list):
                value = sorted(value)
            rulesets[ruleset.name] = value
        return rulesets

    def GetAlignmentList(self) -> Tuple[str, ...]:
        return tuple(self.rs["alignments"])

    def GetBackgroundList(self) -> Tuple[str, ...]:
        return tuple(self.rs["backgrounds"].keys())

    def GetBaseHeight(self, race: str) -> str:
        try:
            return self.rs["metrics"][race]["height"]
        except KeyError:
            return None

    def GetBaseWeight(self, race: str) -> str:
        try:
            return self.rs["metrics"][race]["weight"]
        except KeyError:
            return None

    def GetClassList(self) -> Tuple[str, ...]:
        return tuple(self.rs["classes"].keys())

    def GetFeatList(self) -> Tuple[str]:
        return tuple(self.rs["feats"].keys())

    def GetLanguageList(self, excluded_languages=None) -> Tuple[str]:
        all_languages = self.rs["languages"]
        if isinstance(excluded_languages, list):
            all_languages: List[str] = [
                l for l in all_languages if l not in excluded_languages
            ]
        return tuple(all_languages)

    def GetClassSpellList(self, klass: str, level: int, subklass=None) -> List[str]:
        if subklass in (
            "Arcane Trickster",
            "Eldritch Knight",
        ):
            klass = "Wizard"

        try:
            spell_list_by_level = self.rs["spell_lists"][klass][level]
            if len(spell_list_by_level) == 0:
                raise KeyError

            return [f"{s} (lv. {level})" for s in spell_list_by_level]
        except KeyError:
            return list()

    def GetDominantSex(self, race: str) -> str:
        try:
            return self.rs["metrics"][race]["dominant"]
        except KeyError:
            return None

    def GetEntryByBackground(self, background: str) -> Dict[str, Any]:
        try:
            return self.rs["backgrounds"][background]
        except KeyError:
            raise ValueError(f"Cannot find an entry for the '{background}' background.")

    def GetEntryByClass(self, klass: str):
        try:
            return self.rs["classes"][klass]
        except KeyError:
            raise ValueError(f"Cannot find an entry for the '{klass}' class.")

    def GetEntryByMulticlassOption(self, klass: str):
        try:
            return self.rs["multiclasses"][klass]
        except KeyError:
            return None

    def GetEntryByRace(self, race: str):
        try:
            return self.rs["races"][race]
        except KeyError:
            raise ValueError(f"Cannot find an entry for the '{race}' race.")

    def GetEntryBySubclass(self, subclass: str) -> Dict[str, Any]:
        try:
            return self.rs["subclasses"][subclass]
        except KeyError:
            raise ValueError(f"Cannot find an entry for the '{subclass}' subclass.")

    def GetEntryBySubrace(self, subrace: str):
        try:
            return self.rs["subraces"][subrace]
        except KeyError:
            raise ValueError(f"Cannot find an entry for the '{subrace}' subrace.")

    def GetFeatPerks(self, feat_name: str):
        try:
            return self.rs["feats"][feat_name]["perk"]
        except KeyError:
            return None

    def GetFeatProficiencies(self, feat: str, prof_type: str) -> list:
        try:
            return self.rs["feats"][feat]["perk"][prof_type]
        except KeyError:
            return None

    def GetFeaturesByClass(self, klass: str, level: int) -> List[str]:
        try:
            class_features = self.rs["classes"][klass]["features"]
        except KeyError:
            try:
                class_features = self.rs["subclasses"][klass]["features"]
            except KeyError:
                return []

        class_features = list(
            {k: v for k, v in class_features.items() if k <= level}.values()
        )

        return list(itertools.chain(*class_features))

    def GetFeatRequirements(self, feat_name: str):
        try:
            return self.rs["feats"][feat_name]
        except KeyError:
            return None

    def GetHitDieByClass(self, klass: str):
        try:
            return self.rs["classes"][klass]["hit_die"]
        except KeyError:
            return None

    def GetMetricsByRace(self, race: str) -> Dict[str, str]:
        """Returns metric data by race."""
        try:
            return self.rs["metrics"][race]
        except KeyError:
            return None

    def GetRaceList(self) -> Tuple[str]:
        return tuple(self.rs["races"].keys())

    def GetRacialSpellList(self, race: str, level: int):
        try:
            spell_list = self.rs["races"][race]["spells"]
        except KeyError:
            try:
                spell_list = self.rs["subraces"][race]["spells"]
            except KeyError:
                return []

        spell_list = list({k: v for k, v in spell_list.items() if k <= level}.values())

        return list(itertools.chain(*spell_list))

    def GetSkillAbility(self, skill_name: str) -> str:
        try:
            return self.rs["skills"][skill_name]["associated_ability"]
        except KeyError:
            return None

    def GetSkillList(self, excluded_skills=None) -> Tuple[str]:
        all_skills = list(self.rs["skills"].keys())
        if isinstance(excluded_skills, list):
            all_skills = [s for s in all_skills if s not in excluded_skills]
        return tuple(all_skills)

    def GetSpellSlots(self, klass: str, subklass: str, level: int) -> List[str]:
        if klass in (
            "Bard",
            "Cleric",
            "Druid",
            "Paladin",
            "Sorcerer",
            "Ranger",
            "Warlock",
            "Wizard",
        ) or subklass in (
            "Arcane Trickster",
            "Eldritch Knight",
        ):
            if subklass == "Arcane Trickster":
                klass = "Rogue"
            elif subklass == "Eldritch Knight":
                klass = "Fighter"

            spellslots = self.rs["classes"][klass]["spell_slots"][level]
            return [int(s) for s in spellslots.split(",")]
        return []

    def GetSubclassList(self, klass=None) -> Tuple[str]:
        try:
            return tuple(self.rs["classes"][klass]["subclass"])
        except KeyError:
            return tuple(self.rs["subclasses"].keys())

    def GetSubclassSpellList(self, sublass: str, level: int) -> List[str]:
        try:
            spells = self.rs["subclasses"][sublass]["bonus_spells"]
            if not isinstance(spells, dict):
                raise KeyError

            subclass_spells = list(
                {k: v for k, v in spells.items() if k <= level}.values()
            )

            return list(itertools.chain(*subclass_spells))
        except KeyError:
            return None

    def GetSubraceList(self, race=None) -> Tuple[str]:
        try:
            return tuple(self.rs["races"][race]["subrace"])
        except KeyError:
            return tuple(self.rs["subraces"].keys())

    def GetToolList(self, excluded_tools=None) -> Tuple[str]:
        all_tools = self.rs["proficiencies"]["tools"]
        if isinstance(excluded_tools, list):
            all_tools = [t for t in all_tools if t not in excluded_tools]
        return all_tools

    def GetWeaponList(self, excluded_weapons=None) -> Tuple[str]:
        _all_weapons = self.rs["proficiencies"]["weapons"]
        all_weapons = list()
        if not isinstance(excluded_weapons, list):
            martial, simple = _all_weapons.values()
            return tuple(sorted(itertools.chain(martial, simple)))
        else:
            if "Simple" not in excluded_weapons:
                all_weapons += _all_weapons["Simple"]
            if "Martial" not in excluded_weapons:
                all_weapons += _all_weapons["Martial"]
            all_weapons = [w for w in all_weapons if w not in excluded_weapons]
        return tuple(all_weapons)