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

import time
from datetime import datetime,timedelta
from lxml import etree
import netsvc
from osv import osv, fields, orm
from tools.translate import _
#from validators import validator
from validators import validator
import logging
logger = logging.getLogger('DOTCOM_PLANO_CONTAS')

class dotcom_processamento_periodico(osv.osv):
    _name='dotcom.advogacia.processamento.periodico'
    _columns={
        'cliente_id':fields.many2one('res.partner','Parceiro',required=True),
        'dossier_id':fields.many2one('dotcom.advogacia.dossier','Processo', required=False, domain="[('state','=','aberto'), ('cliente_id','=',cliente_id)]"),
        'data':fields.date('Data',required=True),
        'periodo_id':fields.many2one('configuration.period','Período',required=False),
        'descricao':fields.text('Descricao'),
        'linhas_relatorio':fields.one2many('dotcom.advogacia.relatorio.dossier.linha','processamento_id','Linhas',readonly=True),
        'tipo_facturacao':fields.selection([
                                            ('hora','Por Hora'),
                                            ('fee','Valor Fixo')
                                            ],'T. Facturação', required=False),

        'state':fields.selection([('rascunho','Aberto'),('facturado','Facturado')],'Estado'),

        'tipo_documento': fields.many2one('documento.tipo','Tipo de Documento', required=False, ),
        'prod_id': fields.many2one('product.product','Produto',domain=[('sale_ok','=',True)], required=False,),
        'prod_desc': fields.char('Descrição do Produto',size=128,  required=False),
        'doc_state':fields.selection([('rascunho','Rascunho'),('emitido','Facturado')],'Doc. Estado',required=False),
        'sequencia_id':fields.many2one('dotcom.sequence','Sequência',),
        'tipo_doc_id':fields.related('empresa_id','advogacia_tipo_documento', relation='documento.tipo',string='Tipo Documento'),
        'empresa_id':fields.many2one('res.company','Empresa'),
        'venda_id':fields.many2one('dotcom.venda','Factura', readonly=True),

        'timesheet_ids':fields.one2many('dotcom.advogacia.timesheet','processamento_id','Timesheets',readonly=True),
    }

    _defaults={
        'state':'rascunho',
        'data': lambda *a: time.strftime('%Y-%m-%d'),
        #'report_type': lambda *a: 'pdf',
        'tipo_documento':lambda self,cr,uid,c: self.pool.get('res.company')._get_tipo_doc(cr, uid, 'dotcom.internos.intervencao'),
        'prod_id':lambda self,cr,uid,c: self.pool.get('res.company').get_produto(cr, uid, 'dotcom.internos.intervencao'),
        'doc_state':lambda self,cr,uid,c: self.pool.get('res.company')._get_doc_state(cr, uid, 'dotcom.internos.intervencao', context=c),
        'prod_desc':lambda self,cr,uid,c: self.pool.get('res.company')._get_prod_desc(cr, uid, 'dotcom.internos.intervencao', context=c),
        'sequencia_id':lambda self,cr,uid,c: self.pool.get('res.company').get_sequencia(cr, uid, 'dotcom.internos.intervencao'),

        #'nome':validator.validar_referencia_intervencao,
    }

    def on_change_produto(self,cr,uid,ids,produto,context=None):
        if context is None:
            context={}
        val={}
        if produto==False:
            val={'prod_desc':''}
        else:
            produto=self.pool.get('product.product').browse(cr,uid,produto)
            val={'prod_desc':produto.name}
        logger.info('DESC %s' % str(val))
        return{'value':val}

    def actualizar_linhas_relatorio(self, cr,uid,ids,context={}):
        if context is None:
            context={}
        for documento in self.browse(cr,uid,ids):
            self.pool.get('dotcom.licence').check_expiry(cr,uid,'dotcom_advogados',context)
            logger.info('PROCESSO INICIADO')

            dossiers_ids=[]

            if (documento.dossier_id.id==True):
                dossiers_ids.append(documento.dossier_id.id)
            else:
                if bool(documento.tipo_facturacao)==True:
                    dossiers_ids=self.pool.get('dotcom.advogacia.dossier').search(cr,uid,[
                                                                            ('cliente_id','=',documento.cliente_id.id),
                                                                            ('tipo_facturacao','=',documento.tipo_facturacao),
                                                                            ('state','=','aberto')
                                                                            ])
                else:
                    dossiers_ids=self.pool.get('dotcom.advogacia.dossier').search(cr,uid,[
                                                                        ('cliente_id','=',documento.cliente_id.id),
                                                                        #('tipo_facturacao','=',documento.tipo_facturacao),
                                                                        ('state','=','aberto')
                                                                        ])

            for linha in documento.linhas_relatorio:
                self.pool.get('dotcom.advogacia.relatorio.dossier.linha').unlink(cr,uid,linha.id)

            for linha in documento.timesheet_ids:
                self.pool.get('dotcom.advogacia.timesheet').write(cr,uid,linha.id,{'processamento_id':None})

            advogados_ids=self.pool.get('dotcom.advogacia.consultor').search(cr,uid,[])
            #dossiers_ids=[]

            logger.info('TIPO DE FACTURACAO ACHADO %s' %str(dossiers_ids))

            if (documento.periodo_id.id)==False:
                for dossier in dossiers_ids:
                    dossier=self.pool.get('dotcom.advogacia.dossier').browse(cr,uid,dossier)
                    total_tempo_trabalhado=0
                    total_tempo_facturavel=0
                    valor_total=0

                    for folhas_trabalho in dossier.timesheets_ids:
                        if folhas_trabalho.state=='confirmado':

                            total_tempo_trabalhado=total_tempo_trabalhado+folhas_trabalho.tempo_trabalhado
                            #total_tempo_facturavel=total_tempo_facturavel+folhas_trabalho.tempo_facturavel
                            consultor_id=folhas_trabalho.consultor_id
                            advogados_participacao_ids=self.pool.get('dotcom.advogacia.consultor.dossier').search(cr,uid,[('consultor_id','=',folhas_trabalho.consultor_id.id),
                                                                                ('dossier_id','=',dossier.id),
                                                                                ('activo','=',True)])
                            consultor_id=self.pool.get('dotcom.advogacia.consultor.dossier').browse(cr,uid,advogados_participacao_ids[0])

                            valor=total_tempo_trabalhado*consultor_id.honorarios_metical

                            valor_total=valor_total+valor
                            logger.info('HONORARIOS DO CONSULTOR %s' %str(folhas_trabalho.consultor_id.honorario_hora))
                            #logger.info('HORAS DA FOLHA %s' %str(folhas_trabalho.tempo_facturavel))
                            logger.info('VALOR DE CADA FOLHA %s' %str(valor))
                            self.pool.get('dotcom.advogacia.timesheet').write(cr,uid,folhas_trabalho.id,{'processamento_id':documento.id})

                    if dossier.tipo_facturacao=='fee':
                        valor_total=dossier.valor_dossier

                    val={
                            'dossier_id':dossier.id,
                            'valor_total':valor_total,
                            'data_abertura':dossier.data_abertura,
                            'data_fecho':dossier.data_fecho,
                            'horas_trabalhadas':total_tempo_trabalhado,
                            'hora_facturadas':total_tempo_facturavel,
                            'processamento_id':documento.id,
                            'cliente_id':documento.cliente_id.id,
                            'tipo_facturacao':dossier.tipo_facturacao,
                        }

                    if valor_total>0:
                        linha_id=self.pool.get('dotcom.advogacia.relatorio.dossier.linha').create(cr,uid,val)

            else:
                logger.info('DOSSIERS DO CLIENTE ACHADOS %s' %str(dossiers_ids))
                for dossier in dossiers_ids:
                    dossier=self.pool.get('dotcom.advogacia.dossier').browse(cr,uid,dossier)
                    total_tempo_trabalhado=0
                    total_tempo_facturavel=0
                    valor_total=0

                    for folhas_trabalho in dossier.timesheets_ids:
                        if folhas_trabalho.periodo_id.id==documento.periodo_id.id:

                            total_tempo_trabalhado=total_tempo_trabalhado+folhas_trabalho.tempo_trabalhado
                            #total_tempo_facturavel=total_tempo_facturavel+folhas_trabalho.tempo_facturavel
                            valor=total_tempo_trabalhado*folhas_trabalho.consultor_id.honorarios_metical

                            consultor_id=folhas_trabalho.consultor_id
                            advogados_participacao_ids=self.pool.get('dotcom.advogacia.consultor.dossier').search(cr,uid,[('consultor_id','=',folhas_trabalho.consultor_id.id),
                                                                                ('dossier_id','=',dossier.id),
                                                                                ('activo','=',True)])
                            consultor_id=self.pool.get('dotcom.advogacia.consultor.dossier').browse(cr,uid,advogados_participacao_ids[0])

                            valor_total=valor_total+valor
                            logger.info('HONORARIOS DO CONSULTOR %s' %str(consultor_id.honorario_hora))
                            #logger.info('HORAS DA FOLHA %s' %str(folhas_trabalho.tempo_facturavel))
                            logger.info('VALOR DE CADA FOLHA %s' %str(valor))
                            self.pool.get('dotcom.advogacia.timesheet').write(cr,uid,folhas_trabalho.id,{'processamento_id':documento.id})

                    if dossier.tipo_facturacao=='fee':
                        valor_total=dossier.valor_dossier

                    val={
                            'dossier_id':dossier.id,
                            'valor_total':valor_total,
                            'data_abertura':dossier.data_abertura,
                            'data_fecho':dossier.data_fecho,
                            'horas_trabalhadas':total_tempo_trabalhado,
                            'hora_facturadas':total_tempo_facturavel,
                            'processamento_id':documento.id,
                            'cliente_id':documento.cliente_id.id,
                            'tipo_facturacao':dossier.tipo_facturacao,
                        }
                    if valor_total>0:
                        #linha_id=self.pool.get('dotcom.advogacia.relatorio.dossier.linha').create(cr,uid,val)
                        linha_id=self.pool.get('dotcom.advogacia.relatorio.dossier.linha').create(cr,uid,val)

            return {}

    def facturar(self, cr,uid,ids,context=None):
        if context is None:
            context={}

        for documento in self.browse(cr,uid,ids):

            logger.info('IDENTIFICACAO DO ESTADO %s' %str(documento.doc_state))
            for linha in documento.timesheet_ids:
                validator.verificar_existencia_vendas(cr,uid,linha,linha.dossier_id)

            if bool(documento.tipo_documento.id)==False:
                raise osv.except_osv(_('Acção Invalida !'), _('Preencha correctamente os dados de Facturação!!'))
            if bool(documento.sequencia_id.id)==False:
                raise osv.except_osv(_('Acção Invalida !'), _('Preencha correctamente os dados de Facturação!!'))
            if documento.doc_state!='rascunho' and documento.doc_state!='emitido':
                raise osv.except_osv(_('Acção Invalida !'), _('Preencha correctamente os dados de Facturação!!'))
            if bool(documento.prod_id.id)==False:
                raise osv.except_osv(_('Acção Invalida !'), _('Preencha correctamente os dados de Facturação!!'))

            self.pool.get('dotcom.licence').check_expiry(cr,uid,'dotcom_advogados',context)
            cliente=documento.cliente_id

            partner=''
            if cliente.customer:
                partner='customer'
            else :
                partner='debtor'

            moedas_ids=self.pool.get('res.currency').search(cr,uid,[('name','=','MT')])

            total_documento=0

            for linha_produto in documento.linhas_relatorio:
                total_documento=total_documento+linha_produto.valor_total

            estado_documento=None
            if documento.doc_state=='rascunho':
                estado_documento='draft'
            elif documento.doc_state=='emitido':
                estado_documento='validated'

            val={

                'partner_id':cliente.id,
                'partner_address_id':cliente.address[0].id,
                'partner_type':partner ,
                'partner_name':cliente.name,
                'partner_address':cliente.address[0].street,
                'partner_nuit':cliente.nuit,
                'doc_type':documento.tipo_documento.id,
                'document_date':documento.data,
                'due_date':documento.data,
                'payment_term_id':cliente.condicao_pagamento.id or None,
                'sequence_id':documento.sequencia_id.id,
                'currency_default':moedas_ids[0],
                'lines_sum':total_documento,
                'state':estado_documento,
                'processamento_id':documento.id
            }

            logger.info('NUMERO DE TIMESHEETS ASHADOS %s' %str(val))

            venda = self.pool.get('dotcom.advocacia.copia.venda').create(cr,uid,val)

            nota='Referente a(s)/ao(s) '+str(documento.prod_desc)+' do(s) dia(s):'

            for timesheet in documento.timesheet_ids:
                self.pool.get('dotcom.advogacia.timesheet').write(cr,uid,timesheet.id,{'copia_venda_id':venda})

            nota_linha=None
            for linha_produto in documento.linhas_relatorio:

                valor_total=linha_produto.valor_total
                if linha_produto.dossier_id.tipo_facturacao=='hora':
                    for sublinhas in linha_produto.dossier_id.timesheets_ids:
                        nota_linha='Referente a(s)/ao(s) '+str(documento.prod_desc)+' do(s) dia(s):'
                        if bool(documento.periodo_id.id)==True:
                            if sublinhas.state=='confirmado' and sublinhas.periodo_id==documento.periodo_id.id:
                                nota=nota+"""
                                """+str(sublinhas.timesheet_id.data)+" com "+str(sublinhas.tempo_trabalhado)+" horas"

                                nota_linha=nota_linha+"""
                                """+str(sublinhas.timesheet_id.data)+" com "+str(sublinhas.tempo_trabalhado)+" horas"
                        else:
                            if sublinhas.state=='confirmado':
                                nota=nota+"""
                                    """+str(sublinhas.data)+" com "+str(sublinhas.tempo_trabalhado)+" horas"
                                nota_linha=nota_linha+ """
                                    """+str(sublinhas.data)+" com "+str(sublinhas.tempo_trabalhado)+" horas"

                else:
                    #if documento.tipo_facturacao!='hora':
                    self.pool.get('dotcom.advogacia.dossier').write(cr,uid,linha_produto.dossier_id.id,{'copia_venda_id':venda})

                    validator.validar_existencia_facturas(cr,uid,linha_produto.dossier_id)
                    nota=nota+"""
                        Processo com facturação do tipo Valor Fixo"""
                    valor_total=linha_produto.dossier_id.valor_dossier

                    logger.info('PASSOU PELO FOR')

                linha_venda={
                        'prod_id':documento.prod_id.id,
                        'prod_desc':documento.prod_desc,
                        'qty':1,
                        'unit_price':valor_total,
                        'tax_id':documento.prod_id.iva_id.id or None,
                        'line_total':valor_total,
                        'document_top':venda,
                        'total_temp':0,
                        'iva_incluido':0,
                        'lines_sum':total_documento,
                        'line_total':valor_total,
                        'iva_incluido':valor_total,
                        'notes':nota_linha,
                        #'time_sheet_id':linha_produto.id,
                    }
                linha=self.pool.get('dotcom.advocacia.copia.linha.venda').create(cr,uid,linha_venda)

                #for time_sheet in linha_produto.timesheets_ids:
                #    logger.info('ESTADO DO DOCUMENTO DE VENDA A SER GERADO %s' %str(time_sheet.id))

            resumo={
                    'tipo_documento':str(documento.tipo_documento.name)or None,
                    'numero_documento':'' or None,
                    'parceiro':cliente.name,
                    'produto':documento.prod_id.name,
                    'notas':nota,
                    'estado_documento':documento.doc_state,
                    #'linha_venda':linha,
                    'copia_venda':venda,
                    'state':'draft',
                }

            #linha=self.pool.get('dotcom.venda.linha').create(cr,uid,linha_venda)

            #if documento.doc_state=='rascunho':
            #    self.pool.get('dotcom.venda').pre_compute(cr,uid,[venda])
            #if documento.doc_state=='emitido':
            #    logger.info('ENTROU NOS EMITIDOS')
            #    self.pool.get('dotcom.venda').post(cr,uid,[venda])
            #
            #self.write(cr,uid,documento.id,{
            #                                'state':'facturado',
            #                                'venda_id':venda
            #                                })

            resumo_id=self.pool.get('dotcom.advocacia.factura').create(cr,uid,resumo)

        return {
            'type': 'ir.actions.act_window',
            'name': 'Documento gerado com sucesso',
            'view_mode': 'form',
            'view_type': 'form',
            'res_model': 'dotcom.advocacia.factura',
            'res_id':resumo_id,
            'target': 'new',
            'context': context,
            'nodestroy': True,
        }

dotcom_processamento_periodico()


#  Copyright (c) 2021 GradsFlow. All rights reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
from typing import Optional

import pytorch_lightning as pl
from loguru import logger

class AutoDataset:
    def __init__(
        self,
        train_dataloader: Optional = None,
        val_dataloader: Optional = None,
        datamodule: Optional[pl.LightningDataModule] = None,
        num_classes: Optional[int] = None,
    ):

        self.datamodule = None
        self.num_classes = num_classes

        if not (datamodule or train_dataloader):
            raise UserWarning("Both datamodule and train_dataloader can't be None!")

        if all((datamodule, train_dataloader)):
            logger.warning(
                "Both datamodule and train_dataloader is set!"
                "Using datamodule over train_dataloader."
            )

        if not datamodule:
            datamodule = pl.LightningDataModule()
            datamodule.train_dataloader = train_dataloader
            datamodule.val_dataloader = val_dataloader
            datamodule.num_classes = num_classes

        if datamodule:
            self.datamodule = datamodule
            if hasattr(datamodule, "num_classes"):
                num_classes = datamodule.num_classes
            if num_classes is None:
                raise UserWarning("num_classes is None!")

        self.datamodule = datamodule
        self.num_classes = num_classes


from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length, ValidationError
from stockTicker import stockExists, mmdict_tf

class stockInput(FlaskForm):
    symbol = StringField('Symbol',
                           validators=[DataRequired(), Length(min=1, max=5)])

    def validate_symbol(self,field):
        if not stockExists(field.data):
            raise ValidationError("Stock does not exist")

    month = StringField('Month',
                        validators=[DataRequired(), Length(min=1,max=10)])
    def validate_month(self,field):
        if not mmdict_tf(field.data):
            raise ValidationError("Month is not correct format")

    year = StringField('Year',
                        validators=[DataRequired(), Length(min=4,max=4)])
    def validate_year(self,field):
        if field.data not in [str(i) for i in list(range(1900,2018))]:
            raise ValidationError("Year is not correct format")

    submit = SubmitField('Confirm')

class goBack(FlaskForm):
    back = SubmitField("Back")


# This code analyses a credit card fraud dataset from kaggle
# https://www.kaggle.com/mlg-ulb/creditcardfraud

# most attributes are annonymous numerical data (we don't know what they are)

# The dataset has 30 attributes + the class attribute
# class = 1 is fraud, class = 0 is not fraud
# the aim is to build a model which is able to predict fraud

# to achieve this, I use tensorflow to build a neural network

# the dataset is imbalanced (< 1% of records are fraud cases)

# result: > 95% accuracy for both fraud and non-fraud cases

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# import data

data = pd.read_csv("creditcard.csv")

# split data into fradulent and non-fraudulent data

# as the dataset is imbalanced, I increase
# the sample size of the fraudulent cases

# I also want to know if the model is able to predict
# non-fraud cases and fraud cases

data_non_fraud = data[data["Class"]==0]
data_fraud = data[data["Class"]==1]

# seperate the target attribute from the other attributes

x_non_fraud = data_non_fraud.drop(["Class"], axis=1)
y_non_fraud = data_non_fraud["Class"]

x_fraud = data_fraud.drop(["Class"], axis=1)
y_fraud = data_fraud["Class"]

# scale data

scaler = StandardScaler()

x_non_fraud = scaler.fit_transform(x_non_fraud)
x_fraud = scaler.fit_transform(x_fraud)

# split data into training and testing

x_non_fraud_train, x_non_fraud_test, y_non_fraud_train, y_non_fraud_test = train_test_split(x_non_fraud, y_non_fraud, test_size=0.33)
x_fraud_train, x_fraud_test, y_fraud_train, y_fraud_test = train_test_split(x_fraud, y_fraud, test_size=0.33)

# increase fraud sample to make a balanced dataset

# to achieve this, we will duplicate the fraud records
# until the number of fraud records = non fraud records
# (over-sampling)

n_non_fraud = len(x_non_fraud_train)

while len(x_fraud_train)<n_non_fraud:
    x_fraud_train = np.concatenate((x_fraud_train,x_fraud_train),axis=0)

x_fraud_train = x_fraud_train[0:len(x_non_fraud_train)]

y_fraud_train = np.full(n_non_fraud,1)
y_non_train_fraud = np.full(n_non_fraud,0)

# recombine fraud and non_fraud training samples

x_train = np.concatenate((x_fraud_train,x_non_fraud_train))
y_train = np.concatenate((y_fraud_train,y_non_fraud_train))

# function to build neural network model

def build_NN(n_hidden_layer,epochs):

    model = keras.Sequential([
            layers.Dense(30,activation = tf.nn.relu,input_shape=[30]),
            keras.layers.Dense(n_hidden_layer,activation="relu"),
            keras.layers.Dense(2,activation="softmax")
            ])

    model.compile(optimizer="adam",loss = "sparse_categorical_crossentropy",metrics=["accuracy"])

    model.fit(x_train,y_train,epochs=epochs)
    return model

# define function to test model
# outputs tuple with % correct predictions
# for non_fraud and fraud respectively

def test_model(model):

    non_fraud_predictions = np.array(list(map(np.argmax,model.predict(x_non_fraud_test))))
    non_fraud_correct = np.count_nonzero(non_fraud_predictions==0)/len(non_fraud_predictions)*100.0

    fraud_predictions = np.array(list(map(np.argmax,model.predict(x_fraud_test))))
    fraud_correct = np.count_nonzero(fraud_predictions==1)/len(fraud_predictions)*100.0

    return (non_fraud_correct,fraud_correct)

# test 2 models
# n_hidden_layer = 10 and 20
# both with epochs = 10

model_10 = build_NN(10,10)
model_20 = build_NN(20,10)

print(test_model(model_10))
print(test_model(model_20))


from sqlalchemy import (MetaData, Table, Column, Integer, DateTime, ForeignKey, Unicode)

metadata = MetaData()

update_table = Table(
    'update',
    metadata,
    Column('id', Integer, primary_key = True),
    Column('time', DateTime),
    Column('total_online', Integer)
)


import unittest

from python import part1and2 as d1p1n2
# from python import part2 as d2p2

class TestDay1(unittest.TestCase):
    def test_part1(self):
        input_list = ["R5", "L5", "R5", "R3"]
        assert_int = 12
        self.assertEqual(d1p1n2.move(input_list)[0], assert_int)
        input_list = ["R8", "R4", "R4", "R8"]
        assert_int = 4
        self.assertEqual(d1p1n2.move(input_list)[1], assert_int)

    #To check that any future changes still give the now known solution
    def test_answers(self):
        import os
        if "day1" in os.getcwd():
            path = "python/"
        else:
            path = "day1_Taxicab/python/"
        final_position, first_crossing = d1p1n2.run(path=path)
        self.assertEqual(final_position, 278)
        self.assertEqual(first_crossing, 161)

def main():
    unittest.main()

if __name__ == "__main__":
    main()


"""
A unit fraction contains 1 in the numerator.
The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2	= 	0.5
1/3	= 	0.(3)
1/4	= 	0.25
1/5	= 	0.2
1/6	= 	0.1(6)
1/7	= 	0.(142857)
1/8	= 	0.125
1/9	= 	0.(1)
1/10	= 	0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle.
It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
"""

def convert(numerator, denominator):
    ans = str(numerator // denominator) + "."
    le = {}
    index = 0
    numerator = numerator % denominator
    le[numerator] = index
    t = False
    while t == False:
        if numerator == 0:
            break
        digit = numerator * 10 // denominator
        numerator = numerator * 10 - (numerator * 10 // denominator) * denominator
        if numerator not in le:
            ans += str(digit)
            index += 1
            le[numerator] = index
            t = False
        else:
            ans += str(digit)+")"
            ans = ans[:le.get(numerator) + len(ans[:ans.index(".") + 1])] + "(" + ans[le.get(numerator) + len(ans[:ans.index(".") + 1]):]
            t = True
    return ans

max_len = '0'
j = 0
for i in range(1, 1000):
    if len(max_len) < len(convert(1, i)[2:]):
        max_len = convert(1, i)[2:]
        j = i
print(j)


# uncompyle6 version 3.6.7
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: /Users/mx/Dropbox (MIT)/Science/Code/allesfitter/priors/transform_priors.py
# Compiled at: 2018-11-07 16:44:32
__doc__ = '\nCreated on Tue Oct  2 22:10:28 2018\n\n@author:\nMaximilian N. Günther\nMIT Kavli Institute for Astrophysics and Space Research, \nMassachusetts Institute of Technology,\n77 Massachusetts Avenue,\nCambridge, MA 02109, \nUSA\nEmail: maxgue@mit.edu\nWeb: www.mnguenther.com\n'
from __future__ import print_function, division, absolute_import
import seaborn as sns
sns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True)
sns.set_style({'xtick.direction': 'in', 'ytick.direction': 'in'})
sns.set_context(rc={'lines.markeredgewidth': 1})
import numpy as np
from .simulate_PDF import simulate_PDF as spdf

def get_cosi_from_i(i, Nsamples=10000):
    i = spdf(i[0], i[1], i[2], size=Nsamples, plot=False)
    cosi = np.cos(np.deg2rad(i))
    ll, median, ul = np.percentile(cosi, [16, 50, 84])
    return (
     median, median - ll, ul - median)

def get_Rsuma_from_a_over_Rstar(a_over_Rstar, Rp_over_Rstar, Nsamples=10000):
    a_over_Rstar = spdf(a_over_Rstar[0], a_over_Rstar[1], a_over_Rstar[2], size=Nsamples, plot=False)
    Rstar_over_a = 1.0 / a_over_Rstar
    Rp_over_Rstar = spdf(Rp_over_Rstar[0], Rp_over_Rstar[1], Rp_over_Rstar[2], size=Nsamples, plot=False)
    Rsuma = Rstar_over_a * (1.0 + Rp_over_Rstar)
    ll, median, ul = np.percentile(Rsuma, [16, 50, 84])
    return (
     median, median - ll, ul - median)

def get_Rsuma_from_Rstar_over_a(Rstar_over_a, Rp_over_Rstar, Nsamples=10000):
    Rstar_over_a = spdf(Rstar_over_a[0], Rstar_over_a[1], Rstar_over_a[2], size=Nsamples, plot=False)
    Rp_over_Rstar = spdf(Rp_over_Rstar[0], Rp_over_Rstar[1], Rp_over_Rstar[2], size=Nsamples, plot=False)
    Rsuma = Rstar_over_a * (1.0 + Rp_over_Rstar)
    ll, median, ul = np.percentile(Rsuma, [16, 50, 84])
    return (
     median, median - ll, ul - median)


import numpy as np
import pandas as pd
from qpsolvers import quadprog_solve_qp

import matplotlib.pyplot as plt

df = pd.read_csv("/Users/apple/Desktop/Coding/Sem5/Assignment3_Code/iris.data")

error1 = []
x = []
data_setosa = df.iloc[0:50,0:4].values
data_versicolor = df.iloc[50:100,0:4].values
data_virginica = df.iloc[100:150,0:4].values

# Setosa is of class 1, versicolor is of class 2, virginica is of class 3
data_class_setosa = np.concatenate((np.ones((50,1)),data_setosa,np.ones((50,1))*(-1)),axis = 1)
data_class_versicolor = np.concatenate((np.ones((50,1)),data_versicolor,np.ones((50,1))),axis = 1)

data_class = np.concatenate((data_class_setosa,data_class_versicolor),axis = 0)
np.random.shuffle(data_class)
percentage = 0.7                # Percentage of training set
size = 70
training_set = data_class[0:int(percentage*100),:]       # Training data
test_set = data_class[int(percentage*100):100,:]         # Test data

P = np.array([[10**(-10),0,0,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]],dtype='float')
G = np.zeros((size,5))
h = np.zeros(size)
q = np.zeros(5)
A = np.zeros((5,5))
b = np.zeros(5)
for i in range(size):
    for j in range(5):
        G[i][j] = -training_set[i,j]*training_set[i,5]
for i in range(70):
    h[i] = -1
weights = quadprog_solve_qp(P, q, G, h, A, b)
print("QP solution: x = {}".format(weights))

#for computing Error
err = 0

for i in range(100-size):
    predict = np.dot(np.transpose(weights),np.transpose(test_set[i,0:5]))
    if test_set[i,5] == 1 and predict<-1:
        err = err + 1
    elif test_set[i,5] == -1 and predict>1:
        err = err + 1
print(err)


import os
p = input("Podaj sciezke: ")
r = input("Podaj rozszerzenie pliku: ")

def generator(path,roz):
    for plik in os.listdir(path):
        pom = plik.split('.')
        if pom[1] == roz:
            yield plik

for file in generator(p,r):
    print(file)


#!/usr/bin/env python
"""
Copyright (c) 2015 Jonas Krehl <Jonas.Krehl@triebenberg.de>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""

import numpy
import numexpr
import scipy.interpolate

import reikna.core
import reikna.cluda
import reikna.helpers
from reikna.cluda.api import Thread

from ....Mathematics import FourierTransforms as FT
from ...Potentials.AtomPotentials import WeickenmeierKohl

from ..Base import PlaneOperator

class AtomPhaseshift(reikna.core.Computation):
	def __init__(self, tf, ps, ys, xs, B, ky, kx, kk):
		super().__init__([reikna.core.Parameter('tf', reikna.core.Annotation(tf, 'io')),
						  reikna.core.Parameter('ps', reikna.core.Annotation(ps, 'i')),
						  reikna.core.Parameter('ys', reikna.core.Annotation(ys, 's')),
						  reikna.core.Parameter('xs', reikna.core.Annotation(xs, 's')),
						  reikna.core.Parameter('B', reikna.core.Annotation(B, 's')),
						  reikna.core.Parameter('ky', reikna.core.Annotation(ky, 'i')),
						  reikna.core.Parameter('kx', reikna.core.Annotation(kx, 'i')),
						  reikna.core.Parameter('kk', reikna.core.Annotation(kk, 'i'))])

	def _build_plan(self, plan_factory, device_params, tf, ps, ys, xs, B, ky, kx, kk):
		plan = plan_factory()

		template = reikna.helpers.template_from(
			"""
			<%def name='function(kernel_declaration, tf, ps, ys, xs, B, ky, kx, kk)'>
				${kernel_declaration}
				{
				VIRTUAL_SKIP_THREADS;
				const VSIZE_T idy = virtual_global_id(0);
				const VSIZE_T idx = virtual_global_id(1);
				${tf.store_idx}(idy, idx, ${mulp}(${ps.load_idx}(idy, idx), ${expx}(${addx}(${muli}(COMPLEX_CTR(float2)(0,1), ${adds}(${muly}(${ys}, ${ky.load_idx}(idy)), ${mulx}(${xs}, ${kx.load_idx}(idx)))), ${mulB}(-${B}/8., ${kk.load_idx}(idy,idx))))));
				}
			</%def>
			""")

		Bkk_dtype = reikna.cluda.dtypes.result_type(B.dtype, kk.dtype)
		kxs_dtype = reikna.cluda.dtypes.result_type(xs.dtype, kx.dtype)
		kys_dtype = reikna.cluda.dtypes.result_type(ys.dtype, ky.dtype)
		ks_dtype = reikna.cluda.dtypes.result_type(kys_dtype, kxs_dtype)
		cks_dtype = reikna.cluda.dtypes.result_type(numpy.complex64, ks_dtype)
		Bcks_dtype = reikna.cluda.dtypes.result_type(cks_dtype, Bkk_dtype)

		plan.kernel_call(template.get_def('function'),
						 [tf, ps, ys, xs, B, ky, kx, kk],
						 global_size=tf.shape,
						 render_kwds=dict(mulB=reikna.cluda.functions.mul(B.dtype, kk.dtype),
										  mulx=reikna.cluda.functions.mul(xs.dtype, kx.dtype),
										  muly=reikna.cluda.functions.mul(ys.dtype, ky.dtype),
										  adds=reikna.cluda.functions.add(kys_dtype, kxs_dtype),
										  muli=reikna.cluda.functions.mul(numpy.complex64, ks_dtype),
										  addx=reikna.cluda.functions.add(cks_dtype, Bkk_dtype),
										  expx=reikna.cluda.functions.exp(Bcks_dtype),
										  mulp=reikna.cluda.functions.mul(ps.dtype, Bcks_dtype)
									  ))
		return plan

class Expi(reikna.core.Computation):
	def __init__(self, arg):
		super().__init__([reikna.core.Parameter('res', reikna.core.Annotation(arg, 'o')),
						  reikna.core.Parameter('arg', reikna.core.Annotation(arg, 'i'))])

	def _build_plan(self, plan_factory, device_params, res, arg):
		plan = plan_factory()

		template = reikna.helpers.template_from(
			"""
			<%def name='function(kernel_declaration, res, arg)'>
				${kernel_declaration}
				{
				VIRTUAL_SKIP_THREADS;
				const VSIZE_T idy = virtual_global_id(0);
				const VSIZE_T idx = virtual_global_id(1);
				${res.store_idx}(idy, idx, ${exp}(${mul}(COMPLEX_CTR(${arg.ctype})(0,1), ${div}(${arg.load_idx}(idy, idx), ${f}))));
				}
			</%def>
			""")

		plan.kernel_call(template.get_def('function'),
						 [res, arg],
						 global_size=arg.shape,
						 render_kwds=dict(mul=reikna.cluda.functions.mul(arg.dtype, arg.dtype, out_dtype=res.dtype),
										  exp=reikna.cluda.functions.exp(res.dtype),
										  div = reikna.cluda.functions.div(arg.dtype, int, out_dtype=arg.dtype),
										  f=arg.size))
		return plan

class RegionMult(reikna.core.Computation):
	def __init__(self, A, B):
		super().__init__([reikna.core.Parameter('A', reikna.core.Annotation(A, 'io')),
						  reikna.core.Parameter('B', reikna.core.Annotation(B, 'i')),
						  reikna.core.Parameter('Aoff0', reikna.core.Annotation(numpy.uint, 's')),
						  reikna.core.Parameter('Aoff1', reikna.core.Annotation(numpy.uint, 's')),
						  reikna.core.Parameter('Boff0', reikna.core.Annotation(numpy.uint, 's')),
						  reikna.core.Parameter('Boff1', reikna.core.Annotation(numpy.uint, 's')),
						  reikna.core.Parameter('len0', reikna.core.Annotation(numpy.uint, 's')),
						  reikna.core.Parameter('len1', reikna.core.Annotation(numpy.uint, 's')),
						 ])

	def _build_plan(self, plan_factory, device_params, A, B, Aoff0, Aoff1, Boff0, Boff1, len0, len1):
		plan = plan_factory()

		template = reikna.helpers.template_from(
			"""
			<%def name='function(kernel_declaration, A, B, Aoff0, Aoff1, Boff0, Boff1, len0, len1)'>
				${kernel_declaration}
				{
				VIRTUAL_SKIP_THREADS;
				const VSIZE_T idx0 = virtual_global_id(0);
				const VSIZE_T idx1 = virtual_global_id(1);
				//if(idx0<${len0} && idx1<${len1}){
					//${A.store_idx}(idx0+${Aoff0}, idx1+${Aoff1}, ${mul}(${A.load_idx}(idx0+${Aoff0}, idx1+${Aoff1}), ${B.load_idx}(idx0+${Boff0}, idx1+${Boff1})));
				${A.store_idx}(${add}(idx0, ${Aoff0}), ${add}(idx1, ${Aoff1}), ${mul}(${A.load_idx}(${add}(idx0, ${Aoff0}), ${add}(idx1, ${Aoff1})), ${B.load_idx}(${add}(idx0, ${Boff0}), ${add}(idx1, ${Boff1}))));
				//}
				}
			</%def>
			""")

		plan.kernel_call(template.get_def('function'),
						 [A,B, Aoff0, Aoff1, Boff0, Boff1, len0, len1],
						 global_size=tuple(min(a,b) for a,b in zip(A.shape, B.shape)),
						 render_kwds=dict(mul=reikna.cluda.functions.mul(A.dtype, B.dtype, out_dtype=A.dtype),
										 add=reikna.cluda.functions.add(numpy.uint, numpy.uint)))
		return plan

class FlatAtomDW_ROI_GPU(PlaneOperator):

	def __init__(self, atoms, thread=None, phaseshifts_f=None,
				 ky=None, kx=None, kk=None,
				 roi=None, roi_x=None, roi_y=None,
				 roi_ky=None, roi_kx=None, roi_kk=None,
				 atom_potential_generator=WeickenmeierKohl, energy=None, y=None, x=None,
				 dtype=numpy.complex,
				 lazy=True, forgetful=True,
				 compiled_atom_phaseshift=None,
				 compiled_expi=None,
				 compiled_fft_gpu=None,
				 compiled_mult=None,
	):
		self.__dict__.update(dict(thread=thread, atoms=atoms,
								  phaseshifts_f=phaseshifts_f,
								  ky=ky, kx=kx, kk=kk,
								  roi=roi, roi_y=roi_y, roi_x=roi_x,
								  roi_ky=roi_ky, roi_kx=roi_kx, roi_kk=roi_kk,
								  atom_potential_generator=atom_potential_generator, energy=energy, y=y, x=x,
								  dtype=dtype,
								  lazy=lazy, forgetful=forgetful,
								  compiled_atom_phaseshift=compiled_atom_phaseshift,
								  compiled_expi=compiled_expi,
								  compiled_fft_gpu=compiled_fft_gpu,
								  compiled_mult=compiled_mult,
							  ))

		if self.compiled_atom_phaseshift is None: self.compiled_atom_phaseshift={}
		if self.compiled_expi is None: self.compiled_expi={}
		if self.compiled_fft_gpu is None: self.compiled_fft_gpu={}
		if self.compiled_mult is None: self.compiled_mult={}

		self.transmission_function = None
		if not self.lazy:
			self.generate_tf()

		self.z = numpy.mean(self.atoms['zyx'][:,0])

	@classmethod
	def inherit(cls, parent, atoms, **kwargs):
		args = {}

		args.update({k:v for k,v in parent.transmission_function_args.items() if v is not None})
		args.update({k:v for k,v in kwargs.items() if v is not None})

		if hasattr(parent, 'propagator_args') and 'thread' in parent.propagator_args and isinstance(parent.propagator_args['thread'], Thread):
			args['thread'] = parent.propagator_args['thread']
		elif not 'thread' in args or args['thread'] is None:
			args['thread'] = reikna.cluda.any_api().Thread.create()
		elif isinstance(args['thread'], Thread):
			pass
		elif args['thread'] == 'cuda':
			args['thread'] = reikna.cluda.cuda_api().Thread.create()
		elif args['thread'] == 'opencl':
			args['thread'] = reikna.cluda.ocl_api().Thread.create()
		else:
			raise ValueError
		thread = args['thread']

		args.update({s:parent.__dict__[s] for s in ['y', 'x'] if s not in args or args[s] is None})
		args.update({s:thread.to_device(parent.__dict__[s]) for s in ['ky', 'kx', 'kk'] if s not in args or args[s] is None})

		if 'roi' not in args or args['roi'] is None:
			args['roi'] = 1e-9

		if 'roi_y' not in args or args['roi_y'] is None:
			dy = args['y'][1]-args['y'][0]
			ay = numpy.ceil(args['roi']/dy)
			args['roi_y'] = dy*numpy.arange(-ay,ay+1)

		if 'roi_x' not in args or args['roi_x'] is None:
			dx = args['x'][1]-args['x'][0]
			ax = numpy.ceil(args['roi']/dx)
			args['roi_x'] = dx*numpy.arange(-ax,ax+1)

		if 'roi_ky' not in args or args['roi_ky'] is None:
			args['roi_ky'] = thread.to_device(FT.reciprocal_coords(args['roi_y']))

		if 'roi_kx' not in args or args['roi_kx'] is None:
			args['roi_kx'] = thread.to_device(FT.reciprocal_coords(args['roi_x']))

		if 'roi_kk' not in args or args['roi_kk'] is None:
			args['roi_kk'] = thread.to_device(numpy.add.outer(args['roi_ky'].get()**2, args['roi_kx'].get()**2))

		if 'phaseshifts_f' not in args or args['phaseshifts_f'] is None or not set(numpy.unique(atoms['Z'])).issubset(set(args['phaseshifts_f'].keys())):
			if hasattr(parent, 'phaseshifts_f') and parent.phaseshifts_f is not None:
				args['phaseshifts_f'] = parent.phaseshifts_f
			else:
				if 'energy' not in args or args['energy'] is None:
					args['energy'] = parent.energy
				if 'atom_potential_generator' not in args or args['atom_potential_generator'] is None:
					args['atom_potential_generator'] = parent.atom_potential_generator
				if 'phaseshifts_f' not in args or args['phaseshifts_f'] is None:
					args['phaseshifts_f'] = {}
				args['phaseshifts_f'].update({i: thread.to_device(1/(args['roi_y'].size*args['roi_x'].size)*args['atom_potential_generator'].cis_phaseshift_f(i, args['energy'], args['roi_y'], args['roi_x'])) for i in set(numpy.unique(atoms['Z'])).difference(set(args['phaseshifts_f'].keys()))})

		if 'compiled_atom_phaseshift' not in args or args['compiled_atom_phaseshift'] is None:
			args['compiled_atom_phaseshift'] = {}
		if 'compiled_expi' not in args or args['compiled_expi'] is None:
			args['compiled_expi'] = {}
		if 'compiled_fft_gpu' not in args or args['compiled_fft_gpu'] is None:
			args['compiled_fft_gpu'] = {}
		if 'compiled_mult' not in args or args['compiled_mult'] is None:
			args['compiled_mult'] = {}

		parent.transmission_function_args.update(args)
		return cls(atoms, **args)

	# noinspection PyUnusedLocal,PyUnusedLocal
	def generate_tf(self):

		if self.phaseshifts_f is None:
			phaseshifts_f = {i: self.thread.to_device(1/(self.roi_y.size*self.roi_y.size)*self.atom_potential_generator.cis_phaseshift_f(i, self.energy, self.roi_y, self.roi_x)) for i in numpy.unique(self.atoms['Z'])}
		else:
			phaseshifts_f = self.phaseshifts_f

		if self.ky is None:
			ky = self.thread.to_device(FT.reciprocal_coords(self.y))
		else:
			ky = self.ky

		if self.kx is None:
			kx = self.thread.to_device(FT.reciprocal_coords(self.x))
		else:
			kx = self.kx

		if self.kk is None:
			kk = self.thread.to_device(numpy.add.outer(ky.get()**2, kx.get()**2))
		else:
			kk = self.kk

		if self.roi_y is None:
			roi_yl = -numpy.ceil(self.roi/dy)-1
			roi_yu = numpy.ceil(self.roi/dy)+1
			roi_y = dy*numpy.arange(roi_yl, roi_yu)
		else:
			roi_y = self.roi_y
			roi_yl = -(roi_y.size-1)//2
			roi_yu = (roi_y.size+1)//2

		if self.roi_x is None:
			roi_xl = -numpy.ceil(self.roi/dx)-1
			roi_xu = numpy.ceil(self.roi/dx)+1
			roi_x = dx*numpy.arange(roi_xl, roi_xu)
		else:
			roi_x = self.roi_x
			roi_xl = -(roi_x.size-1)//2
			roi_xu = (roi_x.size+1)//2

		if self.roi_ky is None:
			roi_ky = self.thread.to_device(FT.reciprocal_coords(roi_y))
		else:
			roi_ky = self.roi_ky

		if self.roi_kx is None:
			roi_kx = self.thread.to_device(FT.reciprocal_coords(roi_x))
		else:
			roi_kx = self.roi_kx

		if self.roi_kk is None:
			roi_kk =self.thread.to_device(numpy.add.outer(roi_ky.get()**2, roi_kx.get()**2))
		else:
			roi_kk = self.roi_kk

		if not hasattr(ky, 'thread') or ky.thread != self.thread:
			ky = self.thread.to_device(ky)
		if not hasattr(kx, 'thread') or kx.thread != self.thread:
			kx = self.thread.to_device(kx)
		if not hasattr(kk, 'thread') or kk.thread != self.thread:
			kk = self.thread.to_device(kk)

		self.transmission_function = self.thread.to_device(numpy.ones(kk.shape, self.dtype))
		itf = self.thread.array(roi_kk.shape, self.dtype)
		tmp = self.thread.temp_array(itf.shape, itf.dtype, itf.strides)

		sign = (self.thread,
				reikna.core.Type.from_value(itf).__repr__(),
				reikna.core.Type.from_value(list(phaseshifts_f.values())[0]).__repr__(),
				self.atoms[0]['zyx'].dtype.__repr__(),
				self.atoms[0]['B'].dtype.__repr__(),
				reikna.core.Type.from_value(roi_ky).__repr__(),
				reikna.core.Type.from_value(roi_kx).__repr__(),
				reikna.core.Type.from_value(roi_kk).__repr__())

		if sign in self.compiled_atom_phaseshift:
			atom_phaseshift = self.compiled_atom_phaseshift[sign]
		else:
			atom_phaseshift =  AtomPhaseshift(itf, list(phaseshifts_f.values())[0], self.atoms['zyx'][0,1], self.atoms['zyx'][0,2], self.atoms[0]['B'], roi_ky, roi_kx, roi_kk).compile(self.thread)
			self.compiled_atom_phaseshift[sign] = atom_phaseshift

		xsign = (self.thread, reikna.core.Type.from_value(itf).__repr__())

		if xsign in self.compiled_expi:
			expi = self.compiled_expi[xsign]
		else:
			expi = Expi(itf).compile(self.thread)
			self.compiled_expi[xsign] = expi

		if xsign in self.compiled_fft_gpu:
			fft_gpu, fftshift_gpu = self.compiled_fft_gpu[xsign]
		else:
			fft_gpu = reikna.fft.FFT(itf).compile(self.thread)
			fftshift_gpu =reikna.fft.FFTShift(itf).compile(self.thread)

			self.compiled_fft_gpu[xsign] = fft_gpu, fftshift_gpu

		msign = (self.thread, reikna.core.Type.from_value(self.transmission_function).__repr__(), reikna.core.Type.from_value(itf).__repr__())

		if msign in self.compiled_fft_gpu:
			mult = self.compiled_mult[msign]
		else:
			mult = RegionMult(self.transmission_function, itf).compile(self.thread)
			self.compiled_mult[msign] = mult

		dy = self.y[1]-self.y[0]
		dx = self.x[1]-self.x[0]

		for a in self.atoms:
			py, px = a['zyx'][1], a['zyx'][2]

			rpy, ipy = numpy.modf((py-self.y[0])/dy)
			rpx, ipx = numpy.modf((px-self.x[0])/dx)
			ipy = int(ipy)
			ipx = int(ipx)

			atom_phaseshift(itf, phaseshifts_f[a['Z']], rpy*dy, rpx*dx, a['B']/(4*numpy.pi**2), roi_ky, roi_kx, roi_kk)

			#fftshift_gpu(itf, itf)
			fft_gpu(tmp, itf, 0)
			#fftshift_gpu(tmp, tmp)
			#tmp /= itf.size
			#expi(itf, tmp)

			select = numpy.s_[ipy+roi_yl if ipy+roi_yl>=0 else 0:ipy+roi_yu if ipy+roi_yu<=self.y.size else self.y.size,
							  ipx+roi_xl if ipx+roi_xl>=0 else 0:ipx+roi_xu if ipx+roi_xu<=self.x.size else self.x.size]

			iselect = numpy.s_[0 if ipy+roi_yl>=0 else -(ipy+roi_yl): roi_y.size if ipy+roi_yu<=self.y.size else self.y.size+self.roi_y.size-ipy-roi_yu,
							   0 if ipx+roi_xl>=0 else -(ipx+roi_xl): roi_x.size if ipx+roi_xu<=self.x.size else self.x.size+self.roi_x.size-ipx-roi_xu]

			assert select[0].stop-select[0].start==iselect[0].stop-iselect[0].start and select[1].stop-select[1].start==iselect[1].stop-iselect[1].start, (py, self.y[0], dy, select, iselect)
			if (select[0].stop-select[0].start)>0 and (select[1].stop-select[1].start)>0:
				mult(self.transmission_function, tmp, select[0].start, select[1].start, iselect[0].start, iselect[1].start, select[0].stop - select[0].start, select[1].stop - select[1].start)

		del itf

	def apply(self, wave):
		if not hasattr(wave, 'thread') or wave.thread != self.thread:
			wave = self.thread.to_device(wave)

		if self.transmission_function is None:
			self.generate_tf()

		wave *= self.transmission_function

		if self.forgetful:
			self.transmission_function = None
		return wave


#!/usr/bin/env python3

#zcat raw_data/13mrt_15mrt/20170314\:20.out.gz | uniq | scripts/tools/tweet2tab id user text | python3 scripts/create_silver_set.py datasets/silver_users.csv <outfile.csv>

#file: create_silver_set.py
#06-02-2019

import sys
import numpy as np
import pandas as pd
import ast

def build_Tweet_Dict(tweet,tweet_Dict,user_List,user_Dict,ignore_List):
	[ident,user,text] = tweet.rstrip().split('\t')

	if ident not in ignore_List:
		if user in user_List:
			user_Party = user_Dict[user]

			retweet = False

			if text[:4] == "RT @":
				retweet = True

			if user not in tweet_Dict.keys():
				if retweet == False:
					tweet_Dict[user] = (user_Party,[text],[])
				elif retweet == True:
					tweet_Dict[user] = (user_Party,[],[text])

			elif user in tweet_Dict.keys():
				user_Tweets = tweet_Dict[user][1]
				user_Retweets = tweet_Dict[user][2]

				if retweet == False:
					user_Tweets.append(text)
				elif retweet == True:
					user_Retweets.append(text)
				tweet_Dict[user] = (user_Party,user_Tweets,user_Retweets)

def build_Dataframe(tweet_Dict):
	column = ["username","party","ntotal_tweets","n_retweets","tweets","retweets"]
	dicts_List = []

	for user in tweet_Dict.keys():
		assigned_Label = tweet_Dict[user][0]
		tweet_List = tweet_Dict[user][1]
		retweet_List = tweet_Dict[user][2]
		ntotal_tweets = len(tweet_List) + len(retweet_List)
		n_retweets = len(retweet_List)

		new_Dict = {"username":user,"party":assigned_Label,"ntotal_tweets":ntotal_tweets,"n_retweets":n_retweets,"tweets":tweet_List,"retweets":retweet_List}

		if ntotal_tweets > 9:
			dicts_List.append(new_Dict)

	df = pd.DataFrame(dicts_List,columns = column)

	return df

def main(argv):

	label_File_Path = argv[1]
	csv_file_name = argv[2]

	# Dataframe inladen vanuit .csv bestand
	user_Dataframe = pd.read_csv(label_File_Path, sep='\t', encoding='utf-8', index_col=0).dropna()

	user_List = user_Dataframe.username.values
	label_List = user_Dataframe.party.values
	id_Tweets_List = user_Dataframe['identified_tweets_id']

	ignore_List = []
	for user_Tweets in id_Tweets_List:
		tweets_List = ast.literal_eval(user_Tweets)
		ignore_List = ignore_List + tweets_List

	user_Dict = {}

	for i in range(len(user_List)):
		user_Dict[user_List[i]] = label_List[i]

	tweet_Dict = {}

	for tweet in sys.stdin:
		build_Tweet_Dict(tweet,tweet_Dict,user_List,user_Dict,ignore_List)

	df = build_Dataframe(tweet_Dict)

	#csv_file_name = 'datasets/silver_tweets_new.csv'
	df.to_csv(csv_file_name, sep='\t', encoding='utf-8')

if __name__ == "__main__":
	main(sys.argv)


import json
import sqlite3

class Ispiti(dict):

    def dodaj(self, student, kolegij, ocjena):
        if student not in self:
            self[student] = {}
        self[student][kolegij] = ocjena

    def izbrisi(self, student, kolegij):
        if kolegij in self[student]:
            self[student].pop(kolegij)

    def promijeni(self, student, kolegij, ocjena):
        self[student][kolegij] = ocjena

    def snimi_datoteka(self, naziv):
        for ime in self:
            for predmet in self[ime]:
                with open(naziv, 'a') as f:
                    student = ime + "\t" + str(predmet) + "\t" +  str(self[ime][predmet]) + "\n"
                    f.write(student)

    def otvori_datoteka(self,naziv):
        b = Ispiti()
        with open(naziv, 'r') as f:
            for line in f:
                a = line.replace("\n", "\t").split("\t")
                b.dodaj(a[0],a[1],a[2])
        return b

    def snimi_json(self,naziv):
        with open(naziv, "w") as f:
            json.dump(self, f)

    def otvori_json(self,naziv):
        with open(naziv,'r') as f:
            student = json.load(f)
        return student

""" print("*** TEST datoteka ***")
isp = Ispiti()
isp.dodaj("Ante Antić", "Linearna algebra", 5)
isp.dodaj("Ante Antić", "Programiranje 1", 4)
isp.dodaj("Marija Marijić", "Linearna algebra", 4)
isp.dodaj("Marija Marijić", "Matematička analiza", 5)
isp.snimi_datoteka("ispiti.txt")
print(open("ispiti.txt").read())
isp = isp.otvori_datoteka("ispiti.txt")
print(isp) """

""" print("*** TEST json ***")
isp = Ispiti()
isp.dodaj("Ante Antic", "Linearna algebra", 5)
isp.dodaj("Ante Antic", "Programiranje 1", 4)
isp.dodaj("Marija Marijic", "Linearna algebra", 4)
isp.dodaj("Marija Marijic", "Matematicka analiza", 5)
isp.snimi_json("ispiti.json")
print(open("ispiti.json").read())
isp = isp.otvori_json("ispiti.json")
print(isp)
 """

class IspitiDB():

    def __init__(self, baza):
        self.conn = sqlite3.Connection(baza)
        self.cur = self.conn.cursor()

        self.cur.executescript("""
            DROP TABLE IF EXISTS ispiti;
            DROP TABLE IF EXISTS kolegiji;
            DROP TABLE IF EXISTS studenti;

            CREATE TABLE studenti (
            student_id integer PRIMARY KEY,
            ime_prezime text NOT NULL UNIQUE);

            CREATE TABLE kolegiji (
            kolegij_id integer PRIMARY KEY,
            naziv text NOT NULL UNIQUE);

            CREATE TABLE ispiti (
            student_id integer,
            kolegij_id integer,
            ocjena integer NOT NULL,
            PRIMARY KEY (student_id, kolegij_id),
            FOREIGN KEY (student_id) REFERENCES studenti (student_id),
            FOREIGN KEY (kolegij_id) REFERENCES kolegij (kolegij_id));
            """)

    def vrati_kolegij_id(self, naziv):
        self.cur.execute("""SELECT kolegij_id FROM kolegiji WHERE naziv = ?""", (naziv,))
        row = self.cur.fetchone()
        if row:
            return row[0]

    def dodaj_kolegij(self, naziv):
        self.cur.execute("""INSERT INTO kolegiji (naziv) VALUES (?)""", (naziv, ))
        self.conn.commit()
        return self.cur.lastrowid

    def vrati_student_id(self, ime_prezime):
        self.cur.execute("""SELECT student_id FROM studenti WHERE ime_prezime = ?""", (ime_prezime,))
        row = self.cur.fetchone()
        if row:
            return row[0]

    def dodaj_student(self,ime_prezime):
        self.cur.execute("""INSERT INTO studenti (ime_prezime) VALUES (?)""", (ime_prezime, ))
        self.conn.commit()
        return self.cur.lastrowid

    def promijeni_student(self, ime_prezime, novo_ime_prezime):
        self.cur.execute("""SELECT ime_prezime FROM studenti WHERE ime_prezime = ?""", (ime_prezime,))
        row = self.cur.fetchone()
        if row:
            self.cur.execute("UPDATE studenti SET ime_prezime = ? WHERE ime_prezime = ?", (novo_ime_prezime, ime_prezime))
            self.conn.commit()
        else:
            return None

    def izbrisi_student(self,ime_prezime):
        self.cur.execute("DELETE FROM studenti WHERE ime_prezime = ?", (ime_prezime, ))
        self.conn.commit()

    def ispitaj(self,student,kolegij,ocjena = None):

        student_id = None
        kolegij_id = None

        self.cur.execute("""SELECT student_id FROM studenti WHERE ime_prezime = ?""", (student,))
        id_s = self.cur.fetchone()
        if id_s:
            student_id = id_s[0]
        else:
            self.cur.execute("INSERT INTO studenti (ime_prezime) VALUES (?) ", (student, ))
            self.conn.commit()
            self.cur.execute("""SELECT student_id FROM studenti WHERE ime_prezime = ?""", (student,))
            id_s = self.cur.fetchone()
            student_id = id_s[0]

        self.cur.execute("""SELECT kolegij_id FROM kolegiji WHERE naziv = ?""", (kolegij,))
        id_k = self.cur.fetchone()
        if id_k:
            kolegij_id = id_k[0]
        else:
            self.cur.execute("INSERT INTO kolegiji (naziv) VALUES (?) ", (kolegij, ))
            self.conn.commit()
            self.cur.execute("""SELECT kolegij_id FROM kolegiji WHERE naziv = ?""", (kolegij,))
            id_k = self.cur.fetchone()
            kolegij_id = id_k[0]

        if student_id and kolegij_id:

            if ocjena:
                self.cur.execute("""SELECT ocjena FROM ispiti WHERE student_id = ? and kolegij_id =? """, (student_id,kolegij_id))
                testOcjena = self.cur.fetchone()

                if testOcjena:
                    self.cur.execute("UPDATE ispiti SET ocjena = ? WHERE student_id = ? AND kolegij_id = ?", (ocjena, student_id,kolegij_id))
                    self.conn.commit()

                else:
                    self.cur.execute("INSERT INTO ispiti (ocjena, student_id,kolegij_id) VALUES (?,?,?)", (ocjena, student_id,kolegij_id))
                    self.conn.commit()

            else:
                self.cur.execute("DELETE FROM ispiti WHERE student_id = ? AND kolegij_id = ?" , (student_id, kolegij_id ))
                self.conn.commit()

    def svi_ispiti(self):
        self.cur.execute("""
        SELECT studenti.ime_prezime, kolegiji.naziv, ispiti.ocjena
        FROM studenti
        JOIN ispiti ON studenti.student_id = ispiti.student_id
        JOIN kolegiji ON ispiti.kolegij_id = kolegiji.kolegij_id
        """)
        rows = self.cur.fetchall()

        return json.dumps(rows)

""" print('*** TEST SQLite studenti ***')
db = IspitiDB("ispiti.sqlite")
print(db.cur.execute("SELECT * FROM studenti").fetchall())
db.dodaj_student("Ante Antić")
db.dodaj_student("Ana Anić")
db.dodaj_student("Pero Perić")
print(db.cur.execute("SELECT * FROM studenti").fetchall())
print(db.vrati_student_id("Pero Perić"))
print(db.vrati_student_id("Marija Marijić"))
db.izbrisi_student("Pero Perić")
db.promijeni_student("Ana Anić", "Marija Marijić")
print(db.cur.execute("SELECT * FROM studenti").fetchall()) """

print('*** TEST SQLite ispiti ***')
db = IspitiDB("ispiti.sqlite")
db.dodaj_student("Ante Antic")
db.dodaj_student("Marija Marijic")
db.dodaj_kolegij("Linearna algebra")
db.ispitaj("Ante Antic", "Linearna algebra", 5)
print(db.svi_ispiti())
db.ispitaj("Ante Antic", "Linearna algebra", 4)
print(db.svi_ispiti())
db.ispitaj("Ante Antic", "Linearna algebra")
print(db.svi_ispiti())
db.ispitaj("Ante Antic", "Linearna algebra", 5)
db.ispitaj("Marija Marijic", "Programiranje 1", 5)
db.ispitaj("Marija Marijic", "Matematicka analiza", 4)
print(db.svi_ispiti())


import random

capacity = 50
mutation_rate = 0.1
weights = (10,20,30)
values = (60,100,120)

size = len(weights)

population_size = 200
no_generations = 100

#DNA **********************************************************************************************

class DNA:

    genes = []
    weight = 0
    value = 0

    def __init__(self):
        self.genes = [random.randint(0,1) for i in range(size)]

    def calculate_fitness(self):
        for i in range(size):
            self.weight += self.genes[i]*weights[i]
            self.value += self.genes[i]*values[i]

    def get_dna(self):
        resultado = ""
        for i in range(size):
            resultado += str(self.genes[i])
        resultado = resultado + ". v:{0}, w:{1}".format(self.value, self.weight)
        return resultado

    def crossover(self, mother):
        child = DNA()

        #Pick a midpoint
        midpoint = random.randrange(size)
        for i in range(size):
            #Father half
            if i < midpoint:
                child.genes[i] = self.genes[i]
            #Mother half
            else:
                child.genes[i] = mother.genes[i]

        return child

    def mutate(self):
        for i in range(size):
            if random.random() < mutation_rate:
                self.genes[i] = random.randint(0,1)

#POPULATION ***************************************************************************************

class Population:

    population = []
    mating_pool = []
    generations = 0
    best = None

    def __init__(self):
        for _ in range(population_size):
            dna = DNA()
            dna.calculate_fitness()
            self.population.append(dna)

    def natural_selection(self):
        self.mating_pool = []

        #Number of DNAs whose capacity is lower or equal than knapsack capacity.
        good_adns = 0
        #The greatest value among the population.
        best_value = 0
        #The position of the best DNA.
        best_position = 0

        #Checking the DNAs whose weight is greater than capacity; their value will be changed to -1
        #in order to avoid them being picked for the next generation.
        for i in range(population_size):
            if (self.population[i].weight > capacity):
                self.population[i].value = -1
            else:
                good_adns += 1
                if (self.population[i].value > best_value):
                    best_value, best_position = self.population[i].value, i

        #print("Good ADNs: {0}".format(good_adns))

        #Adding in the mating pool the elements based on their value.
        #remainder: number of times the best element is going to be added.
        #quotient: number of times each 'good' element is gonna be added.
        remainder = population_size%good_adns
        quotient = population_size//good_adns

        for i in range(population_size):
            if (self.population[i].value >= 0):
                for _ in range(quotient):
                    self.mating_pool.append(self.population[i])

        for i in range(remainder):
            self.mating_pool.append(self.population[best_position])

        #print("BEST DNA: {0}".format(self.population[best_position].get_dna()))
        #print("BEST VALUE: {0}".format(self.population[best_position].value))
        #print("BEST WEIGHT: {0}".format(self.population[best_position].weight))

        random.shuffle(self.mating_pool)

    def new_generation(self):
        #Refill the population with children from the mating pool.
        for i in range(population_size):
            #Random indexes to select members from the mating pool.
            a = int(random.randrange(population_size))
            b = int(random.randrange(population_size))

            #Choosing parents
            father = self.mating_pool[a]
            mother = self.mating_pool[b]

            child = father.crossover(mother)
            child.mutate()
            child.calculate_fitness()

            self.population[i] = child

        self.generations += 1

    def get_best(self):
        return self.best

    #Compute the current 'most fit' member of the population.
    def evaluate(self):
        world_record = self.population[0].value
        index = 0

        for i in range(population_size):
            if (self.population[i].value > world_record):
                index = i
                world_record = self.population[i].value

        self.best = self.population[index].get_dna()

    def get_generations(self):
        return self.generations

#MAIN *********************************************************************************************
if __name__ == "__main__":

    pop = Population()

    for i in range(no_generations):

        #Generate mating pool
        pop.natural_selection()

        #Get the best DNA
        pop.evaluate()

        #Create next generation
        pop.new_generation()

    print("Best: {0}".format(pop.get_best()))
    print("Generations: {0}".format(pop.generations))


from os.path import dirname, abspath
d = dirname(abspath(__file__))

Coin = d + "/Art/Coin.gif"
XP = d + "/Art/XP.gif"
HP = d + "/Art/HP.gif"
AP = d + "/Art/AP.gif"

Items = d + "/Art/Items/{}.gif"
Food= d + "/Art/Items/Food/{}.gif"
HeadArmors = d + "/Art/Items/Armor/HeadArmor/{}.gif"
TorsoArmors = d + "/Art/Items/Armor/TorsoArmor/{}.gif"
LegArmors = d + "/Art/Items/Armor/LegArmor/{}.gif"

Battlestaff = d+"/Art/Items/Weapons/BattleStaffs/{}BattleStaff.gif"
Bow = d+"/Art/Items/Weapons/Bows/{}Bow.gif"
Dagger = d+"/Art/Items/Weapons/Daggers/{}Dagger.gif"
Hammer = d+"/Art/Items/Weapons/Hammers/{}Hammer.gif"
Staff = d+"/Art/Items/Weapons/Staffs/{}Staff.gif"
Sword = d+"/Art/Items/Weapons/Swords/{}Sword.gif"
Wand = d+"/Art/Items/Weapons/Wands/{}Wand.gif"

Item = Items.format("Empty")
HeadArmor = HeadArmors.format("EmptyHelmet")
TorsoArmor = TorsoArmors.format("EmptyTorso")
LegArmor = LegArmors.format("EmptyPants")
Weapon = d + "/Art/Items/Weapons/Fist.gif"

#START FOOD
Apple = Food.format("Apple")
Berries = Food.format("Berries")
FrogLeg = Food.format("FrogLeg")
HealthPotion = Food.format("HealthPotion")
JarOfJam = Food.format("JarOfJam")
JarOfWater = Food.format("JarOfWater")
LoafOfBread = Food.format("LoafOfBread")
Pheasant = Food.format("Pheasant")
Potato = Food.format("Potato")
Rabbit = Food.format("Rabbit")
SweetRoll = Food.format("SweetRoll")
#END FOOD

#START BATTLESTAFFS
BirchBattleStaff = Battlestaff.format("Birch")
DogwoodBattleStaff = Battlestaff.format("Dogwood")
ElderBattleStaff = Battlestaff.format("Elder")
HemlockBattleStaff = Battlestaff.format("Hemlock")
OakBattleStaff = Battlestaff.format("Oak")
SycamoreBattleStaff = Battlestaff.format("Sycamore")
WalnutBattleStaff = Battlestaff.format("Walnut")
#END BATTLESTAFFS

#START BOWS
MagicBow = Bow.format("Magic")
MapleBow = Bow.format("Maple")
OakBow = Bow.format("Oak")
WillowBow = Bow.format("Willow")
YewBow = Bow.format("Yew")
#END BOWS

#START DAGGERS
AdamantineDagger = Dagger.format("Adamantine")
BronzeDagger = Dagger.format("Bronze")
PlatinumDagger = Dagger.format("Platinum")
SteelDagger = Dagger.format("Steel")
StoneDagger = Dagger.format("Stone")
VibraniumDagger = Dagger.format("Vibranium")
WoodenDagger = Dagger.format("Wooden")
#END DAGGERS

#START HAMMERS
AdamantineHammer = Hammer.format("Adamantine")
BronzeHammer = Hammer.format("Bronze")
PlatinumHammer = Hammer.format("Platinum")
SteelHammer = Hammer.format("Steel")
StoneHammer = Hammer.format("Stone")
VibraniumHammer = Hammer.format("Vibranium")
WoodenHammer = Hammer.format("Wooden")
#END HAMMERS

#START STAFFS
BirchStaff = Staff.format("Birch")
DogwoodStaff = Staff.format("Dogwood")
ElderStaff = Staff.format("Elder")
HemlockStaff = Staff.format("Hemlock")
OakStaff = Staff.format("Oak")
SycamoreStaff = Staff.format("Sycamore")
WalnutStaff = Staff.format("Walnut")
#END STAFFS

#START SWORDS
AdamantineSword = Sword.format("Adamantine")
BronzeSword = Sword.format("Bronze")
PlatinumSword = Sword.format("Platinum")
SteelSword = Sword.format("Steel")
StoneSword = Sword.format("Stone")
VibraniumSword = Sword.format("Vibranium")
WoodenSword = Sword.format("Wooden")
#END SWORDS

#START WANDS
BirchWand = Wand.format("Birch")
DogwoodWand = Wand.format("Dogwood")
ElderWand = Wand.format("Elder")
HemlockWand = Wand.format("Hemlock")
OakWand = Wand.format("Oak")
SycamoreWand = Wand.format("Sycamore")
WalnutWand = Wand.format("Walnut")
#END WANDS

#START HEAD AROMR
AdamantineHelmet = HeadArmors.format("AdamantineHelmet")
BronzeHelmet = HeadArmors.format("BronzeHelmet")
IronHelmet = HeadArmors.format("IronHelmet")
PlatinumHelmet = HeadArmors.format("PlatinumHelmet")
SteelHelmet = HeadArmors.format("SteelHelmet")
VibraniumHelmet = HeadArmors.format("VibraniumHelmet")

ApprenticeHood = HeadArmors.format("ApprenticeHood")
BeginnerHood = HeadArmors.format("BeginnerHood")
MasterHood = HeadArmors.format("MasterHood")
NoviceHood = HeadArmors.format("NoviceHood")
WizardHood = HeadArmors.format("WizardHood")

CloakingCap = HeadArmors.format("CloakingCap")
HeavyLeatherCap = HeadArmors.format("HeavyLeatherCap")
LightLeatherCap = HeadArmors.format("LightLeatherCap")
SnakeSkinCap = HeadArmors.format("SnakeSkinCap")
StuddedLeatherCap = HeadArmors.format("StuddedLeatherCap")
WolfFurCap = HeadArmors.format("WolfFurCap")
#END HEAD ARMOR

#START TORSO ARMOR
AdamantineTorso = TorsoArmors.format("AdamantineTorso")
BronzeTorso = TorsoArmors.format("BronzeTorso")
IronTorso = TorsoArmors.format("IronTorso")
PlatinumTorso = TorsoArmors.format("PlatinumTorso")
SteelTorso = TorsoArmors.format("SteelTorso")
VibraniumTorso = TorsoArmors.format("VibraniumTorso")

CloakingShirt = TorsoArmors.format("CloakingShirt")
HeavyLeatherShirt = TorsoArmors.format("HeavyLeatherShirt")
LightLeatherShirt = TorsoArmors.format("LightLeatherShirt")
SnakeSkinShirt = TorsoArmors.format("SnakeSkinShirt")
StuddedLeatherShirt = TorsoArmors.format("StuddedLeatherShirt")
WolfFurShirt = TorsoArmors.format("WolfFurShirt")

ApprenticeRobe = TorsoArmors.format("ApprenticeRobe")
BeginnerRobe = TorsoArmors.format("BeginnerRobe")
MasterRobe = TorsoArmors.format("MasterRobe")
NoviceRobe = TorsoArmors.format("NoviceRobe")
WizardRobe = TorsoArmors.format("WizardRobe")
#END TORSO ARMOR

#START LEG ARMOR
AdamantinePants = LegArmors.format("AdamantinePants")
BronzePants = LegArmors.format("BronzePants")
IronPants = LegArmors.format("IronPants")
PlatinumPants = LegArmors.format("PlatinumPants")
SteelPants = LegArmors.format("SteelPants")
VibraniumPants = LegArmors.format("VibraniumPants")

CloakingPants = LegArmors.format("CloakingPants")
HeavyLeatherPants = LegArmors.format("HeavyLeatherPants")
LightLeatherPants = LegArmors.format("LightLeatherPants")
SnakeSkinPants = LegArmors.format("SnakeSkinPants")
StuddedLeatherPants = LegArmors.format("StuddedLeatherPants")
WolfFurPants = LegArmors.format("WolfFurPants")

ApprenticePants = LegArmors.format("ApprenticePants")
BeginnerPants = LegArmors.format("BeginnerPants")
MasterPants = LegArmors.format("MasterPants")
NovicePants = LegArmors.format("NovicePants")
WizardPants = LegArmors.format("WizardPants")
#END LEG ARMOR


from torch import nn
import torch
import numpy as np
from util.cv import right_distribute
from data_process import radar_data
# from data_process import feature_extractor as road_data
import os

SEQ_LEN = 64

def model_test(model_path):
    print('test')
    model = torch.load(model_path)
    # input_data, label_data = radar_data.load_pg_test_data()
    _, _1,input_data, label_data = radar_data.load_pg_data_by_range(0, SEQ_LEN)
    # _, _1, input_data, label_data = radar_data.load_road_data()
    input_data = radar_data.reduce_data_length(input_data, 0, SEQ_LEN)
    label_data = radar_data.reduce_data_length(label_data, 0, SEQ_LEN)
    # L = len(input_data)

    correct_num = 0
    relative_correct_num = 0
    total_num = len(input_data)
    sca = np.zeros(SEQ_LEN)
    sca_r = np.zeros(SEQ_LEN)
    data_sca = np.zeros(SEQ_LEN)
    right_location_num = 0
    zero_num = 0
    for step in range(len(input_data)):
        print(step, '------------------------------------------------------------>')
        x = input_data[step:(step + 1)]
        y = label_data[step:(step + 1)]
        max_y_index = 0
        # 求y的最大值下标
        for i in range(len(y[0])):
            if y[0][i] >= y[0][max_y_index]:
                max_y_index = i

        # if not (max_y_index >= 18 and max_y_index <= 22):  # 去掉低的情况
        #     total_num = total_num - 1
        #     continue

        data_sca[max_y_index] = data_sca[max_y_index] + 1
        x = np.array(x).reshape(1, SEQ_LEN, 1)
        y = np.array(y).reshape(1, SEQ_LEN, 1)
        x = torch.FloatTensor(x).cuda(0)
        y = torch.ByteTensor(y).cuda(0)
        prediction, _ = model(x, None)

        predict = torch.sigmoid(prediction) > 0.08
        max_predict_index = 0
        mm = 0
        for i in range(1, len(predict.view(-1))):
            if predict.view(-1)[i] > mm:
                max_predict_index = i
                mm = predict.view(-1)[i]

        if max_predict_index == 0:
            zero_num = zero_num + 1

        t = label_data[step:(step + 1)]
        # t=
        t = np.array(t[0]).tolist()
        pd = predict.view(-1).data.cpu().numpy()
        pd = np.array(pd).tolist()
        result = torch.eq(y, predict)
        res= result.view(-1).data.cpu().numpy()
        res=np.array(res).tolist()
        print('target:    ', t)
        print('predict:   ', pd)
        print('difference:', res)

        #
        # if (abs(max_y_index - max_predict_index) < 3):
        #     print('step: ', step)
        #     # sca_r[max_y_index] = sca_r[max_y_index] + 1
        #     relative_correct_num = relative_correct_num + 1

        # 在某个点上有物体完全预测正确
        # if t[0][max_y_index] == pd[max_y_index]:
        #     right_location_num = right_location_num+1

        # 在某个位置前后偏离两个位置
        if max_y_index >= 2 and max_y_index <= 62:
            if t[max_y_index] == pd[max_y_index] or t[max_y_index] == pd[max_y_index - 1] \
                    or t[max_y_index] == pd[max_y_index + 1] \
                    or t[max_y_index] == pd[max_y_index + 2] \
                    or t[max_y_index] == pd[max_y_index - 2] \
                    or t[max_y_index] == pd[max_y_index - 1]:
                print('relative right')
                right_location_num = right_location_num + 1
                sca_r[max_y_index] = sca_r[max_y_index] + 1
        else:
            if t[max_y_index] == pd[max_y_index]:
                right_location_num = right_location_num + 1
                sca_r[max_y_index] = sca_r[max_y_index] + 1

        accuracy = torch.sum(result) / torch.sum(torch.ones(y.shape))
        accuracy = accuracy.data.cpu().numpy()
        correct = torch.eq(torch.sum(~result), 0)
        print('accuracy: ', accuracy)
        print('correct: {}'.format(correct))
        if correct == 1:
            # right_index = int(max_y_index/10)
            sca[max_y_index] = sca[max_y_index] + 1
            correct_num = correct_num + 1
        print('<------------------------------------------------------------------\n')

    print('total:', (step + 1), ' | correct_num:', correct_num, '| complete_correct_rate:', correct_num / total_num,
          # '| relative_correct_num : ', relative_correct_num, '| relative_correct_rate: ',
          # relative_correct_num / total_num,
          ' |right_location_rate: ', right_location_num / total_num,
          ' |zero_num:', zero_num,
          ' |zero_num_rate: ', zero_num / total_num)
    print('sca : ', sca)
    print('sca_r: ', sca_r)
    print('data_sca:', data_sca)

    right_distribute.distribute_cv(sca, data_sca, SEQ_LEN)
    right_distribute.distribute_cv(sca_r, data_sca, SEQ_LEN)

if __name__ == '__main__':
    model_location = 'D:\home\zeewei\projects\\77GRadar\model\\rnn\model_save_dir\\rnn2-32-4-0'
    model_path = os.path.join(model_location, 'rnn_loss2_9990_270.pkl')
    model_test(model_path)


import qutip as qt
import numpy as np
import benchmarkutils

name = "wigner_state"

samples = 3
evals = 5
cutoffs = range(10, 101, 10)

def setup(N):
    alpha = 0.7
    xvec = np.linspace(-50, 50, 100)
    yvec = np.linspace(-50, 50, 100)
    state = qt.coherent(N, alpha)
    return state, xvec, yvec

def f(state, xvec, yvec):
    return qt.wigner(state, xvec, yvec)

print("Benchmarking:", name)
print("Cutoff: ", end="", flush=True)
checks = {}
results = []
for N in cutoffs:
    print(N, "", end="", flush=True)
    state, xvec, yvec = setup(N)
    alpha_check = 0.6 + 0.1j
    checks[N] = f(state, [alpha_check.real], [alpha_check.imag])[0, 0]
    t = benchmarkutils.run_benchmark(f, state, xvec, yvec, samples=samples, evals=evals)
    results.append({"N": N, "t": t})
print()

benchmarkutils.check(name, checks)
benchmarkutils.save(name, results)


import json
import pandas as pd
import logging

from aggregator.schemas import RapidapiResponse
from aggregator.matcher import CountryNameMatcher

class RapidapiDataPreparer:

    @classmethod
    def prepare(
        cls,
        data: str,
        matcher: CountryNameMatcher
    ) -> pd.DataFrame:

        data: pd.DataFrame = cls._json_to_dataframe(data)
        data = cls._unwrap_columns(data)
        data = cls._choose_columns(data)
        data = cls._convert_types(data)
        data = cls._set_country_keys_and_names(data, matcher)
        data = cls._remove_non_countries(data)
        data = cls._sort_and_enumerate(data)
        cls._check_new_countries(data, matcher)
        return data

    @staticmethod
    def _json_to_dataframe(data: str) -> pd.DataFrame:
        data: RapidapiResponse = json.loads(data)
        data = data['response']
        data = pd.DataFrame(data)
        return data

    @classmethod
    def _unwrap_columns(cls, data) -> pd.DataFrame:
        for colname in ('cases', 'deaths'):
            data = cls._unwrap_one_column(data, colname)
        return data

    @staticmethod
    def _unwrap_one_column(data, colname: str) -> pd.DataFrame:
        data = data.copy()
        unwrapped_data = pd.DataFrame(list(data[colname]))
        unwrapped_data.columns = [
            name + '_' + colname
            for name in unwrapped_data.columns
        ]
        data = data.join(unwrapped_data)
        del(data[colname])
        return data

    @staticmethod
    def _choose_columns(data) -> pd.DataFrame:
        columns = [
            'country', 'total_cases', 'new_cases',
            'recovered_cases', 'total_deaths', 'new_deaths']
        data = data[data.columns.intersection(columns)]
        return data

    @staticmethod
    def _convert_types(data) -> pd.DataFrame:
        data = data.copy()
        data.total_cases = data.total_cases.astype(object)
        data.recovered_cases = data.recovered_cases.astype(object)
        data.total_deaths = data.total_deaths.astype(object)
        return data

    @staticmethod
    def _set_country_keys_and_names(data, matcher) -> pd.DataFrame:
        data = data.copy()
        data['key'] = data.country.str.lower()
        del data['country']
        data.key = data.key.str.replace(r'[\.\-\&\;]', '')
        data.key = data.key.map(matcher.name_to_key())
        data = data.drop_duplicates(subset=['key'])
        data['name'] = data.key.map(matcher.key_to_name())
        return data

    @staticmethod
    def _remove_non_countries(data) -> pd.DataFrame:
        exceptions = [
            'europe', 'northamerica', 'asia',
            'southamerica', 'africa', 'oceania',
            ''
        ]
        data = data.where(~data.key.isin(exceptions))
        data = data.dropna(subset=['key'])
        return data

    @staticmethod
    def _sort_and_enumerate(data) -> pd.DataFrame:
        data = data.sort_values('total_cases', ascending=False)
        data = data.reset_index(drop=True)
        data['number'] = list(range(len(data)))
        data['type'] = ['country'] * len(data)
        return data

    @staticmethod
    def _check_new_countries(data, matcher) -> None:
        new_countries = set(data.key)
        old_countries = matcher.keys()
        difference = new_countries - old_countries
        if len(difference) > 0:
            logging.warning(
                f' New countries: {str(difference)}')


from django import forms
from .models import Topic

class NewTopicForm(forms.ModelForm):
	message = forms.CharField(
		widget=forms.Textarea
		(attrs={'rows':5, 'placeholder':"What's in your mind?"}),
		max_length=4000, help_text= 'The maximum length of words is 5000')

	class Meta:
		model = Topic
		fields = ['subject', 'message']


# Merging the the algorithm test code with the multi-threading code
#
# Author: Daniel de Gouw
# Date: 9/4/19
import threading
import PID
import time
import cv2, os
import cv2.aruco as aruco
import numpy as np
from pyparrot.Minidrone import Mambo
from subprocess import Popen, PIPE

# Set to true if testing with the Mambo
mambo_connected = True

# Set this to true if you want to fly for the demo
testFlying = False

# Debug Options
debug_controller = False
debug_draw_frame = True
debug_frame_output = True

#Other
drone_image = None
count = 0
keep_running=True

initialisation = True

controller_state = 0
angle_tracker = 0

# Normally these would be loaded from an external source.
camera_matrix = np.array([[  1.10203699e+03,   0.00000000e+00,   2.97856040e+02],
                          [  0.00000000e+00,   1.10715227e+03,   2.19618658e+02],
                          [  0.00000000e+00,   0.00000000e+00,   1.00000000e+00]])
distortion_coeff = np.array([7.978574896538845329e-02, 3.400042995004967317e+00, -1.786514214937548820e-02,
                            -3.217060871280347668e-03, -2.063856972981825777e+01])

class image_thread(threading.Thread):
    # Class for running the second thread
    def __init__(self):

        threading.Thread.__init__(self)

    def run(self):
        # Continuosly runs, obtaining frames from the stream
        global drone_image,count,keep_running
        # 'ffmpeg -i  rtsp://192.168.99.1/media/stream2 -async 1 -vsync 1 -vcodec rawvideo -pix_fmt rgb24 -f rawvideo -'
        cmd = 'ffmpeg -i  rtsp://192.168.99.1/media/stream2 -framerate 30 -vcodec rawvideo -pix_fmt rgb24 -f rawvideo -'
        p1 = Popen(cmd, stdout=PIPE, shell=True)
        fd = p1.stdout
        sx,sy=640,360
        while keep_running:
            # Reads the fram at a certain size
            s = fd.read(sx * sy * 3)
            drone_image = np.fromstring(s,dtype='uint8').reshape((sy,sx,3))
            #count = count + 1

def convert_image():
    # Copying the frame so that they are same for both conversions
    frame = drone_image

    # Converting the frame
    gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

    return frame, gray

def detect_markers(frame, gray):
    corners, ids, rejected = aruco.detectMarkers(gray, dictionary)  # Attempt to detect markers in the frame.

    # Marker detected
    if ids is not None:  # We have detected some markers.
        # Estimate the pose of the detected markers (assumes marker is 16cm wide).
        # Note: half the width gives correct distances...
        poses = aruco.estimatePoseSingleMarkers(corners, 0.05, camera_matrix, distortion_coeff)
        rvec, tvec = poses[0:2]
        frame = aruco.drawDetectedMarkers(frame, corners, ids)  # Draw the detected markers onto the frame.
        # Draw the estimated position for the detected markers and print the details in the terminal.
        for i in range(len(ids)):
            x, y, z = np.squeeze(tvec[i])
            rx, ry, rz = rotation_vector_to_euler(np.squeeze(rvec[i]))
            # Draw a 3D axis for each marker position.
            frame = aruco.drawAxis(frame, camera_matrix, distortion_coeff, rvec[i], tvec[i], 0.035)

            #print("ID: {}\n\tTranslation Vector: x: {:6.3f}m, y: {:6.3f}m, z: {:6.3f}m\n\t".format(ids[i], x, y, z))
            #print("ID: {}\n\tTranslation Vector: x: {:6.3f}m, y: {:6.3f}m, z: {:6.3f}m\n\t \
            #\Rotation Vector: rx: {:6.2f}deg, ry: {:6.2f}deg, rz: {:6.2f}deg".format(ids[i], x, y, z, rx, ry, rz))

        detected = True
        co_ords = (x, y, z, ry)

    # No Marker detected
    else:
        # Ensure the variables are reset
        co_ords = (0, 0, 0, 0)
        detected = False

    return frame, co_ords, detected

def rotation_vector_to_euler(rotation_vector):
    # Convert an OpenCV-style rotation vector into Euler angles in degrees.
    rotation_matrix, _ = cv2.Rodrigues(rotation_vector)
    euler_angles, _, _, _, _, _ = cv2.RQDecomp3x3(rotation_matrix)
    return euler_angles

def debug_frame(frame, state):
    w = 640
    h = 360
    # Draw axis for center point
    frame = cv2.line(frame, (0,int(h/2)), (w,int(h/2)), (0,255,0), 1)
    frame = cv2.line(frame, (int(w/2),0), (int(w/2),h), (0,255,0), 1)

    if state >= 0 and state < 5:
        cv2.putText(frame, "No Marker Detected", (10,20), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    else:
        cv2.putText(frame, "Marker Detected", (10,20), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)

    if state >= 10 and state < 20:
        cv2.putText(frame, "Centered", (10,50), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    elif state == 6:
        cv2.putText(frame, "Turn Right", (10,50), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    elif state == 7:
        cv2.putText(frame, "Turn Left", (10,50), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)

    if state >= 15 and state < 20:
        cv2.putText(frame, "Aprox. 1m away", (10,80), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    elif state == 11:
        cv2.putText(frame, "Moving Forward", (10,80), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    elif state == 12:
        cv2.putText(frame, "Moving Backwards", (10,80), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)

    if state == 16:
        cv2.putText(frame, "Spinning Right", (10,110), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    elif state == 17:
        cv2.putText(frame, "Spinning Left", (10,110), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)
    elif state == 19:
        cv2.putText(frame, "Square on", (10,110), cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0,255,0), 1)

    return frame

def debug_controller_state(controller_state):
    # Prints an output of what state the tracking algorithm is in
    print("State: %2f \n" % controller_state)

    if controller_state >= 0 and controller_state < 5:
        print("Detecting state \n")
        if controller_state == 1:
            print("Spinning around to the left 10 deg/loop")
        elif controller_state == 2:
            print("Marker lost - Attempting to find it again ")
        elif controller_state == 4:
            print("Landing - No marker found")

    elif controller_state >= 5 and controller_state < 10:
        print("Aligning state \n")
        if controller_state == 9:
            print("Alignment lost in another state - Realigning")
        elif controller_state == 6:
            print("Turning Right")
        elif controller_state == 7:
            print("Turning Left")

    elif controller_state >= 10 and controller_state < 15:
        print("Adjusting State \n")
        if controller_state == 11:
            print("Moving forward")
        elif controller_state == 12:
            print("Moving backward")

    print("\n") # spacer

def controller_fsm(controller_state, detected, distance, t_angle, r_angle, angle_count):
    # yaw - Y axis
    # pitch - X axis
    # roll - Z axis

    # Tracking algorithm for ensuring the Fiducial markers are centred, within a
    # certain distance (1 metre) and at a certain orientation (0 degrees)

    # Spins around till a marker is found
    if controller_state >= 0 and controller_state < 5:
        if detected == True:
            # Do nothing
            controller_state = 5
            angle_count = 0
        elif angle_count == 360:
            # Land
            mambo.smart_sleep(1)
            controller_state = 4
        else:
            angle_count = angle_count + 10
            # Rotate the drone left
            mambo.fly_direct(roll=0, pitch=0, yaw=40, vertical_movement=0, duration=0.1)
            mambo.smart_sleep(0.5)

    # Centres the marker within the frame
    elif controller_state >= 5 and controller_state < 10:
        if detected == False:
            # Do nothing
            mambo.smart_sleep(1)
            pid_centring.update(pid_centring.SetPoint)
            pid_centring.ITerm = 0.0
            controller_state = 2
        elif t_angle > lowAngleLim and t_angle < upperAngleLim:
            # Do nothing
            mambo.smart_sleep(1)
            pid_centring.update(pid_centring.SetPoint)
            pid_centring.ITerm = 0.0
            controller_state = 10
        elif t_angle > upperAngleLim:
            # Right
            if controller_state == 7:
                pid_centring.ITerm = 0.0
            pid_centring.update(-t_angle)
            mambo.fly_direct(roll=0, pitch=0, yaw=pid_centring.output, vertical_movement=0, duration=0.5)
            mambo.smart_sleep(0.3)
            controller_state = 6
        elif t_angle < lowAngleLim:
            # Left
            if controller_state == 6:
                pid_centring.ITerm = 0.0
            pid_centring.update(-t_angle)
            mambo.fly_direct(roll=0, pitch=0, yaw=pid_centring.output, vertical_movement=0, duration=0.5)
            mambo.smart_sleep(0.3)
            controller_state = 7

    # Postions the drone so that the marker is approximately 1 metre away
    elif controller_state >= 10 and controller_state < 15:
        if detected == False:
            # Do nothing
            mambo.smart_sleep(1)
            pid_distance.update(pid_distance.SetPoint)
            pid_distance.ITerm = 0.0
            controller_state = 2
        elif t_angle < (lowAngleLim-2) or t_angle > (upperAngleLim+2):
            # Do nothing
            mambo.smart_sleep(1)
            pid_distance.update(pid_distance.SetPoint)
            pid_distance.ITerm = 0.0
            controller_state = 9
        elif distance > 0.9 and distance < 1.1:
            # Do nothing
            mambo.smart_sleep(1)
            pid_distance.update(pid_distance.SetPoint)
            pid_distance.ITerm = 0.0
            controller_state = 15
        elif distance > 1.1:
            # Move forward
            if controller_state == 12:
                pid_distance.ITerm = 0.0
            pid_distance.update(distance)
            if pid_distance.output < 15:
                forward = 15
            else:
                forward = -pid_distance.output
            mambo.fly_direct(roll=0, pitch=forward, yaw=0, vertical_movement=0, duration=0.4)
            mambo.smart_sleep(0.5)
            controller_state = 11
        elif distance < 0.9:
            # Move backward
            if controller_state == 11:
                pid_distance.ITerm = 0.0
                mambo.smart_sleep(1.5)
            pid_distance.update(distance)
            mambo.fly_direct(roll=0, pitch=-pid_distance.output*2, yaw=0, vertical_movement=0, duration=0.3)
            mambo.smart_sleep(0.3)
            controller_state = 12

    # Orientates the drone so that is perpendicular to the marker
    elif controller_state >= 15 and controller_state < 20:
        if detected == False:
            # Do nothing
            mambo.smart_sleep(1)
            controller_state = 2
        elif t_angle < (lowAngleLim-2) or t_angle > (upperAngleLim+2):
            # Do nothing
            mambo.smart_sleep(1)
            controller_state = 9
        elif distance < 0.6 or distance > 1.4:
            # Do nothing
            mambo.smart_sleep(1)
            controller_state = 14
        elif r_angle > -20 and r_angle < 20:
            # Do nothing
            mambo.smart_sleep(1)
            controller_state = 19
        elif r_angle < -20:
            # Spin right 25 -30
            if controller_state == 17:
                mambo.smart_sleep(1)
            mambo.fly_direct(roll=20, pitch=-10, yaw=-18, vertical_movement=0, duration=0.1) # Anti-Clockwise
            mambo.smart_sleep(0.4)
            controller_state = 16
        elif r_angle > 20:
            # Spin left
            if controller_state == 16:
                mambo.smart_sleep(1)
            mambo.fly_direct(roll=-20, pitch=-10, yaw=15, vertical_movement=0, duration=0.1) # Clockwise
            mambo.smart_sleep(0.4)
            controller_state = 17

    return controller_state, angle_count

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

if __name__ == "__main__":

    # Fiducial marker library used
    dictionary = aruco.getPredefinedDictionary(aruco.DICT_6X6_250)  # Retrieve one of the fiducial dictionaries.

    mamboAddr = "e0:14:d0:63:3d:d0"

    # PID initialisation
    pid_centring = PID.PID(5,1,1)
    pid_centring.setSampleTime(0.1)
    pid_centring.SetPoint = 1.0

    pid_distance = PID.PID(15,1,1)
    pid_distance.setSampleTime(0.1)
    pid_distance.SetPoint = 1.0

    # Anges for alignment
    lowAngleLim = -1.0
    upperAngleLim = 3.0

    # make my mambo object
    mambo = Mambo(mamboAddr, use_wifi=True)
    print("trying to connect to mambo now")
    success = mambo.connect(num_retries=3)
    print("connected: %s" % success)

    if (success):
        # get the state information
        print("sleeping")
        mambo.smart_sleep(1)
        mambo.ask_for_state_update()
        mambo.smart_sleep(1)

        # Start the vision thread
        Obtain_Image_Thread = image_thread()
        Obtain_Image_Thread.start()

        mambo.smart_sleep(5)
        print("Taking off!!")
        #mambo.safe_takeoff(5)
        mambo.smart_sleep(1)

    while True:

        if drone_image is not None:
            # Get the BGR image and grayscale image
            frame, gray = convert_image()

            # Look for Fiducial Markers and return the co-ordinates
            frame, co_ords, detected = detect_markers(frame, gray)

            # Find the angle of the Markers centre point to the centre of the screen - t_angle
            # Find the angle of the markers reference frame wrt camera reference frame - r_angle
            if not co_ords == (0, 0, 0, 0):
                t_angle = np.degrees((np.arctan((co_ords[0]/co_ords[2]))))
                r_angle = co_ords[3]
                #print("\n %f \n" % r_angle)
            else:
                # No marker detected
                t_angle = 0; # To mitigate 0 division error
                r_angle = 0; # For completeness

            print("State: %2f \n" % controller_state)
            print("Distance: %.2f\n" % co_ords[2])
            print("t_angle: %.2f\n" % t_angle)
            print("r_angle: %.2f\n" % r_angle)
            print("PID centre: %.2f \n" % pid_centring.output)
            #print("With I: %.2f \n" % pid_centring.ITerm)
            print("PID distance: %.2f \n" % pid_distance.output)
            #print("With I: %.2f \n" % pid_distance.ITerm)

            # Controller
            controller_state, angle_tracker = controller_fsm(controller_state, detected, co_ords[2], t_angle, r_angle, angle_tracker)

            # Debug the controller
            if debug_controller:
                debug_controller_state(controller_state)

            # Debug and draw on the frame
            if debug_draw_frame:
                frame = debug_frame(frame, controller_state)

            # Display the frame for de bugging
            if debug_frame_output:
                cv2.imshow('Drones View', frame)

                # Resetting the variable - we will then wait for a new frame
                drone_image=None
        #else:
            #print("No new image!! Stream error")

        # Always check forq button press or end of code
        if ((cv2.waitKey(1) & 0xFF == ord('q')) or (controller_state == 4)):
            # Stop thread on next loop
            keep_running=False
            mambo.safe_land(5)
            mambo.smart_sleep(2)
            # Break this while loop
            break

# Wait for thread to finish and close it
Obtain_Image_Thread.join()

#Close all open windows
cv2.destroyAllWindows()

# Disconnect the drone
mambo.smart_sleep(1)
print("Disconnecting from Drone")
mambo.disconnect()

Assessments/Project/Past Project(s)/Daniel De Gouw/Final Version.py


from flask import Flask
from flask import jsonify
import numpy as np
import pandas as pd
import pickle

app = Flask(__name__)

@app.route("/movie/<name>")
def hello(name):
    filename = "model/my_movie_model.pk"
    with open(filename, 'rb') as handle:
        my_movie_model = dict(pickle.load(handle))

    movie_name   = my_movie_model['movie_name']
    movie_list   = list(movie_name)
    corr_mat     = my_movie_model['corr_mat']

    try:
        movie_index  = movie_list.index(name)
        corr_movie   = corr_mat[movie_index]
        return jsonify({ "result" : list(movie_name[(corr_movie >= 0.9) & (corr_movie <= 1.0)])})
    except Exception as e:
        return jsonify({ "result" : []})


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: D:\BuildAgent\work\test/iobjectspy/ml\vision\_models\semantic_seg\_seg_models\model_builder.py
# Compiled at: 2019-12-31 04:09:04
# Size of source mod 2**32: 1731 bytes
"""
@author: YangRuijie
@license:
@contact: yangruijie@supermap.com
@software:
@file: unet_api.py
@time: 5/10/19 1:54 AM
@desc:
"""
from keras import Input
from . import Unet, ChangUNet

def build_model(width, height, depth, classes, backbone_name='vgg19', encoder_weights='imagenet', net_type='unet', freeze_encoder=False):
    """

    :param width: 输入图像宽
    :param height: 输入图像高
    :param depth: 输入图像通道数
    :param classes: 类别数量
    :param backbone_name: 主干网络 vgg19 resnet50 resnext50
    :param encoder_weights:  str imagenet
    :param net_type:  暂时只支持unet, 其他 pspnet,linknet,fpn,unetregression 随后支持
    :return: keras.model
    """
    input_tensor = Input(shape=(width, height, depth))
    input_shape = (width, height, depth)
    if net_type == 'unet':
        model = Unet(input_shape=input_shape, input_tensor=input_tensor, backbone_name=backbone_name, encoder_weights=encoder_weights,
          classes=classes)
    else:
        if net_type == 'change_unet':
            model = ChangUNet(input_shape=input_shape, input_tensor=input_tensor, backbone_name=backbone_name, encoder_weights=encoder_weights,
              classes=classes,
              freeze_encoder=freeze_encoder)
    return model


# -*- coding: utf-8 -*-
"""
Code for XML data Extraction
"""

import xml.sax

class DrawingHandler( xml.sax.ContentHandler ):
   def __init__(self):
      self.CurrentData = ""
      self.topx = ""
      self.topy = ""
      self.botx = ""
      self.boty = ""

   # Call when an element starts
   def startElement(self, tag, attributes):
      self.CurrentData = tag
      if tag == "drawing":
         print("*****Drawing*****")
         title = attributes["type"]
         print("Type:", title)

      if tag == "page":
         print("*****New Page*****")
         title = attributes["pg"]
         print("Pg.:", title)

      if tag == "tab":
         print("*****New Table*****")
         title = attributes["num"]
         print("Table No.:", title)

   # Call when an elements ends
   def endElement(self, tag):
      if self.CurrentData == "topx":
         print("TopX:", self.topx)
      elif self.CurrentData == "topy":
         print("TopY:", self.topy)
      elif self.CurrentData == "botx":
         print("BotX:", self.botx)
      elif self.CurrentData == "boty":
         print("BotY:", self.boty)
      self.CurrentData = ""

   # Call when a character is read
   def characters(self, content):
      if self.CurrentData == "topx":
         self.topx = content
      elif self.CurrentData == "topy":
         self.topy = content
      elif self.CurrentData == "botx":
         self.botx = content
      elif self.CurrentData == "boty":
         self.boty = content

if ( __name__ == "__main__"):

   # create an XMLReader
   parser = xml.sax.make_parser()
   # turn off namepsaces
   parser.setFeature(xml.sax.handler.feature_namespaces, 0)
   # override the default ContextHandler
   Handler = DrawingHandler()
   parser.setContentHandler(Handler)

   parser.parse("DrawingMaster.xml")

"""
XML structure
-------------
<drawing type="">
	<teeth num="">
		<page pg="">
			<tab num="">
				<topx>data</topx>
				<topy>data</topy>
				<botx>data</botx>
				<boty>data</boty>
			</tab>
        </page>
    </teeth>
</drawing>
"""