from numpy import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import LDA
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']#使可视化可以显示中文

def getdata(filename1,classnumber):
    '''
    导入单个txt文件，将其转成列表
    :param filename1: 文件名
    :param classnumber: 将其判为哪一类，0or1
    :return: 生成好的data,labels
    '''
    f  = open(filename1)
    lines  = f.readlines()
    mansls= []
    for line in lines:
        a=line.split()
        a= [float(i) for i in a ]
        mansls.append(a)

    manslabels= [classnumber]*shape(mansls)[0]
    return mansls,manslabels

def pca_new(dataMat,n):
    '''

    :param dataMat: 待降维的数据集（已转成矩阵）
    :param n: 需降到的维度
    :return: 降维后的数据集，排序后的特征值，排序后的特征向量
    '''

    meanVals = mean(dataMat, axis=0)
    meanRemoved = dataMat - meanVals
    covMat = cov(meanRemoved, rowvar=0)
    eigvals, eigVects = linalg.eig(mat(covMat))
    eigValInd = argsort(-eigvals)
    taken_eigVects=eigVects[eigValInd[:n],:]#取前N个特征向量
    dataMat = dot(dataMat, taken_eigVects.T)
    final_eigvals=eigvals[eigValInd]
    final_eigVects=eigVects[eigValInd,:]

    return dataMat,final_eigvals,final_eigVects

#读入数据
mansls,manslabels1=getdata('boy.txt',0)
girlsls,girlslabels1=getdata('girl.txt',1)
m=mansls.copy()
g=girlsls.copy()
ml=manslabels1.copy()
gl=girlslabels1.copy()
ml.extend(gl)
alllabels = ml
m.extend(g)
alldatas = mat(m)
#训练集降维
down_Mat,eigvals,eigVects=pca_new(alldatas,2)
eigVects[:2]=eigVects[:2]*300#为了看得见投影面和数据点

#可视化
ax=plt.subplot(223,projection='3d')
plt.title('均一化')
ax.scatter(array((mansls-mean(mansls))/sum(mansls))[:, 0], array((mansls-mean(mansls))/sum(mansls))[:, 1], array((mansls-mean(mansls))/sum(mansls))[:, 2], c='red')
ax.scatter(array((girlsls-mean(girlsls))/sum(girlsls))[:, 0], array((girlsls-mean(girlsls))/sum(girlsls))[:, 1], array((girlsls-mean(girlsls))/sum(girlsls))[:, 2], c='green')

ax=plt.subplot(221,projection='3d')
plt.title('原始数据')
ax.scatter(array(mansls)[:, 0], array(mansls)[:, 1], array(mansls)[:, 2], c='red')
ax.scatter(array(girlsls)[:, 0], array(girlsls)[:, 1], array(girlsls)[:, 2], c='green')

ax=plt.subplot(222,projection='3d')
plt.title('投影平面')
plt.xlim(150,200)
plt.ylim(40,90)

ax.scatter(array(mansls)[:, 0], array(mansls)[:, 1], array(mansls)[:, 2], c='red')
ax.scatter(array(girlsls)[:, 0], array(girlsls)[:, 1], array(girlsls)[:, 2], c='green')
ax.plot_trisurf([0,eigVects[:2][0,0],eigVects[:2][1,0]], [0,eigVects[:2][0,1],eigVects[:2][1,1]],[0,eigVects[:2][0,2],eigVects[:2][1,2]])

plt.subplot(224)
plt.title('投影之后')
plt.scatter(array(down_Mat)[:len(mansls), 0],array(down_Mat)[:len(mansls), 1], c='red')
plt.scatter(array(down_Mat)[len(mansls):, 0], array(down_Mat)[len(mansls):, 1], c='green')

plt.show()

#--------------降维后再使用LDA----------------------
#用降维的数据测试LDA
w,mean1,mean2,group1,group2= LDA.train(down_Mat[:len(mansls), :],down_Mat[len(mansls):, :])
#将测试集降维
testboy,labels=LDA.getdata('boy82.txt',0)
testboy = mat(testboy)
#训练集降维
test_Mat,test_eigvals,test_eigVects=pca_new(testboy,2)
group3=test_Mat.T
count=0
for i in range(shape(group3)[1]):
    if (LDA.predict(group3[:,i].T,w,mean1,mean2))[0,0]>=0:#这里要注意和测试数据对应
        count = count+1
print('降维后的准确率：',count/shape(group3)[1])#降维后有0.96准确率，而没降维只有0.84(用身高，体重)


# -*- coding: utf-8 -*-
"""
    Jellybeans Colorscheme
    ~~~~~~~~~~~~~~~~~~~~~~

    Converted by Vim Colorscheme Converter
"""
from pygments.style import Style
from pygments.token import Token, Keyword, Number, Comment, Name, Operator, String, Generic

class JellybeansStyle(Style):

    background_color = '#151515'
    styles = {
        Token:              'noinherit #e8e8d3 bg:#151515',
        Generic.Traceback:  'noinherit bg:#902020',
        Generic.Heading:    '#70b950 bold',
        Comment.Preproc:    'noinherit #8fbfdc',
        Name.Constant:      'noinherit #cf6a4c',
        Generic.Subheading: '#70b950 bold',
        Keyword:            'noinherit #8197bf',
        Name.Tag:           'noinherit #8197bf',
        Generic.Inserted:   'noinherit bg:#032218',
        Keyword.Type:       'noinherit #ffb964',
        Name.Variable:      'noinherit #c6b6ee',
        Generic.Deleted:    'noinherit #220000 bg:#220000',
        Number:             'noinherit #cf6a4c',
        Operator.Word:      'noinherit #e8e8d3 bg:#151515',
        Name.Function:      'noinherit #fad07a',
        Name.Entity:        'noinherit #799d6a',
        Name.Exception:     'noinherit #ffb964',
        Comment:            'noinherit #888888 italic',
        Generic.Output:     'noinherit #808080 bg:#151515',
        Name.Attribute:     'noinherit #fad07a',
        String:             'noinherit #99ad6a',
        Name.Label:         'noinherit #ffb964',
        Generic.Error:      'noinherit bg:#902020',
    }


import random
class space:
  def __init__(self,name,color,value,kind):
    self.name = ""
    self.color = ""
    self.value = 0
    self.kind = ""

board = []

go = space("","",0,"")
go.name = "Go"
go.value =200
go.kind = "go"
board.append(go)

MeditAve = space("","",0,"")
MeditAve.name = "Mediteranean Avenue"
MeditAve.color = "brown"
MeditAve.value =60
MeditAve.kind = "property"
board.append(MeditAve)

ComChest1 = space("","",0,"")
ComChest1.name = "Community Chest"
ComChest1.kind = "community chest"
board.append(ComChest1)

BalticAve = space("","",0,"")
BalticAve.name = "Baltic Avenue"
BalticAve.color = "brown"
BalticAve.value =60
BalticAve.kind = "property"
board.append(BalticAve)

Tax = space("","",0,"")
Tax.name = "Income Tax"
Tax.value =200
Tax.kind = "income tax"
board.append(Tax)

ReadRail = space("","",0,"")
ReadRail.name = "Reading Railroad"
ReadRail.value =200
ReadRail.kind = "property"
board.append(ReadRail)

OrienAve = space("","",0,"")
OrienAve.name = "Oriental Avenue"
OrienAve.color = "light blue"
OrienAve.value =100
OrienAve.kind = "property"
board.append(OrienAve)

Chance1 = space("","",0,"")
Chance1.name = "Chance"
Chance1.kind = "chance"
board.append(Chance1)

VerAve = space("","",0,"")
VerAve.name = "Vermont Avenue"
VerAve.color = "light blue"
VerAve.value =100
VerAve.kind = "property"
board.append(VerAve)

ConAve = space("","",0,"")
ConAve.name = "Connecticut Avenue"
ConAve.color = "light blue"
ConAve.value =120
ConAve.kind = "property"
board.append(ConAve)

Jail = space("","",0,"")
Jail.name = "Jail"
Jail.kind = "jail"
board.append(Jail)

CharPlace = space("","",0,"")
CharPlace.name = "St.Charles Place"
CharPlace.color = "pink"
CharPlace.value =140
CharPlace.kind = "property"
board.append(CharPlace)

ElecCom = space("","",0,"")
ElecCom.name = "Electric Company"
ElecCom.value =150
ElecCom.kind = "property"
board.append(ElecCom)

StaAve = space("","",0,"")
StaAve.name = "States Avenue"
StaAve.color = "pink"
StaAve.value =140
StaAve.kind = "property"
board.append(StaAve)

VirAve = space("","",0,"")
VirAve.name = "Virginia Avenue"
VirAve.color = "pink"
VirAve.value =160
VirAve.kind = "property"
board.append(VirAve)

PenRail = space("","",0,"")
PenRail.name = "Pennsylvania Railroad"
PenRail.value =200
PenRail.kind = "property"
board.append(PenRail)

JamePlace = space("","",0,"")
JamePlace.name = "St.James Place"
JamePlace.color = "orange"
JamePlace.value =180
JamePlace.kind = "property"
board.append(JamePlace)

ComChest2 = space("","",0,"")
ComChest2.name = "Community Chest"
ComChest2.kind = "community chest"
board.append(ComChest2)

TenAve = space("","",0,"")
TenAve.name = "Tennessee Avenue"
TenAve.color = "orange"
TenAve.value =180
TenAve.kind = "property"
board.append(TenAve)

NyAve = space("","",0,"")
NyAve.name = "New York Avenue"
NyAve.color = "orange"
NyAve.value =200
NyAve.kind = "property"
board.append(NyAve)

FreePark = space("","",0,"")
FreePark.name = "Free Parking"
FreePark.kind = "free parking"
board.append(FreePark)

KenAve = space("","",0,"")
KenAve.name = "Kentucky Avenue"
KenAve.color = "red"
KenAve.value =220
KenAve.kind = "property"
board.append(KenAve)

Chance2 = space("","",0,"")
Chance2.name = "Chance"
Chance2.kind = "chance"
board.append(Chance2)

FleeStr = space("","",0,"")
FleeStr.name = "Fleet Street"
FleeStr.color = "red"
FleeStr.value =220
FleeStr.kind = "property"
board.append(FleeStr)

TraSquare = space("","",0,"")
TraSquare.name = "Trafalgar Square"
TraSquare.color = "red"
TraSquare.value =240
TraSquare.kind = "property"
board.append(TraSquare)

FenStation = space("","",0,"")
FenStation.name = "Fenchurch St. Station"
FenStation.value =200
FenStation.kind = "property"
board.append(FenStation)

LeiSquare = space("","",0,"")
LeiSquare.name = "Leicester Square"
LeiSquare.color = "yellow"
LeiSquare.value =260
LeiSquare.kind = "property"
board.append(LeiSquare)

CovStr = space("","",0,"")
CovStr.name = "Coventry Street"
CovStr.color = "yellow"
CovStr.value =260
CovStr.kind = "property"
board.append(CovStr)

WatWorks = space("","",0,"")
WatWorks.name = "Water Works"
WatWorks.value =150
WatWorks.kind = "property"
board.append(WatWorks)

Piccad = space("","",0,"")
Piccad.name = "Piccadilly"
Piccad.color = "yellow"
Piccad.value =280
Piccad.kind = "property"
board.append(Piccad)

GoToJail = space("","",0,"")
GoToJail.name = "Go To Jail"
GoToJail.kind = "go to jail"
board.append(GoToJail)

RegStr = space("","",0,"")
RegStr.name = "Regent Street"
RegStr.color = "green"
RegStr.value =300
RegStr.kind = "property"
board.append(RegStr)

OxStr = space("","",0,"")
OxStr.name = "Oxford Street"
OxStr.color = "green"
OxStr.value =300
OxStr.kind = "property"
board.append(OxStr)

ComChest3 = space("","",0,"")
ComChest3.name = "Community Chest"
ComChest3.kind = "community chest"
board.append(ComChest3)

BonStr = space("","",0,"")
BonStr.name = "Bond Street"
BonStr.color = "green"
BonStr.value =320
BonStr.kind = "property"
board.append(BonStr)

LivSta = space("","",0,"")
LivSta.name = "Liverpool St. Station"
LivSta.value =200
LivSta.kind = "property"
board.append(LivSta)

Chance3 = space("","",0,"")
Chance3.name = "Chance"
Chance3.kind = "chance"
board.append(Chance3)

ParLan = space("","",0,"")
ParLan.name = "Park Lane"
ParLan.color = "blue"
ParLan.value =350
ParLan.kind = "property"
board.append(ParLan)

SuTask = space("","",0,"")
SuTask.name = "Super Task"
SuTask.kind = "super task"
board.append(SuTask)

MayFair = space("","",0,"")
MayFair.name = "May Fair"
MayFair.color = "blue"
MayFair.value =400
MayFair.kind = "property"
board.append(MayFair)

players = int(input("How many players are there?"))
turn = 1
money = []
for i in range(players):
  money.append(1500)
propertys = []
for i in range(players):
  propertys.append([])
location = []
for i in range(players):
  location.append(0)
def next(turn,players):
  turn += 1
  if turn > players:
    turn = 1
  return turn
tasks = ["Advance to Go","Advance to St.Charles Place","Get out of Jail Free","Go back 3 spaces","Go to Jail","Pay each player 100 dollars"]
jailfree = []
jail= []
while True:
  print("Its player "+str(turn)+" turn" )
  input("Press enter to roll the dice!")
  dice = random.randint(2,12)
  if turn not in jail:

    spot = location[turn-1] + dice
    while spot>len(board):
      spot = spot - len(board)

  print("You rolled " +str(dice))
  if turn not in jail:
    print("You landed on " +board[spot].name )
  if board[spot].kind == "property":
    if money[turn-1]>board[spot].value:
      option = input("Would you like to purchase property?").lower()
      if option == "yes":
        board[spot].kind = "bought property"
        print("You have now bought property!")
        money[turn-1]-= board[spot].value
        propertys[turn-1].append(board[spot].name)
    else:
      print("Sorry you don't have enough money to buy this property")
  elif board[spot].kind == "bought property":
    for i in range(len(propertys)):
      if board[spot] in propertys[i]:
        owner = i+1
        break
    if board[spot].value > money[turn-1]:
      money[owner]+= money[turn-1]
      money[turn-1] = 0
    else:
      money[owner]+=board[spot].value
      money[turn-1]-=board[spot].value
    print("Sorry you have to give "+ str(board[spot].value)+" to player "+str(owner))
  elif board[spot].kind == "chance" or board[spot].kind == "community chest":
    card = random.choice(tasks)
    print("You drew " + card)
    if card == "Advance to Go":
      location[turn-1]=0
      money[turn-1]+=100
    if card == "Advance to St.Charles Place":
      location[turn-1]=board.index(CharPlace)
    if card == "Get out of Jail Free":
      jailfree.append(turn)
    if card == "Go back 3 spaces":
      location[turn-1]-=3
    if card == "Go to Jail":
      location[turn-1]=board.index(GoToJail)
      jail.append(turn)
      if turn in jailfree:
        print("You are out of Jail!")
        jailfree.remove(turn)
    if card == "Pay each player 100 dollars":
      money[turn-1]-=(players-1)*100
      for i in range (players):
        if i!=turn:
          money[i]+=100
    elif board[spot].kind == "free parking":
      print("You landed on Free Parking! You will now recive $150")
      money[turn-1]+=150
    elif board[spot].kind == "go":
      print("You are on go")
      money[turn-1]+=200
    elif board[spot].kind == "go to jail":
      if turn in jail:
        print("You are in jail")
        if dice == 12:
          jail.remove(turn)
          print("You rolled 12! You are now out of jail")
        elif money[turn-1]>50:
          pay = input("Do you want to pay $50 to get out of jail?").lower()
          if pay == "yes":
            money[turn-1]-=50
            jail.remove(turn)
    elif board[spot].kind == "income tax":
      print("You have landed on income tax. You have to pay each player $100")
      money[turn]-=100
  turn = next(turn,players)


import queueUsingLinkedList as queue

#creation

class BSTNode:
    def __init__(self, data):
        self.data = data
        self.leftChild = None
        self.rightChild = None

#insertion

def insertNode(rootNode, nodeValue):
    if rootNode.data == None:
        rootNode.data = nodeValue
    elif nodeValue <= rootNode.data:
        if rootNode.leftChild is None:
            rootNode.leftChild = BSTNode(nodeValue)
        else:
            insertNode(rootNode.leftChild, nodeValue)
    else:
        if rootNode.rightChild is None:
            rootNode.rightChild = BSTNode(nodeValue)
        else:
            insertNode(rootNode.rightChild, nodeValue)
    return ("Inserted")

#preOrder traversal

def preOrderTraversal(rootNode):
    if not rootNode:
        return
    print(rootNode.data)
    preOrderTraversal(rootNode.leftChild)
    preOrderTraversal(rootNode.rightChild)

#inOrder traversal

def inOrderTraversal(rootNode):
    if not rootNode:
        return
    preOrderTraversal(rootNode.leftChild)
    print(rootNode.data)
    preOrderTraversal(rootNode.rightChild)

#postOrder traversal

def postOrderTraversal(rootNode):
    if not rootNode:
        return
    preOrderTraversal(rootNode.leftChild)
    preOrderTraversal(rootNode.rightChild)
    print(rootNode.data)

#levelOrder Traversal

def levelOrderTraversal(rootNode):
    if not rootNode:
        return
    else:
        customQueue = queue.Queue()
        customQueue.enqueue(rootNode)
        while not (customQueue.isEmpty()):
            root = customQueue.dequeue()
            print(root.value.data)
            if root.value.leftChild is not None:
                customQueue.enqueue(root.value.leftChild)
            if root.value.rightChild is not None:
                customQueue.enqueue(root.value.rightChild)

#searching

def searchNode(rootNode, nodeValue):
    if rootNode.data == nodeValue:
        print("Found")
    elif nodeValue < rootNode.data:
        if rootNode.leftChild.data == nodeValue:
            print("Found")
        else:
            searchNode(rootNode.leftChild, nodeValue)
    else:
        if rootNode.rightChild.data == nodeValue:
            print("Found")
        else:
            searchNode(rootNode.rightChild, nodeValue)

#delete Node

def minValueNode(bstNode):
    current = bstNode
    while (current.leftChild is not None):
        current = current.leftChild
    return current

def deleteNode(rootNode, nodeValue):
    if rootNode is None:
        return rootNode
    elif nodeValue < rootNode.data:
        rootNode.leftChild = deleteNode(rootNode.leftChild, nodeValue)
    elif nodeValue > rootNode.data:
        rootNode.rightChild = deleteNode(rootNode.rightChild, nodeValue)
    else:
        if rootNode.leftChild is None:
            temp = rootNode.rightChild
            rootNode = None
            return temp
        if rootNode.rightChild is None:
            temp = rootNode.leftChild
            rootNode = None
            return temp

        temp = minValueNode(rootNode.rightChild)
        rootNode.data = temp.data
        rootNode.rightChild = deleteNode(rootNode.rightChild, temp.data)
    return rootNode

#delete entire BST

def deleteBST(rootNode):
    rootNode.data = None
    rootNode.leftChild = None
    rootNode.rightChild = None
    print("BST Deleted")

newBST = BSTNode(None)

print(insertNode(newBST, 70))
print(insertNode(newBST, 50))
print(insertNode(newBST, 90))
print(insertNode(newBST, 30))
print(insertNode(newBST, 60))
print(insertNode(newBST, 80))
print(insertNode(newBST, 100))
print(insertNode(newBST, 20))
print(insertNode(newBST, 40))

# print(newBST.data)
# print(newBST.leftChild.data)
# print(newBST.rightChild.data)

# preOrderTraversal(newBST)

# inOrderTraversal(newBST)

# postOrderTraversal(newBST)

# levelOrderTraversal(newBST)

# searchNode(newBST, 70)

# deleteNode(newBST, 20)
# levelOrderTraversal(newBST)

deleteBST(newBST)


from setuptools import setup

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='mqtls',
    packages=['mqtls'],
    version='0.5',
    license='wtfpl',
    description='MqTLS client for python',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author='Efrén Boyarizo',
    author_email='efren@boyarizo.es',
    url='https://github.com/efrenbg1/mqtls-python',
    download_url='https://github.com/efrenbg1/mqtls-python/archive/0.5.tar.gz',
    keywords=['MqTLS', 'gobroker', 'client'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools'
    ],
)


from odoo import api, fields, models,_
from datetime import datetime, timedelta
from odoo.exceptions import UserError, ValidationError

class JoborderChallan(models.Model):
    _name="joborder.challan"
    _order = 'id desc'

    @api.multi
    # def unlink(self):
    #     if self.env.user.id == self.env.ref('base.user_admin').id:
    #         return super(JoborderChallan, self).unlink()
    #     else:
    #         raise ValidationError('You Can not delete a record')
    # @api.multi
    def unlink(self):
        if self.state == 'draft':
            return super(JoborderChallan, self).unlink()
        else:
            if self.state != 'draft' and self.env.user.id == self.env.ref('base.user_admin').id:
                return super(JoborderChallan, self).unlink()
            else:
                raise ValidationError('You Can not delete a record')

    @api.model
    def create(self, vals):
        challan_rec = self.env['joborder.challan'].search([('name', '=', vals['name'])])
        if challan_rec:
            raise ValidationError('Challan No Already Exist!')
        total_qty = 0
        total = 0
        seq=''
        a=''
        if vals['challan_type'] == 'regular':
            a = ''
            seq = self.env['ir.sequence'].get('job_order_challan')
        if vals['challan_type'] == 'rework':
            a = 'Rw-'
            seq = self.env['ir.sequence'].get('job_order_challan1')
        if vals['challan_type'] == 'foc':
            # a = 'Foc-'
            seq = self.env['ir.sequence'].get('job_order_challan')
        if vals['challan_type'] == 'return':
            a = 'Ret-'
            seq = self.env['ir.sequence'].get('job_order_challan3')
        if vals['challan_type'] == 'osp':
            a = 'osp-'
            seq = self.env['ir.sequence'].get('job_order_challan4')

        # vals['name']=a

        vals['name'] = a + str(seq)
        sum_id = super(JoborderChallan, self).create(vals)
        return sum_id

    def action_create_bill(self):
        data = []
        if self.challan_type not in ['foc','rework']:
            bill_rec = self.env['challan.bill']
            for line in self.challan_line:
                job_rec = self.env['job.order.line'].search([('order_id','=',line.job_order_id.id),('product_id','=',line.product_id.id)])
                # if job_rec.unit_price == 0:
                #     raise ValidationError('Bill Not Generated Autometically')
                # else:
                data.append((0,0,{
                    'party_challan':line.party_challan.id,
                    'product_id':line.product_id.id,
                    # 'part_id':line.part_id.id,
                    'part_no':line.part_no,
                    'sac_code':line.product_id.category_id.hsn_no,
                    'our_challan':self.id,
                    # val1.product_id.category_id.hsn_no
                    'qty':line.qty,
                    'unit_id':line.unit_id.id,
                    'unit_price': job_rec.unit_price,
                    # 'unit_price':line.party_challan.unit_price,
                    'tax_id':[(4,tax.id) for tax in job_rec.tax_id],
                    'price_subtotal':line.price_subtotal,
                    'qty_nos': int(line.qty) if ((line.unit_id.name.lower())[0] == 'n') else 0,
                    'qty_kg': line.qty if ((line.unit_id.name.lower())[0] != 'n') else 0,
                    'bq':line.bq
                }))
                line.bq = line.bq - line.qty
            bill_rec.create({
                'job_order_id':self.get_challna_line_po(),
                'job_order_date':self.get_challna_line_podate(),
                'vehicle_no':self.vehicle_no.id,
                'payment_term_ids':self.payment_term_recs,
                'partner_id':self.partner_id.id,
                'challan_bill_line':data,
                'challan_issue':[(6,0,[line.order_id.id])]})
            self.billed = True

    def _amount_all_wrapper(self):
        total_amount = 0.00
        for val in self:
            if val.challan_line:
                for val1 in val.challan_line:
                    total_amount = total_amount + val1.amount
                    self.amount_untaxed = total_amount

    def _tax_amount(self):
        total_tax = 0.00
        for val in self:
            if val.challan_line:
                for val1 in val.challan_line:
                    amount = 0.0
                    for val2 in val1.tax_id.children_tax_ids:
                        amount = amount + val2.amount
                    total_tax = total_tax + (val1.qty * val1.material_price)* amount / 100
                    self.tax_value = total_tax

    def _get_total_amount(self):
        total_amount = 0.00
        for val in self:
            total_amount = val.amount_untaxed + val.tax_value
            self.total_amount = total_amount

    @api.multi
    def action_fetch_receipt_data(self):
        if self.challan_line:
            for line in self.challan_line:
                line.unlink()
        data = []
        if self.challan_type == 'regular':
            final_inspection_rec = self.env['final.inspection'].search([('party_name', '=', self.partner_id.id),('is_issue','=',False),('expected_qty','>',0)])
            for rec in final_inspection_rec:
                job_rec = self.env['joborder.challan.receipt.line'].search(
                    [('order_id', '=', rec.order_ids.id), ('product_id', '=', rec.product_id.id)])
                job_work_rec = self.env['job.order.line'].search([('product_id','=',rec.product_id.id),('order_id','=',job_rec.job_order_id.id)])
                if rec.expected_qty > 0:
                    data = [(0, 0, {
                        'product_id': rec.product_id.id,
                        'name': rec.product_id.name,
                        'hsn_code': rec.product_id.hsn_code,
                        'party_challan': rec.order_ids.id,
                        'qty': rec.expected_qty,
                        'batch_no':rec.batch_no,
                        # 'part_id': line.part_id.id,
                        'part_no': rec.part_no,
                        'unit_id': rec.unit_id.id,
                        'job_order_id': job_rec.job_order_id.id,
                        'unit_price': job_work_rec.unit_price,
                        'material_price': job_work_rec.material_price,
                        'tax_id': job_work_rec.tax_id.id,
                        'joborder_challan_receipt_line_id': job_rec.id,
                        'qty_nos': int(rec.expected_qty) if ((rec.unit_id.name.lower())[0] == 'n') else 0,
                        'qty_kg': rec.expected_qty if ((rec.unit_id.name.lower())[0] != 'n') else 0,
                        # 'bq': qty
                    })]
                    self.challan_line = data

            # receipt_rec = self.env['joborder.challan.receipt'].search([('partner_id','=',self.partner_id.id)])
            # #final_inspection_rec = self.env['final.inspection'].search([('is_issue','=',False)])
            # for rec in receipt_rec:
            #     if rec.joborder_challan_receipt_lines_rec:
            #         for line in rec.joborder_challan_receipt_lines_rec:
            #             self.payment_term_recs =line.job_order_id.payment_term
            #             qty = line.production_ok_qty_line - line.production_desp_qty_line
            #             if qty > 0:
            #                 data=[(0,0,{
            #                     'product_id': line.product_id.id,
            #                     'name':line.product_id.name,
            #                     'hsn_code':line.product_id.hsn_code,
            #                     'party_challan': rec.id,
            #                     'qty': qty,
            #                     # 'part_id': line.part_id.id,
            #                     'part_no':line.part_no,
            #                     'unit_id': line.unit_id.id,
            #                     'job_order_id': line.job_order_id.id,
            #                     'unit_price': line.unit_price,
            #                     'material_price': line.material_price,
            #                     'tax_id': line.tax_id.id,
            #                     'joborder_challan_receipt_line_id':line.id,
            #                     'qty_nos':int(qty) if ((line.unit_id.name.lower())[0] =='n') else 0,
            #                     'qty_kg':qty if ((line.unit_id.name.lower())[0] !='n') else 0,
            #                     #'bq': qty
            #                 })]

        elif self.challan_type == 'return':

            inspection_rec = self.env['joborder.inspection'].search([('party_name', '=', self.partner_id.id),('is_return','=',False)])
            for rec in inspection_rec:
                job_rec = self.env['joborder.challan.receipt.line'].search([('order_id','=',rec.order_ids.id),('product_id','=',rec.product_id.id)])
                if rec.rejected_qty > 0:
                    data = [(0, 0, {
                        'product_id': rec.product_id.id,
                        'name': rec.product_id.name,
                        'hsn_code': rec.product_id.hsn_code,
                        'party_challan': rec.order_ids.id,
                        'qty': rec.rejected_qty,
                        # 'part_id': line.part_id.id,
                        'part_no': rec.part_no,
                        'unit_id': rec.unit_id.id,
                        'job_order_id': job_rec.job_order_id.id,
                        'unit_price': job_rec.unit_price,
                        'material_price': job_rec.material_price,
                        'tax_id': job_rec.tax_id.id,
                        'joborder_challan_receipt_line_id': job_rec.id,
                        'qty_nos': int(rec.rejected_qty) if ((rec.unit_id.name.lower())[0] == 'n') else 0,
                        'qty_kg': rec.rejected_qty if ((rec.unit_id.name.lower())[0] != 'n') else 0,
                        # 'bq': qty
                    })]
                    self.challan_line = data
            # final_inspection_rec = self.env['final.inspection'].search([('party_name', '=', self.partner_id.id),('is_return','=',False)])
            # for rec in final_inspection_rec:
            #     job_rec = self.env['joborder.challan.receipt.line'].search([('order_id','=',rec.order_ids.id),('product_id','=',rec.product_id.id)])
            #     if rec.rejected_qty > 0:
            #         data.append({
            #             'product_id': rec.product_id.id,
            #             'name': rec.product_id.name,
            #             'hsn_code': rec.product_id.hsn_code,
            #             'party_challan': rec.order_ids.id,
            #             'qty': rec.rejected_qty,
            #             # 'part_id': line.part_id.id,
            #             'part_no': rec.part_no,
            #             'unit_id': rec.unit_id.id,
            #             'job_order_id': job_rec.job_order_id.id,
            #             'unit_price': job_rec.unit_price,
            #             'material_price': job_rec.material_price,
            #             'tax_id': job_rec.tax_id.id,
            #             'joborder_challan_receipt_line_id': job_rec.id,
            #             'qty_nos': int(rec.rejected_qty) if ((rec.unit_id.name.lower())[0] == 'n') else 0,
            #             'qty_kg': rec.rejected_qty if ((rec.unit_id.name.lower())[0] != 'n') else 0,
            #             # 'bq': qty
            #         })
            # self.challan_line = data

    def get_time(self):
        date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
        date_time = datetime.strptime(date, '%Y-%m-%d %H:%M:%S') + timedelta(hours=5, minutes=30, seconds=0)
        date_time  = date_time .strftime('%H:%M')
        return date_time

    def _amount_all_wrapper(self):
        total_amount = 0.00
        for val in self:
            if val.challan_line:
                for val1 in val.challan_line:
                    total_amount = total_amount + val1.price_subtotal
                    self.amount_untaxed = total_amount

    def _tax_amount(self):
        total_tax = 0.00
        for val in self:
            if val.challan_line:
                for val1 in val.challan_line:
                    amount = 0.0
                    if val1.tax_id:
                        amount = amount + val1.tax_id.amt

                    total_tax = total_tax + (val1.qty * val1.material_price) * amount / 100
                    self.tax_value = total_tax

    def _get_total_amount(self):
        total_amount = 0.00
        for val in self:
            total_amount = val.amount_untaxed + val.tax_value
            self.total_amount = total_amount

    def action_fetch_data(self):
        if self.ref_challan and not self.challan_line:
            for val in self.ref_challan:
                for val1 in val.joborder_challan_receipt_lines:
                    self.env['challan.line'].create(
                        {'order_id': self.id,
                         'party_challan':val.id,
                         'product_id':val1.product_id.id,
                         # 'part_id':val1.part_id.id,
                         'part_no':val1.part_no,
                         'unit_id': val1.unit_id.id,
                         'hsn_code': val1.hsn_code,
                         'qty': val1.qty,
                         'unit_price': val1.unit_price,
                         'material_price': val1.material_price,
                         'tax_id': val1.tax_id.id,
                         })

    def action_confirm(self):
        if self.chno:
            self.name = self.chno

        for val1 in self.challan_line:
            val1.qty_nos = val1.qty if (val1.unit_id.name.lower())[0] == 'n' else 0
            val1.qty_kg = val1.qty if (val1.unit_id.name.lower())[0] != 'n' else 0
            inspection_rec = self.env['joborder.inspection'].search([('product_id','=',val1.product_id.id),('order_ids','=',val1.party_challan.id)])
            for insp in inspection_rec:
                insp.is_return=True
                insp.bq -= insp.rejected_qty

            val1.bq = val1.qty
            final_inspection_rec = self.env['final.inspection'].search(
                [('product_id','=',val1.product_id.id),('order_ids','=',val1.party_challan.id)])
            for final_rec in final_inspection_rec:
                final_rec.bq = val1.bq - final_rec.bq
                final_rec.is_issue = True
                if final_rec.bq == 0:
                    final_rec.state = 'confirm'
            sale_line_obj = self.env['joborder.challan.receipt.line'].search(
                [('product_id', '=', val1.product_id.id), ('unit_id', '=', val1.unit_id.id),
                 ('order_id', '=', val1.party_challan.id)])
            for data in sale_line_obj:
                # sale_line_obj.write({'issue_qty': data.issue_qty + val1.qty,
                #                      'bal_qtynew': data.bal_qtynew - val1.qty,
                #                      })
                sale_line_obj.write({'issue_qty': data.issue_qty + val1.qty,
                                     'bal_qtynew': (data.qty-data.issue_qty),
                                     })

                # rec_obj.write({'remaining_total': rec_obj.remaining_total - val1.qty})
        for rec in self.challan_line:

            rec.joborder_challan_receipt_line_id = sale_line_obj.id
            rec.party_challan.challan_line_ids = [(0, sale_line_obj.id, dict(
                # order_id=rec.order_id.id,
                challan_issue_id=rec.order_id.name,
                product_id=rec.product_id.id,
                unit_price=rec.unit_price,
                name=rec.name,
                tax_id=rec.tax_id.id,
                party_challan=rec.party_challan.id,
                qty=rec.qty,
                product_id1=rec.product_id1.id,
                unit_id=rec.unit_id.id,
                hsn_code=rec.hsn_code,
                # part_id=rec.part_id.id,
                part_no=rec.part_no,
                challan_reciept_id=rec.party_challan.id,
                job_order_id = rec.job_order_id.id

            ))]
        if self.partner_id.billing_mode:
            self.action_create_bill()
        # self.method_update_challan_receipt_total_iss(self.challan_line)
        self.write({'state':'confirm'})

    # def method_update_challan_receipt_total_iss(self,challanline):
    #     for lines in challanline:
    #         rec_obj = self.env['joborder.challan.receipt'].search(
    #             [('id', '=', lines.party_challan.id)])
    #
    #         rec_obj.total_iss+=lines.qty
    #         rec_obj.total_bal-=lines.qty

    # Change By Ayush
    def action_gen_invoice(self):
        action = self.env.ref('job_order_process.action_challan_bill').read()[0]
        action['domain'] = [('partner_id', '=', self.partner_id.id), ('challan_issue', '=',self.id)]
        return action

    name = fields.Char('Issue No.', required=True,default='New')
    chno = fields.Char('Issue No.Org')
    partner_id = fields.Many2one('my.partner','Party Name',required=True,)
    # date = fields.Date('Date',default=fields.Date.today(),required=True,)
    date = fields.Date(required=True, default=lambda self: self._get_current_date())
    @api.model
    def _get_current_date(self):
        """ :return current date """
        date = datetime.now() + timedelta(hours=5, minutes=30)
        date = date.date()
        return date

    remark = fields.Char('Remark')
    origin = fields.Many2one('joborder.challan.receipt', 'Refecence')
    reference_id = fields.Many2many('joborder.challan.receipt', 'Refecence')
    ref_challan = fields.Many2many('joborder.challan.receipt', string='Reference')
    challan_line = fields.One2many('challan.line','order_id','Lines')
    user_id = fields.Many2one('res.users', 'Created By', default=lambda self: self.env.user)
    amount_untaxed = fields.Float(compute = _amount_all_wrapper, string='Untaxed Amount' )
    tax_value = fields.Float(compute = _tax_amount, string='Taxes' )
    total_amount = fields.Float(compute = _get_total_amount, string='Total Amount')
    # eway_bill = fields.Char('E-way Bill No.')
    # transport = fields.Char('Transport Mode')
    vehicle_no = fields.Many2one('vehicle', 'Vehicle No')
    time = fields.Char('Time',default=get_time)
    amount_untaxed = fields.Float(compute=_amount_all_wrapper, string='Untaxed Amount')
    tax_value = fields.Float(compute=_tax_amount, string='Taxes')
    total_amount = fields.Float(compute=_get_total_amount, string='Total Amount')
    challan_type = fields.Selection([('regular', 'Regular'),('rework', 'Rework'),('foc', 'FOC'),('return','Return'),('osp','Returnable Challan')],default='regular',string='Challan Type',required=True)
    billed = fields.Boolean('Billed')
    description = fields.Char('Description')
    state = fields.Selection([
        ('draft', 'Draft'),
        ('confirm', 'Confirm'),
    ], string='Status', readonly=True, copy=False, index=True, default='draft')
    payment_term_recs = fields.Integer(string="Payment term (days)")
    job_order_challan_reference = fields.Char('Reference')
    production_challan_reference = fields.Char('Pro Reference')
    mast_oldid = fields.Integer('Mast Id')

    _sql_constraints = [
        ('name', 'unique(name,partner_id)', 'Challan  no. already exists for this party!')
    ]

#new changes ayush gupta
    def get_challna_line_po(self):
        data = []
        data_line = []
        for line in self.challan_line:
            if data_line:
                # data_line.append(line.job_order_id.name + ' dt.' + datetime.strptime(str(line.job_order_id.date),'%Y-%m-%d').strftime('%d/%m/%Y'))
                data_line.append(line.job_order_id.name)
                # podate=line.job_order_id.date
            else:
                data_line.append(line.job_order_id.name)
            #     data_line.append(line.job_order_id.name + ' dt.' + datetime.strptime(str(line.job_order_id.date),'%Y-%m-%d').strftime('%d/%m/%Y'))
            #
        data_line=set(data_line)

        s = [str(i) for i in data_line]
        res = str(",".join(set(s)))
        return res

    def get_challna_line_podate(self):
        data = []
        data_line = []
        for line in self.challan_line:
            if data_line:
                # data_line.append(line.job_order_id.name + ' dt.' + datetime.strptime(str(line.job_order_id.date),'%Y-%m-%d').strftime('%d/%m/%Y'))
                data_line.append(datetime.strptime(str(line.job_order_id.date),'%Y-%m-%d').strftime('%d/%m/%y'))
                # podate=line.job_order_id.date
            else:
                data_line.append(datetime.strptime(str(line.job_order_id.date),'%Y-%m-%d').strftime('%d/%m/%y'))
            #     data_line.append(line.job_order_id.name + ' dt.' + datetime.strptime(str(line.job_order_id.date),'%Y-%m-%d').strftime('%d/%m/%Y'))
            #
        data_line = set(data_line)
        s = [str(i) for i in data_line]
        res = str(",".join(set(s)))
        return res

    def get_receiptChallanNo(self, ReceiptChallanNO):
        if ReceiptChallanNO:
            return  ReceiptChallanNO.split('_')[0]

class ChallanLine(models.Model):
    _name = "challan.line"

    # @api.multi
    # def unlink(self):
    #     if self.env.user.id == self.env.ref('base.user_admin').id:
    #         return super(ChallanLine, self).unlink()
    #         # self.env[joborder.challan.receipt.line].get_total_balance()
    #         # print(data.qty, data.issue_qty, val1.qty, 'eeeeeeeee', (data.qty - data.issue_qty))
    #     else:
    #         raise ValidationError('You Can not delete a record')
    # @api.multi
    # def unlink(self):
    #     if self.state == 'draft':
    #         return super(ChallanLine, self).unlink()
    #     else:
    #         if self.state != 'draft' and self.env.user.id == self.env.ref('base.user_admin').id:
    #             return super(ChallanLine, self).unlink()
    #         else:
    #             raise ValidationError('You Can not delete a record')
    @api.multi
    def write(self, vals):
        for rec in self:
            if 'product_id' in vals:
                prod = self.env['my.product'].browse([vals.get('product_id')])
            else:
                prod = rec.product_id

            if 'party_challan' in vals:
                challan = self.env['joborder.challan.receipt'].browse([vals.get('party_challan')])
            else:
                challan = rec.party_challan

            for line in self.env['joborder.challan'].browse([rec.order_id.id]).challan_line:
                if (prod.id == line.product_id.id) and (challan.id == line.party_challan.id) and line.id != rec.id and line.order_id == rec.id:
                    raise UserError(_(u"Duplicate lines \nthis line already exist!\ncheck your lines again please!"))
        result = super(ChallanLine, self).write(vals)
        return result

    @api.model
    def create(self, vals):
        if vals.get('order_id', False):
            for line in self.env['joborder.challan'].browse([vals['order_id']]).challan_line:
                if (vals.get('product_id') == line.product_id.id) and (vals.get('party_challan') == line.party_challan.id):
                    raise UserError(_(u"Duplicate lines \nthis line already exist!\ncheck your lines again please!"))
        result = super(ChallanLine, self).create(vals)
        return result

    @api.onchange('job_order_id')
    def onchange_job_order_product(self):
        product_list = []
        job = []
        for val in self.env['job.order'].search([('partner_id', '=', self.order_id.partner_id.id),('state','=','confirm')]):
            job.append(val.id)
        domain = {'job_order_id':[('id','in',job)]}
        for line in self.env['joborder.challan.receipt.line'].search([('job_order_id', '=', self.job_order_id.id),('bal_qtynew','>',0)]):
            product_list.append(line.product_id.id)
        product_list = list(set(product_list))
        domain.update({'product_id': [('id', 'in', product_list)]})
        return {'domain': domain}  # ,'domain1':d

    # @api.onchange('product_id')
    # def onchange_product_id(self):
    #     product_list = []
    #     data_list = []
    #     if self.product_id:
    #         for val in self.env['joborder.challan.receipt.line'].search([('product_id', '=', self.product_id.id),('bal_qtynew','>',0)]):
    #             data_list.append(val.order_id.id)
    #         domain = {'party_challan': [('id', 'in', data_list)]}
    #
    #                 # self.process = rec.process_id.id
    #                 # self.packing_id = rec.packing_id.id
    #         return {'domain': domain}
    @api.onchange('product_id')
    def onchange_product_id(self):
        product_list = []
        data_list = []
        if self.product_id:
            for val in self.env['joborder.challan.receipt.line'].search(
                    [('product_id', '=', self.product_id.id), ('bal_qtynew', '>', 0),
                     ('order_id.partner_id', '=', self.order_id.partner_id.id),
                     ('order_id.challan_type', '=', self.order_id.challan_type)]):
                data_list.append(val.order_id.id)
            domain = {'party_challan': [('id', 'in', data_list)]}

            # self.process = rec.process_id.id
            # self.packing_id = rec.packing_id.id
            self.hsn_code=self.product_id.hsn_code
            job_rec = self.env['job.order.line'].search(
                [('order_id', '=', self.job_order_id.id), ('product_id', '=', self.product_id.id)])
            for val in job_rec:
                self.material_price=val.material_price

            return {'domain': domain}

    @api.onchange('party_challan')
    def get_product_detail(self):
        for val in self.env['joborder.challan.receipt.line'].search([('order_id', '=', self.party_challan.id)]):
            for line in val:
                if val.product_id.id == self.product_id.id:
                    if self.product_id:
                        self.unit_id = line.unit_id.id
                        # self.part_id = line.part_id.id
                        self.part_no = line.product_id.part_no if line.product_id.part_no else '',
                        # self.job_order_id = line.job_order_id.id
                        self.sac_code = line.sac_code
                        self.hsn_code = self.product_id.hsn_code
                        self.tax_id = line.tax_id.id
                        self.unit_price = line.unit_price
                        # self.material_price = self.material_price
                        self.qty = line.bal_qtynew

    @api.onchange('qty')
    def change_qty(self):
        if self.qty:
            for val in self.env['joborder.challan.receipt.line'].search([('order_id', '=', self.party_challan.id),('product_id','=',self.product_id.id)]):
                if val.product_id.id == self.product_id.id:
                    if round(self.qty,2) > val.bal_qtynew:
                        raise ValidationError('Qty is not more than %s'%val.bal_qtynew)

    @api.depends('qty','unit_price')
    def get_subtotal(self):
        total_price = 0.00
        for val in self:
            if val.qty:
                total_price = (val.qty * val.material_price)
                val.write({'price_subtotal1': total_price})
                val.price_subtotal = total_price

    order_id = fields.Many2one('joborder.challan','Id',ondelete='cascade')
    job_order_id = fields.Many2one('job.order', 'Order No.',required=True)

    party_challan =fields.Many2one('joborder.challan.receipt', 'Party Challan', ondelete='cascade')
    challan_reciept_id = fields.Many2one('joborder.challan.receipt', 'Party Challan id', ondelete='cascade')

    product_id = fields.Many2one('my.product','Product',required=True)
    product_id1 = fields.Many2one('my.vik', 'Item')
    name = fields.Char('Description',default='After Platting')
    # part_id = fields.Many2one('part.number','Part No.')
    part_no=fields.Char('Part No.')
    hsn_code = fields.Char('HSN No.')
    # unit_id = fields.Many2one('my.uom','UOM')
    unit_id = fields.Many2one('my.unit', 'UOM')
    qty = fields.Float('Quantity',digits=(10,2))

    qty_nos=fields.Integer('Qty Nos')
    qty_kg=fields.Float('Qty_Kg',digits=(10,2))
    unit_price = fields.Float('Unit Price')
    material_price = fields.Float('Material Price')

    nature_of_process = fields.Char('Nature of Process')

    tax_id = fields.Many2one('my.tax', string='Taxes',)
    price_subtotal = fields.Float(compute=get_subtotal, string='Subtotal')
    price_subtotal1 = fields.Float(string='Subtotal')
    challan_issue_id=fields.Char(string='Issue ChNo')
    # joborder_challan_receipt_line_id=fields.Integer()
    joborder_challan_receipt_line_id= fields.Many2one('joborder.challan.receipt.line', ondelete='cascade')
    bq = fields.Float('Bal qty')
    rtq = fields.Float('Return qty')
    batch_no=fields.Char('Batch No')

class MyVik(models.Model):
    _name = "my.vik"
    _order = 'name asc'

    name = fields.Char('Name')
    product_id = fields.Many2one('my.product', 'Product')
    challan_id = fields.Many2one('joborder.challan.receipt','Challan')
    qty = fields.Float('Qty')

    @api.multi
    def unlink(self):
        if self.env.user.id == self.env.ref('base.user_admin').id:
            return super(MyVik, self).unlink()
        else:
            raise ValidationError('You Can not delete a record')


import unittest

import numpy as np

from src.minimizer.minimizer_library.differential_evolution import DifferentialEvolution
from src.parametric_function_library.linear_function import LinearFunction
from src.statistical_models.statistical_model_library.gaussian_noise_model import GaussianNoiseModel

dimension = 3
function = LinearFunction()
theta = np.ones(dimension + 1)
x = np.ones(dimension)
x0 = np.identity(dimension)

lower_bounds_theta = 0 * np.ones(dimension + 1)
upper_bounds_theta = 3 * np.ones(dimension + 1)

lower_bounds_x = 0 * np.ones(dimension + 1)
upper_bounds_x = 10 * np.ones(dimension + 1)

model = GaussianNoiseModel(function=function,
                           lower_bounds_theta=lower_bounds_theta,
                           upper_bounds_theta=upper_bounds_theta,
                           lower_bounds_x=lower_bounds_x,
                           upper_bounds_x=upper_bounds_x,
                           sigma=0.1,
                           )

class TestGaussianNoiseModel(unittest.TestCase):

    def test_if_model_can_be_called_correctly(self):
        self.assertEqual(np.array([dimension + 1]), model(theta=theta, x=x))

    def test_if_random_drawing_returns_random_drawing(self):
        self.assertAlmostEqual(4, model.random(x=x, theta=theta)[0], delta=1)

    def test_if_fim_is_calculated_correctly(self):
        matrix = 1 / model._var * np.array([[3, 1, 1, 1], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]])
        self.assertEqual(True, (matrix == model.calculate_fisher_information_matrix(x0=x0, theta=theta)).all())

    def test_if_likelihood_is_calculated_correctly(self):
        pass

    def test_if_mle_is_approximately_found(self):
        minimizer = DifferentialEvolution()
        y = np.array([function(theta=theta, x=x) for x in x0])
        mle = model.calculate_maximum_likelihood_estimation(x0=x0, y=y, minimizer=minimizer)
        self.assertAlmostEqual(0, float(np.mean(mle - theta)), delta=0.5)

    def test_if_determinant_of_fim_is_calculated_correctly(self):
        # The FIM is not invertible, i.e. the determinant must be (approximately) zero
        self.assertAlmostEqual(0, model.calculate_determinant_fisher_information_matrix(x0=x0, theta=theta), delta=1e-5)

    def test_if_bounds_are_returned_correctly(self):
        self.assertEqual(True, (lower_bounds_x == model.lower_bounds_x).all())
        self.assertEqual(True, (lower_bounds_theta == model.lower_bounds_theta).all())
        self.assertEqual(True, (upper_bounds_x == model.upper_bounds_x).all())
        self.assertEqual(True, (upper_bounds_theta == model.upper_bounds_theta).all())

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


import cv2

img = cv2.imread("/home/pradeep/Documents/Deeplearning/Tyser/Task_1.jpg")

cv2.namedWindow("Image", cv2.WINDOW_NORMAL)
cv2.imshow("Image", img)

start_x, start_y, end_x, end_y = 0, 0, 0, 0 #coordinates initialization

# Function to mousecalback
def mouse_event(event, x, y, flags, param):
    global start_x, start_y, end_x, end_y
    if event == cv2.EVENT_LBUTTONDOWN:
        start_x, start_y = x, y
    elif event == cv2.EVENT_LBUTTONUP:
        end_x, end_y = x, y
        # Draw the rectangle for cropping
        cv2.rectangle(img, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)
        # Display the top-left and bottom-right coordinates of the rectangle
        cv2.putText(img, f'Top Left: ({start_x}, {start_y})', (start_x, start_y - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        cv2.putText(img, f'Bottom Right: ({end_x}, {end_y})', (end_x, end_y + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        cv2.imshow("Image", img)
        cv2.imwrite("/home/pradeep/Documents/Deeplearning/Tyser/1/Task_1_insights.jpg",img)

cv2.setMouseCallback("Image", mouse_event)
cv2.waitKey(0)
cv2.destroyAllWindows()


import numpy as np
import shelve
from auc import roc

test = np.loadtxt('new_pre.csv', delimiter=',')

x_test = test[:, 0:-1]
y_test = np.ravel(test[:, -1])

y_pre_vote = np.zeros((16, len(y_test)))

models = shelve.open('classifier/model')

for i in range(16):
    clf_name = 'clf' + str(i)
    clf = models[clf_name]
    y_pre_vote[i, :] = clf.project(x_test)

np.savetxt('y_pre_vote.csv', y_pre_vote, delimiter=',')
proj = np.sum(y_pre_vote, axis=0)
print(proj)
r = roc(y_test, proj)
r.plot()
print(r.auc)
# auc: 0.7687586071217752
y_pre = np.sign(np.sum(y_pre_vote, axis=0))

# F1: 2*TP / (samples + TP - TN)
actual = y_test > 0
pred = y_pre > 0
TP = sum(actual & pred)
FN = sum(actual) - TP
TN = sum(~(actual | pred))
FP = sum(pred) - TP
# accuracy
acc = (TP + TN) / (TP + FN + FP + TN)
# recall
recall = 1.0 * TP / (TP + FN)
# precision
precision = 1.0 * TP / (TP + FP )
# F1- score
F1_score = (2.0 * recall * precision) / (recall + precision)
record = [TP, FN, TN, FP, recall, precision, F1_score, acc]
print(record)
# [84, 33, 1388, 567, 0.717948717948718, 0.12903225806451613, 0.21875, 0.7104247104247104]


import threading
from PyQt5 import QtSql
from util.mm_logger import MMLogger

class MMDatabase(object):
    _INST_LOCK = threading.Lock()
    _INSTANCE = None

    @classmethod
    def get_instance(cls):
        """ Method for getting the only instance """
        if cls._INSTANCE is None:
            with cls._INST_LOCK:
                if cls._INSTANCE is None:
                    cls._INSTANCE = MMDatabase()
        assert cls._INSTANCE is not None
        return cls._INSTANCE

    def __new__(cls, *args, **kwargs):
        """ To make sure there will be only one instance """
        if not isinstance(cls._INSTANCE, cls):
            cls._INSTANCE = object.__new__(cls, *args, **kwargs)
        return cls._INSTANCE

    def __init__(self):
        self._logger = MMLogger.get_instance()
        self._logger.info("Open database")
        self._database_url = "database.db"
        self._database = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        self._database.setDatabaseName(self._database_url)

    def init_db(self):
        statements = list()
        statements.append("""DROP TABLE account_type;""")
        statements.append("""DROP TABLE `account`;""")
        statements.append("""DROP TABLE `transaction`;""")
        statements.append("""DROP TABLE `transaction_type`;""")

        statements.append("""CREATE TABLE account_type (id INTEGER, name TEXT, PRIMARY KEY(id));""")
        statements.append("""CREATE TABLE `account` (`id` INTEGER, `name` TEXT, `initial_balance` INTEGER, `account_type_id` INTEGER, PRIMARY KEY(id));""")
        statements.append("""CREATE TABLE `transaction_type` (`id` INTEGER, `name` TEXT, PRIMARY KEY(id));""")
        statements.append("""CREATE TABLE `transaction` (`id` INTEGER, `name` TEXT, `date` TEXT, `transaction_type_id` INTEGER, PRIMARY KEY(id));""")

        for statement in statements:
            query = QtSql.QSqlQuery()
            ok = query.exec_(statement)
            if not ok:
                self._logger.info("Database initialization failed! %s", self._database.lastError().text())
                return

        self._logger.info("Database creation done!")

    def execute_sql(self, statement):
        query = QtSql.QSqlQuery()
        ok = query.exec_(statement)

        if not ok:
            self._logger.error("SQL statement %s failed!", statement)


from mambupy.rest.mambucentre import MambuCentre as MambuCentre1
from mambupy.rest.mambucentre import MambuCentres as MambuCentres1
from mambupy.rest1to2.mambustruct import MambuStruct, process_filters
from mambupy.rest.mamburestutils import MambuStructIterator

centre_filters = ["branchId"]

class MambuCentre(MambuStruct, MambuCentre1):
    def __init__(self, *args, **kwargs):
        process_filters(centre_filters, kwargs)
        super().__init__(*args, **kwargs)

class MambuCentres(MambuStruct, MambuCentres1):
    def __init__(self, *args, **kwargs):
        if "mambuclassname" in kwargs:
            mambuclassname = kwargs.pop("mambuclassname")
        else:
            mambuclassname = "MambuCentre"
        if "mambuclass1" in kwargs:
            mambuclass1 = kwargs.pop("mambuclass1")
        else:
            mambuclass1 = MambuCentre
        process_filters(centre_filters, kwargs)
        super().__init__(
            mambuclassname=mambuclassname,
            mambuclass1=mambuclass1, *args, **kwargs)

    def __iter__(self):
        return MambuStructIterator(self.wrapped2)

    def __repr__(self):
        return super().__repr__()


import random

from Art.Day_11_Art import logo

cards = [{'Ace': 11}, {'Two': 2}, {'Three': 3}, {"Four": 4}, {"Five": 5}, {'Six': 6}, {'Seven': 7},
         {"Eight": 8}, {"Nine": 9}, {"Ten": 10}, {"Jack": 10}, {"Queen": 10}, {"King": 10}]

def print_lines():
    print(f"-----------------------------------------------------------------------------")

def deal_card(n=1):
    result = []
    for i in range(n):
        card = random.choice(cards)
        result.append(card)

    return result

def calculate_score(hand: list):

    score = 0
    for item in hand:
        for key in item:
            if key == 'Ace':
                if score > 10:
                    score += 1
                else:
                    score += item[key]
            else:
                score += item[key]
    return score

def winner(your_score, casino_score):

    if your_score > 21 and casino_score > 21:
        print(f"Draw!")
    elif your_score > 21 and casino_score < 21:
        print("Casino Win!")
    elif your_score < 21 and casino_score > 21:
        print('You win!')
    elif your_score > casino_score:
        print('You win!')
    elif casino_score > your_score:
        print('Casino win !')
    elif casino_score == your_score:
        print('Draw')

def check_casino_hand(hand: list):
    score = calculate_score(hand)
    if score < 17:
        hand.extend(deal_card())
    return hand

def black_jack():
    print(logo)
    your_hand = deal_card(n=2)
    casino_hand = deal_card()
    print(f"Your cards: {your_hand}")
    print(f"Computer's first card: {casino_hand}")

    terminated = False
    while terminated is False:
        loop = input(f"Type 'y' to get another card, type 'n' to pass: ")
        if loop == 'y':
            your_hand.extend(deal_card())
            print(f"Your cards: {your_hand}")
        else:
            casino_hand.extend(deal_card())
            check_casino_hand(casino_hand)
            print_lines()
            your_score = calculate_score(your_hand)
            casino_score = calculate_score(casino_hand)
            print(f"Your final hand: {your_hand} - {your_score}")
            print(f"Casino final hand: {casino_hand} - {casino_score}")
            winner(your_score, casino_score)
            print_lines()

            option = input(f"Do you want to create a new game? Type 'y' or 'n' ")
            if option == 'y':
                black_jack()
            else:
                terminated = True

black_jack()


#coding=utf-8

import os
from share_operation import get_share_operations

PTHREAD_CREATE = 0x01
PTHREAD_JOIN = 0x02
PTHREAD_MUTEX_LOCK = 0x03
PTHREAD_MUTEX_UNLOCK = 0x04
PTHREAD_COND_SIGNAL = 0x05
PTHREAD_COND_WAIT = 0x06
PTHREAD_BARRIER_WAIT = 0x07

SHARE_VAR_READ = 0x08
SHARE_VAR_WRITE = 0x09

def get_cmd(op_mode, file):
    if op_mode == PTHREAD_CREATE:
        return "cat %s | grep -n pthread_create\( | awk '{print $1}'" % os.path.abspath(file)
    elif op_mode == PTHREAD_JOIN:
        return "cat %s | grep -n pthread_join\( | awk '{print $1}'" % os.path.abspath(file)
    elif op_mode == PTHREAD_MUTEX_LOCK:
        return "cat %s | grep -n pthread_mutex_lock\( | awk '{print $1}'" % os.path.abspath(file)
    elif op_mode == PTHREAD_MUTEX_UNLOCK:
        return "cat %s | grep -n pthread_mutex_unlock\( | awk '{print $1}'" % os.path.abspath(file)
    elif op_mode == PTHREAD_COND_SIGNAL:
        return "cat %s | grep -n pthread_cond_signal\( | awk '{print $1}'" % os.path.abspath(file)
    elif op_mode == PTHREAD_COND_WAIT:
        return "cat %s | grep -n pthread_cond_wait\( | awk '{print $1}'" % os.path.abspath(file)
    elif op_mode == PTHREAD_BARRIER_WAIT:
        return "cat %s | grep -n pthread_barrier_wait\( | awk '{print $1}'" % os.path.abspath(file)

def do_instrumentation(file):
    for i in range(1, 8):
        cmd = get_cmd(i)
        lines = os.popen(cmd).readlines()

        #插桩代码在本句结束后添加
        contents = open(file, "r").readlines()
        for line in lines:
            linenum = int(line[:-1])
            j = 0
            while True:
                if ");" in contents[linenum+j]:
                    contents[linenum+j] = contents[linenum].replace(");", ");instr(%d, '');" % i)
                    break
                else:
                    j += 1

    # end instr, rewrite file
    f = open(file, "w")
    f.seek(0)
    f.writelines(['#include "pf.h"',])
    f.writelines(contents)
    f.flush()
    f.close()

def do_share_operation_instrument(analyses_file):
    results = get_share_operations(analyses_file)
    current_file = ""
    contents = ""
    for file, line, op, var in results:
        if file != current_file:
            # 到新文件了，保存旧文件
            out = open(current_file, "w")
            out.seek(0)
            out.writelines(['#include "pf.h"', ])
            out.writelines(contents)
            out.flush()
            out.close()

            contents = open(file, "r").readlines()
        while True:
            if ";" in contents[line-1]:
                contents[line-1] = contents[line-1].replace(";", ";instr(%d, '%s')" % (op, var))
                break
            else:
                line += 1

    # 修改最后一个文件
    out = open(current_file, "w")
    out.seek(0)
    out.writelines(['#include "pf.h"', ])
    out.writelines(contents)
    out.flush()
    out.close()


#
# https://leetcode.com/problems/merge-two-sorted-lists/
#
# Merge two sorted linked lists and return it as a sorted list.
# The list should be made by splicing together the nodes of the first two lists.
#

from typing import List
import pdb

solution_json = {
    "date": "2021/3/24",
    "runtime": "40 ms",
    "memory": "14.4 MB"
}

#
# Definition for singly-linked list.
#

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        n1 = l1
        n2 = l2
        pre_n3 = None
        first_n3 = None
        while True:

            if n1 == None and n2 == None:
                break
            elif n1 == None and n2 != None:
                min_val = n2.val
                n2 = n2.next
            elif n2 == None and n1 != None:
                min_val = n1.val
                n1 = n1.next
            elif n1.val <= n2.val:
                min_val = n1.val
                n1 = n1.next
            else:
                min_val = n2.val
                n2 = n2.next

            #print('min_val = %d' % min_val)
            n3 = ListNode(min_val)
            if first_n3 == None:
                first_n3 = n3
            if pre_n3 != None:
                pre_n3.next = n3
            pre_n3 = n3

        return first_n3

    def list_to_ll(self, list):
        pre_node = None
        first_node = None
        for i in range(len(list)):
            node = ListNode(list[i])
            if first_node == None:
                first_node = node
            if pre_node != None:
                pre_node.next = node
            pre_node = node
        return first_node

    def print_link(self, link):
        node = link
        line = ''
        while True:
            line += (str(node.val) + ' -> ')
            node = node.next
            if node == None:
                break
        print(line)

    def ll_to_list(self, link):
        node = link
        list = []
        while True:
            if node == None:
                break
            list.append(node.val)
            node = node.next

        return list