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

import requests
import os
import datarobot as dr
import numpy as np
import datetime
import sys
import time
import yaml
import warnings
import json
import pandas as pd
import nbconvert
warnings.filterwarnings("ignore")

class DataRobotPredictionError(Exception):
    pass

# Credentials
API_KEY = ''
USERNAME =''

#deployment
deployment_id = ''

def make_datarobot_deployment_predictions(data, deployment_id):
    """
    Make predictions on data provided using DataRobot deployment_id provided.
    See docs for details:
         https://app.datarobot.com/docs/users-guide/predictions/api/new-prediction-api.html

    Parameters
    ----------
    data : str
        Feature1,Feature2
        numeric_value,string
    deployment_id : str
        The ID of the deployment to make predictions with.

    Returns
    -------
    Response schema:
        https://app.datarobot.com/docs/users-guide/predictions/api/new-prediction-api.html#response-schema

    Raises
    ------
    DataRobotPredictionError if there are issues getting predictions from DataRobot
    """
    # Set HTTP headers. The charset should match the contents of the file.
    # You will need to put your datarobot-key (for cloud accounts)
    headers = {'Content-Type': 'text/plain; charset=UTF-8', 'datarobot-key': ''}

    url = 'https://cfds-ccm-prod.orm.datarobot.com/predApi/v1.0/deployments/{deployment_id}/'          'predictions'.format(deployment_id=deployment_id)
    # Make API request for predictions
    predictions_response = requests.post(
        url, auth=(USERNAME, API_KEY), data=data, headers=headers)
    _raise_dataroboterror_for_status(predictions_response)
    # Return a Python dict following the schema in the documentation
    return predictions_response.json()

def _raise_dataroboterror_for_status(response):
    """Raise DataRobotPredictionError if the request fails along with the response returned"""
    try:
        response.raise_for_status()
    except requests.exceptions.HTTPError:
        err_msg = '{code} Error: {msg}'.format(
            code=response.status_code, msg=response.text)
        raise DataRobotPredictionError(err_msg)

def main(filename, deployment_id):
    """
    Return an exit code on script completion or error. Codes > 0 are errors to the shell.
    Also useful as a usage demonstration of
    `make_datarobot_deployment_predictions(data, deployment_id)`
    """
    if not filename:
        print(
            'Input file is required argument. '
            'Usage: python datarobot-predict.py <input-file.csv>')
        return 1
    data = open(filename, 'rb').read()
    data_size = sys.getsizeof(data)
    if data_size >= MAX_PREDICTION_FILE_SIZE_BYTES:
        print(
            'Input file is too large: {} bytes. '
            'Max allowed size is: {} bytes.'
        ).format(data_size, MAX_PREDICTION_FILE_SIZE_BYTES)
        return 1
    try:
        predictions = make_datarobot_deployment_predictions(data, deployment_id)
    except DataRobotPredictionError as exc:
        print(exc)
        return 1
    print(predictions)
    return 0

# Make predictions on scoring data against deployment id one replacement model
#prediction dataset
data = open('../../../demo/lendingclub/lendingclubGR/driftdata.csv','rb').read()

predictions = pd.DataFrame.from_dict(make_datarobot_deployment_predictions(data, deployment_id))

#Feedback actuals

def feedback_actuals(data, deployment_id):
 	headers = {
 		'Content-Type': 'application/json',
 		'Authorization':  'Token {}'.format(API_KEY)}
 	url = 'https://app.datarobot.com/api/v2/deployments/{deployment_id}/actuals/fromJSON/'.format(
 		deployment_id=deployment_id)
 	resp = requests.post(url, data=data, headers=headers)
 	return resp

def set_association_id(deployment_id, association_id):
    headers = {
        'Content-Type': 'application/json',
        'Authorization':  'Token {}'.format(API_KEY)
    }
    url = 'https://app.datarobot.com/api/v2/modelDeployments/{deployment_id}/associationIdSettings/'.format(deployment_id=deployment_id)
    data = {'allowMissingValues': False, 'columnName': association_id}
    data = json.dumps(data)
    resp = requests.patch(url, data=data, headers=headers)
    resp.raise_for_status()
    return resp

actuals = pd.read_csv('') # actual.csv
actuals['associationId'] = actuals['member_id']
actuals['actualValue'] = actuals['actuals']

#put the df in json format
data = json.dumps({
    'data':
    actuals[['associationId', 'actualValue']].to_dict('records')
})

actual_response = feedback_actuals(data, deployment_id)


# Future
from __future__ import print_function

# warning ignore
import warnings
warnings.filterwarnings("ignore")

import argparse

from utils.fast_network_utils import get_network
from utils.fast_data_utils import get_fast_dataloader
from utils.utils import *

# fetch args
parser = argparse.ArgumentParser()

# model parameter
parser.add_argument('--dataset', default='cifar10', type=str)
parser.add_argument('--network', default='vgg', type=str)
parser.add_argument('--depth', default=16, type=int)
parser.add_argument('--base', default='adv', type=str)
parser.add_argument('--batch_size', default=256, type=float)
parser.add_argument('--gpu', default='0', type=str)

# transformer parameter
parser.add_argument('--tran_type', default='small', type=str, help='small/base')
parser.add_argument('--img_resize', default=224, type=int, help='224')
parser.add_argument('--patch_size', default=16, type=int, help='16')

# attack parameters
parser.add_argument('--eps', default=8/255, type=float)
parser.add_argument('--steps', default=30, type=int)
args = parser.parse_args()

def main_worker():

    # print configuration
    print_configuration(args, 0)

    # setting gpu id of this process
    torch.cuda.set_device(f'cuda:{args.gpu}')

    # init model
    net = get_network(network=args.network,
                      depth=args.depth,
                      dataset=args.dataset,
                      tran_type=args.tran_type,
                      img_size=args.img_resize,
                      patch_size=args.patch_size,
                      pretrain=False).cuda()
    net.eval()

    # upsampling for transformer
    upsample = True if args.network in transformer_list else False

    # init dataloader
    _, testloader, _ = get_fast_dataloader(dataset=args.dataset,
                                        train_batch_size=1,
                                        test_batch_size=args.batch_size,
                                        dist=False,
                                        upsample=upsample,
                                        shuffle=False)

    # checkpoint base tag
    base_tag = '' if args.base == 'standard' else '_' + args.base

    # setting checkpoint name
    if args.network in transformer_list:
        net_checkpoint_name = f'checkpoint/{args.base}/{args.dataset}/{args.dataset}{base_tag}_{args.network}_{args.tran_type}_patch{args.patch_size}_{args.img_resize}_best.t7'
    else:
        net_checkpoint_name = f'checkpoint/{args.base}/{args.dataset}/{args.dataset}{base_tag}_{args.network}{args.depth}_best.t7'

    rprint("This test : {}".format(net_checkpoint_name), 0)
    checkpoint = torch.load(net_checkpoint_name, map_location=torch.device(torch.cuda.current_device()))
    checkpoint_module(checkpoint['net'], net)

    # test
    test_whitebox(net, args.dataset, testloader, attack_list=['pgd'], steps=args.steps, eps=args.eps, rank=0)

if __name__ == '__main__':
    main_worker()


import requests
from pprint import pprint

SPOT_URL = 'https://api.coinbase.com/v2/prices/{}/spot'
def get_spot(pair):
   try:
      res = requests.get(SPOT_URL.format(pair))
      res = res.json()
      return res['data']['amount']
   except Exception as e:
      print("there was an error: ", e)


import time
from odoo import api, fields, models
from datetime import datetime,timedelta
from odoo.exceptions import AccessError, UserError, RedirectWarning, ValidationError, Warning

import logging
_logger = logging.getLogger(__name__)

class IssueMaterial(models.TransientModel):
    _name = 'issue.material'

    issue_material_line = fields.One2many('issue.material.line', 'material_id', 'Lines')

    @api.model
    def default_get(self, fields):
        obj = self.env['joborder.challan.receipt'].browse(self.env.context.get('active_id'))
        res = super(IssueMaterial, self).default_get(fields)
        moves = []
        res = {}
        if 'issue_material_line' in fields:
            query = "select bol.id , bol.product_id, bol.qty_remaining, bol.uom_id, bol.hsn_code, bol.unit_price,bol.tax_id from Joborder_challan_receipt_line as bol left join joborder_challan_receipt as bo on bo.id = bol.order_id where  bo.id = '" + str(obj.id) + "'"
            self.env.cr.execute(query)
            temp = self.env.cr.fetchall()
            for val1 in temp:
                if val1[2]:

                    dict2 = {}
                    dict2['material_id'] =val1[0]
                    dict2['product_id']=val1[1]
                    dict2['qty'] = val1[2]
                    dict2['uom_id']=val1[3]
                    dict2['hsn_code']=val1[4]
                    dict2['unit_price']=val1[5]
                    dict2['tax_id'] = val1[6]

                    moves.append (dict2)
            res['issue_material_line'] = [(0, 0, x) for x in moves]
        return res

    def material_issue(self):
        product_list = []
        product_list1 = []
        joborder = self.env['joborder.challan.receipt'].browse(self.env.context.get('active_id'))
        challan = self.env['joborder.challan'].create({'challan_id': joborder.id,'origin':joborder.id,
                                                       'partner_id': joborder.partner_id.id,
                                                       'date': datetime.today().strftime(
                                                           '%Y-%m-%d')})
        for val in self.issue_material_line:
            if val.select:

                self.env['challan.line'].create(
                                                {'order_id': challan.id,
                                                'product_id': val.product_id.id,
                                                 'party_challan':joborder.id,
                                                'uom_id': val.uom_id.id,
                                                'unit_price': val.unit_price,
                                                'hsn_code': val.product_id.category_id.hsn_no,
                                                'qty': val.qty,
                                                 'tax_id': val.tax_id.id})

                job_obj = self.env['joborder.challan.receipt.line'].search(
                                                            [('order_id', '=', joborder.id),
                                                             ('product_id', '=', val.product_id.id)])
                for job in job_obj:
                    job.write({'issue_qty': job.issue_qty + val.qty})
                #
                #
                # product_list = self.env['stock.quant'].search( [
                #         ('product_id', '=', val.product_id.id,),
                #         ('location_id', '=', joborder.location_id.id)])
                # if product_list:
                #     for val6 in product_list:
                #         val6.write(
                #                 {'quantity': val6.quantity - val.qty})
                # else:
                #     self.env['stock.quant'].create({'product_id': val.product_id.id,
                #                                                         'location_id': joborder.location_id.id,
                #                                                         'quantity': - val.qty,
                #                                                         'product_uom_id':val.uom_id.id
                #
                #                                                         })
                #
                # product_list1 = self.env['stock.quant'].search([
                #         ('product_id', '=', val.product_id.id,),
                #         ('location_id', '=', joborder.location_dest_id.id)])
                # if product_list1:
                #     for val7 in product_list1:
                #         val7.write(
                #                 {'quantity': val7.quantity + val.qty})
                # else:
                #     self.env['stock.quant'].create({'product_id': val.product_id.id,
                #                                                         'location_id': joborder.location_dest_id.id,
                #                                                         'quantity': val.qty,
                #                                                         'product_uom_id':val.uom_id.id
                #
                #                                                         })

        return {
                        'name': ('Challan'),
                        'type': 'ir.actions.act_window',
                        'res_model': 'joborder.challan',
                        'res_id': challan.id,
                        'view_type': 'form',
                        'view_mode': 'form',
                        'target': 'current',
                        'nodestroy': True,
                    }

class IssueMaterialLine(models.TransientModel):
    _name = 'issue.material.line'

    material_id = fields.Many2one('issue.material', 'Wizard')
    select = fields.Boolean('Select')
    product_id = fields.Many2one('my.product', 'Product')
    unit_price = fields.Float('Unit Price')
    uom_id = fields.Many2one('my.uom', 'UOM')
    qty = fields.Float('Quantity')
    hsn_code = fields.Char('Hsn Code')
    tax_id = fields.Many2one('my.tax', string='Taxes', )


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 16:20:22 2020

@author: jeffa
"""

import tkinter as tk
import time

timer = tk.Tk()

canvas1 = tk.Canvas(timer, width = 400, height = 300,  relief = 'raised')
canvas1.pack()

label1 = tk.Label(timer, text='Productivity Timer')
label1.config(font=('helvetica', 14))
canvas1.create_window(200, 25, window=label1)

label2 = tk.Label(timer, text='Enter Time in Seconds:')
label2.config(font=('helvetica', 10))
canvas1.create_window(200, 100, window=label2)

entry1 = tk.Entry (timer)
canvas1.create_window(200, 140, window=entry1)

def count_down_timer ():

    print("test")

    text1 = "Time Remaining:"
    label3 = tk.Label(timer, text= text1,font=('helvetica', 10))
    canvas1.create_window(200, 210, window=label3)

    # for time_remaining in range(int(time_seconds), 0, -1):
    #     print(time_remaining)
    #     label4 = tk.Label(timer, text= str(time_remaining),font=('helvetica', 10, 'bold'))
    #     canvas1.create_window(200, 230, window=label4)
    #     time.sleep(1)

button1 = tk.Button(text='Start Timer', command=count_down_timer, bg='brown', \
                    fg='white', font=('helvetica', 9, 'bold'))
time_seconds = entry1.get()
print(time_seconds)
canvas1.create_window(200, 180, window=button1)

timer.mainloop()


from setuptools import setup

# Should match git tag
VERSION = '0.1.1'

def readme():
    with open('README.md') as f:
        return f.read()

with open('requirements.txt') as file:
    REQUIRED_MODULES = [line.strip() for line in file]

with open('requirements-dev.txt') as file:
    DEVELOPMENT_MODULES = [line.strip() for line in file]

setup(name='module-starter.leon',
      version=VERSION,
      description='Starter project for python modules',
      long_description=readme(),
      keywords='module starter',
      url='https://github.com/AumitLeon/module_starter_cli',
      author='Aumit Leon',
      author_email='aumitleon@gmail.com',
      packages=['src'],
      install_requires=REQUIRED_MODULES,
      extras_require={'dev': DEVELOPMENT_MODULES},
      entry_points={
          'console_scripts': ['command=src.command_line:main'],
      },
      include_package_data=True)


import sys

lines = sys.stdin.readlines()

verif = 0
dictionnary = {}

for line in lines:

        temp = list(map(str, line.split()))

        if verif == 1:
                if temp[0] in dictionnary:
                        print(dictionnary.get(temp[0]))
                else:
                        print("eh")

        if not temp :
                verif = 1

        if verif == 0:
                dictionnary[temp[1]] = temp[0]


import tensorflow as tf
import utilities as uti

cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)

def compute_loss(model, dis_model, x, pre_training):
    mean, log_var = model.encoder(x)
    z = uti.sampling_latent_variable(mean, log_var)

    reconstructed = model.decode(z, True)
    rec_loss = tf.reduce_mean(tf.reduce_sum(tf.keras.losses.binary_crossentropy(x, reconstructed), axis=(1, 2)))

    KL_divergence = -0.5 * (1 + log_var - tf.square(mean) - tf.exp(log_var))
    KL_divergence = tf.reduce_mean(tf.reduce_sum(KL_divergence, axis=1))

    batch_size = x.shape[0]
    combined_images = tf.concat([reconstructed, x], axis=0)
    combined_labels = tf.concat([tf.zeros((batch_size, 1)), tf.ones((batch_size, 1))], axis=0)
    combined_labels += 0.05 * tf.random.uniform(tf.shape(combined_labels))
    discriminator_predicted = dis_model.discriminate(combined_images)
    dis_loss = cross_entropy(combined_labels, discriminator_predicted)
    gen_loss = cross_entropy(tf.ones((batch_size, 1)), dis_model.discriminate(reconstructed))

    # gen_score = tf.sigmoid(dis_model.discriminate(reconstructed))
    # second_term = 0.5 * -(tf.reduce_mean(gen_score - 1.0))
    # first_term = 0.5 * tf.reduce_mean(tf.sigmoid(dis_model.discriminate(x)))

    if pre_training:
        return rec_loss + KL_divergence + 100 * gen_loss, dis_loss, gen_loss
    else:
        clusters = model.group(mean)
        p = uti.compute_t_distribution(mean, alpha=100)
        q = uti.compute_t_distribution(clusters, alpha=1)
        p_q_loss = tf.reduce_sum(-(tf.math.multiply(p, tf.math.log(q))))

        return rec_loss + KL_divergence + 100 * gen_loss + 10 * p_q_loss, dis_loss, gen_loss

@tf.function
def train_step(model, dis_model, x, optimizer, optimizer_dis, pre_training):
    with tf.GradientTape() as tape, tf.GradientTape() as dis_tape:
        loss, dis_loss, _ = compute_loss(model, dis_model, x, pre_training)

    gradients = tape.gradient(loss, model.trainable_variables)
    dis_gradients = dis_tape.gradient(dis_loss, dis_model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    optimizer_dis.apply_gradients(zip(dis_gradients, dis_model.trainable_variables))


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

class JoborderProduction(models.Model):
    _name = 'joborder.production'
    _rec_name = 'batch_no'
    _order = 'id desc'

    # @api.depends('qty')
    def calc_surface_area(self):

        for val in self:
            rec = self.env['joborder.challan.receipt.line'].search(
                [('order_id', '=', val.order_ids.id), ('product_id', '=', val.product_id.id)])
            res = self.env['job.order.line'].search(
                [('order_id', '=', rec.job_order_id.id), ('product_id', '=', val.product_id.id)])

            # print(rec, '==================rec val ==', rec.unit_price)
            if val.qty:
                if res.surface_area == 0:
                    val.surface_area = 0
                else:
                    val.surface_area = (val.qty * res.surface_area)
                    val.value = (val.qty * res.unit_price)

    order_ids = fields.Many2one('joborder.challan.receipt', string="Challan No.",ondelete='cascade')
    product_id = fields.Many2one('my.product', 'Product',required=True)
    # part_id = fields.Many2one('part.number', string='Part No', )
    part_no=fields.Char('Part No.')
    unit_id = fields.Many2one('my.unit', 'UOM')
    qty = fields.Float('Quantity', default=1)

    party_name = fields.Many2one('my.partner', 'Party Name')
    party_date = fields.Date('Date')
    expected_qty = fields.Float('OK Qty')
    rejected_qty = fields.Float('NOT OK Qty')
    remark = fields.Char('Remark')
    production_date = fields.Datetime('Production Date')
    batch_no = fields.Char('Incomeing LOT No.')
    batch_no_prod = fields.Char('Production LOT No.')
    process_ids = fields.Many2one('job.process.master', string="Process")
    rework_qty = fields.Float('Rework Qty')
    inspection_id = fields.Many2one('joborder.inspection')
    inspection_count = fields.Integer('Count', compute="action_view_job_order_inspection")
    invoice_count = fields.Integer('Count', compute="action_view_job_order_challan")
    joborder_challan_receipt_line_id = fields.Integer('Rec Line_id')
    challan_issue_count = fields.Integer('Count',compute="action_view_job_order_challan_issue")
    hold_qty  = fields.Float('Hold Quantity')
    is_hold = fields.Boolean('Hold', default=False)
    surface_area = fields.Integer('Surface Area(in²)',compute='calc_surface_area',)# compute='calc_surface_area',
    value=fields.Float('Value',digits=(10,2),compute='calc_surface_area', )#compute='calc_surface_area',
    # rq=fields.Float('RecQty')
    # mq = fields.Float('MoveQty')
    state = fields.Selection([('draft','Draft'),('confirm','Confirm')],default='draft')
    bq = fields.Float('BalQty')

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

    def action_move_to_production(self):# update hold qty
        [action] = self.env.ref('job_order_process.action_wizard_move_update_qty_view111').read()
        action['view_mode'] = 'form'
        action['view_mode'] = 'form'
        action['target'] = 'new'
        # self.write({'state':typ})

        return action

    def action_view_job_order_inspection(self):
        contract_data = self.env['joborder.inspection'].sudo().read_group(
            [('production_id', '=', self.id)], ['id'], ['production_id'])
        result = dict((data['production_id'][0], data['production_id_count']) for data in contract_data)
        for employee in self:
            employee.inspection_count = result.get(self.id, 0)

    def open_inspection_history(self):
        action = self.env.ref('job_order_process.action_challan_inspection').read()[0]
        action['domain'] = [('production_id', '=', self.id)]
        return action

    def action_view_job_order_challan(self):
        contract_data = self.env['joborder.challan'].sudo().read_group(
            [('production_challan_reference', '=', self.order_ids.name), ('partner_id', '=', self.party_name.id),
             ('challan_type', '=', 'return'),('challan_line.product_id', '=', self.product_id.id)], ['id'], ['partner_id'])
        result = dict((data['partner_id'][0], data['partner_id_count']) for data in contract_data)
        for employee in self:
            employee.invoice_count = result.get(self.party_name.id, 0)

    def open_partner_history(self):
        action = self.env.ref('job_order_process.action_challan').read()[0]
        action['domain'] = [('production_challan_reference', '=', self.order_ids.name), ('partner_id', '=', self.party_name.id),
             ('challan_type', '=', 'return'),('challan_line.product_id', '=', self.product_id.id)]
        return action

    def action_view_job_order_challan_issue(self):
        contract_data = self.env['joborder.challan'].sudo().read_group([('partner_id', '=', self.party_name.id),('challan_type', '=', 'regular'),('challan_line.product_id', '=', self.product_id.id),('challan_line.party_challan','=',self.order_ids.id)], ['id'],
            ['partner_id'])
        result = dict((data['partner_id'][0], data['partner_id_count']) for data in contract_data)
        for employee in self:
            employee.challan_issue_count = result.get(self.party_name.id, 0)

    def open_challan_issue_history(self):
        action = self.env.ref('job_order_process.action_challan').read()[0]
        action['domain'] = [('partner_id', '=', self.party_name.id),('challan_type', '=', 'regular'),('challan_line.product_id', '=', self.product_id.id),('challan_line.party_challan','=',self.order_ids.id)]
        return action

    def action_return(self):
        rec = self.env['joborder.challan.receipt.line'].search(
            [('order_id', '=', self.order_ids.id), ('product_id', '=', self.product_id.id)])
        res = self.env['joborder.challan']
        res.create({
            'partner_id': self.party_name.id,
            'challan_type': 'return',
            'production_challan_reference': self.order_ids.name,
            'challan_line': [(0, 0,
            {
                'product_id': self.product_id.id,
                'party_challan': self.order_ids.id,
                'qty': self.rejected_qty,
                # 'part_id': self.part_id.id,
                'part_no':self.part_no,
                'unit_id': self.unit_id.id,
                'job_order_id': rec.job_order_id.id,
                'joborder_challan_receipt_line_id': rec.id,
                # 'joborder_challan_receipt_line_id': self.joborder_challan_receipt_line_id,
            })]
        })
        self.is_return = True

    def action_move(self):
        rec = self.env['joborder.inspection']
        rec.create({
            'order_ids': self.order_ids.id,
            'party_name': self.party_name.id,
            'party_date': datetime.strptime(str(self.party_date), '%Y-%m-%d').strftime('%Y-%m-%d'),
            'product_id': self.product_id.id,
            'qty': self.rework_qty,
            # 'part_id': self.part_id.id,
            'part_no':self.part_no,
            'unit_id': self.unit_id.id,
            'batch_no':self.batch_no,
            'inspection_date': self.production_date,
            'process_ids': self.process_ids.id,
            'production_id':self.id,
            'joborder_challan_receipt_line_id': self.joborder_challan_receipt_line_id,

        })
        self.is_inspection = True

    def action_done(self):
        rec = self.env['joborder.challan.receipt.line'].search(
            [('order_id', '=', self.order_ids.id), ('product_id', '=', self.product_id.id)])
        res = self.env['joborder.challan']
        res.create({
            'partner_id': self.party_name.id,
            'challan_type': 'regular',
            #'job_order_challan_reference': self.order_ids.name,
            'challan_line': [(0, 0,
                              {
                                  'product_id': self.product_id.id,
                                  'party_challan': self.order_ids.id,
                                  'qty': self.expected_qty,
                                  # 'part_id': self.part_id.id,
                                  'part_no':self.part_no,
                                  'unit_id': self.unit_id.id,
                                  'job_order_id': rec.job_order_id.id,
                                  'unit_price':rec.unit_price,
                                  'tax_id':rec.tax_id.id,
                                  'joborder_challan_receipt_line_id':rec.id,

                               })]

        })
        self.is_issue = True

    # @api.onchange('expected_qty','rejected_qty','rework_qty')
    # def change_ok_reqork_qty(self):
    #     total = 0
    #     total = self.expected_qty + self.rework_qty + self.rejected_qty
    #     if self.expected_qty and self.rejected_qty and self.rework_qty:
    #         total = self.expected_qty + self.rework_qty + self.rejected_qty
    #         if self.expected_qty > self.qty:
    #             raise  ValidationError(_('Ok qty should not more than the actual quantity'))
    #         if total > self.qty:
    #             raise ValidationError(_('Total quantity should not more than the actual quantity'))
    #         if total < self.qty:
    #             raise ValidationError(_('Total quantity should not less than the actual quantity'))
    # @api.constrains('expected_qty','rejected_qty','rework_qty')
    # def change_ok_reqork_qty(self):
    #     total = 0
    #     total = self.expected_qty + self.rework_qty + self.rejected_qty
    #     if self.expected_qty > self.qty:
    #         raise  ValidationError(_('Ok qty is not more than the actual quantity'))
    #     if total > self.qty:
    #         raise ValidationError(_('Total quantity is not more than the actual quantity'))
    #     if total < self.qty:
    #         raise ValidationError(_('Total quantity is not less than the actual quantity'))


def solve(arr):
    arr = sorted(arr)

    li = []
    result = []
    while arr:
        try:
            li.append(max(arr))
            li.append(min(arr))
            arr.remove(max(arr))
            arr.remove(min(arr))
        except:
            ''
    for item in li:
        if item not in result:
            result.append(item)

    return result


# find good features

# carry out optical flow

#  nearest neighbor search? dont really understand this part

# ratio test -  its nice to have a slider and visual by this point

from rospkg import RosPack
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from triangulation import calc_F

def get_keypoints(img1_path, img2_path):
    img1 = cv2.imread(img1_path, cv2.COLOR_BGR2GRAY)
    img2 = cv2.imread(img2_path, cv2.COLOR_BGR2GRAY)
    # Create sift detector
    sift = cv2.SIFT_create()

    # find the keypoints and descriptors with SIFT
    kp1, des1 = sift.detectAndCompute(img1,None)
    kp2, des2 = sift.detectAndCompute(img2,None)

    # FLANN parameters
    FLANN_INDEX_KDTREE = 2
    index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 7)
    search_params = dict(checks=50)   # or pass empty dictionary
    flann = cv2.FlannBasedMatcher(index_params,search_params)
    matches = flann.knnMatch(des1,des2,k=2)
    # Need to draw only good matches, so create a mask
    matchesMask = [[0,0] for i in range(len(matches))]
    # ratio test as per Lowe's paper
    good_matches = []
    pts_img1 = []
    pts_img2 = []
    for i,(m,n) in enumerate(matches):
        if m.distance < 0.35 * n.distance:
            pts_img2.append(kp2[m.trainIdx].pt)
            pts_img1.append(kp1[m.queryIdx].pt)
            matchesMask[i]=[1,0]
    draw_params = dict(matchColor = (0,255,0),
                    singlePointColor = (255,0,0),
                    matchesMask = matchesMask,
                    flags = cv2.DrawMatchesFlags_DEFAULT)
    img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,**draw_params)

    return pts_img1, pts_img2

pts_img1, pts_img2 = get_keypoints("image_1.png", "image_2.png")

# printing out points
# print('points image 1', pts_img1)
# print('points image 2', pts_img2)

# F, mask = cv2.findFundamentalMat(pts_img1,pts_img2,cv2.FM_RANSAC)

# finding fundamental matrix
F = calc_F(pts_img1, pts_img2)

# writing out camera calibration matrix
K = np.array([[1013.109848, 0.000000, 493.049154],
              [0.000000, 1013.410857, 390.447766],
              [0.000000, 0.000000, 1.000000]
])

# special matrice W used for seperating essential matrix
W = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
# finding essential matrix
E = np.matmul(np.transpose(K), F, K)

# seperating into rotational and translation matrice options
U, sigma, V = np.linalg.svd(E)

# options for R and T
R1 = np.matmul(U, W, np.transpose(V))
R2 = np.matmul(U, np.transpose(W), np.transpose(V))
t1 = U[:,[2]]
t2 = -U[:,[2]]

# four options for camera matrices
P1_1 = np.hstack([R1, t1])
P1_2 = np.hstack([R1, -t1])
P1_3 = np.hstack([R2, t1])
P1_4 = np.hstack([R2, -t1])

print('P1', P1_1, 'P1', P1_2)


import math
import random

#TODO bias and bias wt

def softmax(output_layer_vals):
	softmax_vals = []
	sum_of_vals = 0
	max_val = 0
	for output_layer_val in output_layer_vals:
		if max_val < output_layer_val:
			max_val = output_layer_val

	for i, output_layer_val in enumerate(output_layer_vals):
		sum_of_vals += math.exp(output_layer_val - max_val)

	for i, output_layer_val in enumerate(output_layer_vals):
		softmax_vals.append(math.exp(output_layer_val - max_val)/sum_of_vals)

	return softmax_vals

def derivative_softmax(x):
	return x * (1-x)

def leaky_relu(x):
	if x < 0:
		return 0.01 *x
	else:
		return x

def derivative_leaky_relu(x):
	if x < 0:
		return 0.001
	else:
		return 1

def output_function(x):
	return 1/(1 + math.exp(-x))

def derivative_output_function(x):
	return math.exp(x)/((1-math.exp(x)) * (1-math.exp(x)))

def output_summation(layer, i):
	sum = 0
	for neuron in layer.neurons:
		#print neuron
		sum += neuron.get_summation(i)
	return sum

class HiddenLayer:
	bias = 1
	neurons = []
	prevLayer = None
	nextLayer = None
	inputSummation = []

	def __init__(self, hidden_layer_size):
		self.size = hidden_layer_size

	def calc_neuron_vals(self):
		self.inputSummation = []
		for i, neuron in enumerate(self.neurons):
			self.inputSummation.append(output_summation(self.prevLayer, i) + self.bias)
			neuron.value = output_function(self.inputSummation[-1])
			#print "val ", neuron.value

	def set_architecture(self, prevLayer, nextLayer):
		self.prevLayer = prevLayer
		self.nextLayer = nextLayer
		bias = 0.5
		for i in xrange(self.size):
			self.neurons.append(Neuron())
			for j, neuron in enumerate(self.prevLayer.neurons):
				neuron.outgoing_weights.append(random.uniform(0, 1))

	def change_weights(self, rate):
		for i, neuron in enumerate(self.neurons):
			neuron.error = derivative_output_function(self.inputSummation[i])
			sumNextErrors = 0
			for j, nextNeuron in enumerate(self.nextLayer.neurons):
				sumNextErrors += neuron.outgoing_weights[i] * nextNeuron.error
			neuron.error *= sumNextErrors
			for j, prevNeuron in enumerate(self.prevLayer.neurons):
				weightDiff = rate * neuron.error * prevNeuron.value
				prevNeuron.outgoing_weights[i] += weightDiff

class InputLayer:
	neurons = []
	nextLayer = None
	def __init__(self, size):
		self.size = size

	def set_architecture(self, nextLayer):
		for i in xrange(self.size):
			self.neurons.append(Neuron())
		self.nextLayer = nextLayer

	def put_values(self, feature_vector):
		for i, feature in enumerate(feature_vector):
			self.neurons[i].value = feature

class OutputLayer:
	bias = 1
	neurons = []
	prevLayer = None
	inputSummation = []

	def __init__(self, output_size):
		self.size = output_size

	def calc_neuron_vals(self):
		self.inputSummation = []
		for i, neuron in enumerate(self.neurons):
			#print output_summation(self.prevLayer, i)
			self.inputSummation.append(output_summation(self.prevLayer, i) + self.bias)
		neuron_vals = softmax(self.inputSummation)
		for i, neuron in enumerate(self.neurons):
			neuron.value = neuron_vals[i]

	def set_architecture(self, hiddenLayer):
		self.prevLayer = hiddenLayer
		bias = 0.5
		for i in xrange(self.size):
			self.neurons.append(Neuron())
			for j, neuron in enumerate(self.prevLayer.neurons):
				neuron.outgoing_weights.append(random.uniform(0, 1))

	def put_values(self, expected_output):
		self.expected_output = expected_output

	def output_diff(self):
		diff = []
		for i in xrange(self.size):
			diff.append(self.expected_output[i] - self.neurons[i].value)
		return diff

	def get_output(self):
		max_val = 0
		max_pos = 0
		for i, neuron in enumerate(self.neurons):
			if max_val < neuron.value:
				max_val = neuron.value
				max_pos = i
		inps = ['frog', 'bird', 'airplane', 'dog', 'deer', 'truck', 'automobile', 'horse', 'cat', 'ship']
		return inps[max_pos]

	def change_weights(self, rate):
		diff = self.output_diff()
		#print "diff ", diff
		for i, neuron in enumerate(self.neurons):
			neuron.error = diff[i] * derivative_softmax(neuron.value)
			#print self.inputSummation[i]
			for j, prevNeuron in enumerate(self.prevLayer.neurons):
				weightDiff = rate * neuron.error * prevNeuron.value
				#print weightDiff
				prevNeuron.outgoing_weights[i] += weightDiff

class Neuron:
	value = 0
	outgoing_weights = []
	error = 0
	def __init__(self):
		pass

	def get_summation(self, i):
		return self.value * self.outgoing_weights[i]


# coding: utf-8
# Author: wanhui0729@gmail.com

# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/

'''
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
'''
class Solution_1(object):
    '''
    双指针法
    时间复杂度: O(n)
    空间复杂度: O(1)
    '''
    def twoSum(self, numbers, target):
        left, right = 0, len(numbers) - 1
        while left < right:
            if numbers[left] + numbers[right] > target:
                right -= 1
            if numbers[left] + numbers[right] < target:
                left += 1
            if numbers[left] + numbers[right] == target:
                return [left+1, right+1]

class Solution_2(object):
    '''
    空间换取时间
    时间复杂度: O(n)
    空间复杂度: O(n)
    '''
    def twoSum(self, numbers, target):
        visited = {}
        for index, number in enumerate(numbers):
            if target - number in visited:
                return [visited[target - number], index + 1]
            else:
                visited[number] = index + 1

if __name__ == '__main__':
    s1 = Solution_1()
    s2 = Solution_2()
    assert s1.twoSum([2, 7, 11, 15], 9) == [1, 2]
    assert s2.twoSum([2, 7, 11, 15], 9) == [1, 2]

'''
intuition
常见处理方法可以想到使用空间换取时间的方法，但是没有利用到已排序的特性
双指针法则很好的利用了排序的特性且将空间复杂度降到最低
'''


def numbers_searching(*args):
    min_num = min(*args)
    max_num = max(*args)
    result = []
    seq_example = {x for x in range(min_num,max_num+1)}
    seq_actual = list(args)
    seq_actual_Set = set(seq_actual)

    missing_number = seq_example - seq_actual_Set
    result.append(missing_number.pop())

    list_result = sorted([item for item in seq_example if seq_actual.count(item)>1])
    result.append(list_result)
    return(result)

print(numbers_searching(1, 2, 4, 2, 5, 4))


import pathlib
from shutil import copyfile

import numpy as np

p4_sys_names = [
    "FT_EFF_B_systematics__1",
    "FT_EFF_C_systematics__1",
    "FT_EFF_Light_systematics__1",
    "FT_EFF_extrapolation__1",
    "FT_EFF_extrapolation_from_charm__1",
    "MUON_EFF_ISO_STAT__1",
    "MUON_EFF_ISO_SYS__1",
    "MUON_EFF_RECO_STAT__1",
    "MUON_EFF_RECO_STAT_LOWPT__1",
    "MUON_EFF_RECO_SYS__1",
    "MUON_EFF_RECO_SYS_LOWPT__1",
    "MUON_EFF_TTVA_STAT__1",
    "MUON_EFF_TTVA_SYS__1",
    "MUON_ID__1",
    "MUON_MS__1",
    "MUON_SAGITTA_RESBIAS__1",
    "MUON_SAGITTA_RHO__1",
    "MUON_SCALE__1",
    "PRW_DATASF__1",
]

# parameters
fit_ntup_dir = "/data/zprime/ntuples_fit/22-0120-sys"
mass_points_low = [5, 7, 9, 11, 13, 15, 17, 19, 23, 27, 31, 35, 39, "42_low"]
mass_points_high = ["42_mz2", 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75]

mass_points_low_num = [5, 7, 9, 11, 13, 15, 17, 19, 23, 27, 31, 35, 39, 42]
mass_points_high_num = [42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75]

dnn_cut_dict = {
    5: 0.46,
    7: 0.58,
    9: 0.50,
    11: 0.60,
    13: 0.52,
    15: 0.54,
    17: 0.54,
    19: 0.65,
    23: 0.54,
    27: 0.65,
    31: 0.68,
    35: 0.72,
    39: 0.74,
    "42_low": 0.74,
    "42_mz2": 0.24,
    42: 0.16,
    45: 0.10,
    48: 0.10,
    51: 0.14,
    54: 0.12,
    57: 0.12,
    60: 0.12,
    63: 0.14,
    66: 0.12,
    69: 0.16,
    72: 0.20,
    75: 0.14,
}

def get_sigma(mass):
    # sigma_range = 3.0 * (0.0401444 + 0.0122949 * mass + 0.000140695 * mass * mass)  # @ Bing Li
    # sigma_range = 3.0 * (0.193 - 0.002 * mass + 0.00035 * mass * mass)  # @ Shuzhou Zhang
    sigma = np.poly1d(
        [
            5.20753537e-08,
            3.34322964e-08,
            -2.17314377e-04,
            2.26208490e-02,
            -1.81540253e-02,
        ]
    )
    return sigma(mass)

def get_mass_cut(mass):
    sigma_range = 3 * get_sigma(mass)
    return (
        np.around(mass - sigma_range, decimals=2),
        np.around(mass + sigma_range, decimals=2),
    )

def get_bin_dict(mass):
    bin_dict_SR = {}
    bin_dict_CR = {}

    # 1D case
    # 10 bins
    # bin_dict_SR["10bins"], bin_dict_CR["10bins"] = 10, 10
    # 20 bins
    # bin_dict_SR["20bins"], bin_dict_CR["20bins"] = 20, 20

    # 10 bins
    # bin_dict_SR["10bins_auto"] = 'Binning: "AutoBin","TransfoD", 5, 5'
    # bin_dict_CR["10bins_auto"] = 'Binning: "AutoBin","TransfoD", 5, 5'
    # 20 bins
    bin_dict_SR["20bins_auto"] = 'Binning: "AutoBin","TransfoD", 10, 10'
    bin_dict_CR["20bins_auto"] = 'Binning: "AutoBin","TransfoD", 10, 10'

    return bin_dict_SR, bin_dict_CR

# Script to create config files

with open("config_template_morph.config", "r") as f:
    config_temp = f.read()
with open("config_template_overall_sys_module.config", "r") as f:
    config_overall_sys_temp = f.read()
with open("config_template_wt_sys_module.config", "r") as f:
    config_wt_sys_temp = f.read()
with open("config_template_p4_sys_module.config", "r") as f:
    config_p4_sys_temp = f.read()

def prepare_config(
    mass,
    region,
    dnn_cut,
    mass_left,
    mass_right,
    sig_scale_left,
    sig_scale_right,
    shift_left,
    shift_right,
):
    # Setups
    if region == "low_mass":
        fit_var = "mz2"
    else:
        fit_var = "mz1"
    mass_str = f"m_{mass:05.2f}"
    # regular settings
    m_low, m_high = get_mass_cut(mass)
    bin_sr = 'Binning: "AutoBin","TransfoD", 10, 10'
    bin_cr = 'Binning: "AutoBin","TransfoD", 10, 10'
    dnn_label = f"p{int(dnn_cut*100):02d}"
    if region == "low_mass":
        p_cr_low = 0
        p_cr_high = 45
    else:
        p_cr_low = 30
        p_cr_high = 85

    # Folders
    stats_dir = pathlib.Path(f"stats_morph/{mass_str}")
    stats_dir.mkdir(parents=True, exist_ok=True)
    sys_dir = pathlib.Path(f"sys_morph/{mass_str}")
    sys_dir.mkdir(parents=True, exist_ok=True)

    # Stats config
    stats_config = config_temp.format(
        p_job="default",
        p_mass=mass,
        p_dnn_label=dnn_label,
        p_fit_var=fit_var,
        p_ntuple_path=f"{fit_ntup_dir}/{region}/tree_NOMINAL",
        p_mass_cut_low=m_low,
        p_mass_cut_high=m_high,
        p_dnn_cut=dnn_cut,
        p_dnn_cut_label=dnn_label,
        p_region=region,
        p_window=np.around(m_high - m_low, decimals=2),
        p_cr_cut_low=p_cr_low,
        p_cr_cut_high=p_cr_high,
        p_cr_low=p_cr_low,
        p_cr_high=p_cr_high - (m_high - m_low),
        p_cr_bin=10,
        p_sr_bin=10,
        p_binning_cr=bin_sr,
        p_binning_sr=bin_cr,
        # For the morphing
        p_mass_left=mass_left,
        sig_scale_left=str(sig_scale_left),
        p_mass_right=mass_right,
        sig_scale_right=str(sig_scale_right),
        p_shift_left=str(shift_left),
        p_shift_right=str(shift_right),
    )
    config_name = f"{mass_str}_cut_{dnn_label}_stats.config"
    with stats_dir.joinpath(config_name).open("w", encoding="utf-8") as f:
        f.write(stats_config)

    # Sys config
    # add overall sys
    sys_config = stats_config[:]
    sys_config += config_overall_sys_temp[:]
    # add weight systematic config
    config_wt_config = config_wt_sys_temp.format(
        p_mass=mass,
        p_ntuple_path=f"{fit_ntup_dir}/{region}/tree_NOMINAL",
        p_region=region,
        p_qcd_var=fit_var,
    )
    sys_config += config_wt_config
    # add p4 systematic config
    for sys_name in p4_sys_names:
        ntuple_path_up_sig = f"{fit_ntup_dir}/{region}/tree_{sys_name}up"
        ntuple_path_down_sig = f"{fit_ntup_dir}/{region}/tree_{sys_name}down"
        # sig
        sys_entry = config_p4_sys_temp.format(
            p_sys_name=sys_name[5:],
            p_sample="Zprime_left",
            p_ntuple_path_up=ntuple_path_up_sig,
            p_ntuple_path_down=ntuple_path_down_sig,
            p_ntuple_files=f"sig_Zp{mass_left:03d}",
            p_weight_str=f"weight * {sig_scale_left}",
        )
        sys_config += sys_entry

        sys_entry = config_p4_sys_temp.format(
            p_sys_name=sys_name[5:],
            p_sample="Zprime_right",
            p_ntuple_path_up=ntuple_path_up_sig,
            p_ntuple_path_down=ntuple_path_down_sig,
            p_ntuple_files=f"sig_Zp{mass_right:03d}",
            p_weight_str=f"weight * {sig_scale_right}",
        )
        sys_config += sys_entry

        # bkg
        ntuple_path_up_bkg = f"{fit_ntup_dir}/{region}/tree_{sys_name}up"
        ntuple_path_down_bkg = f"{fit_ntup_dir}/{region}/tree_{sys_name}down"
        ## add qcd
        sys_entry = config_p4_sys_temp.format(
            p_sys_name=sys_name,
            p_sample="ZZ4l",
            p_ntuple_path_up=ntuple_path_up_bkg,
            p_ntuple_path_down=ntuple_path_down_bkg,
            p_ntuple_files="bkg_qcd",
            p_weight_str="weight",
        )
        sys_config += sys_entry
        ## add ggZZ
        sys_entry = config_p4_sys_temp.format(
            p_sys_name=sys_name,
            p_sample="ggZZ",
            p_ntuple_path_up=ntuple_path_up_bkg,
            p_ntuple_path_down=ntuple_path_down_bkg,
            p_ntuple_files="bkg_ggZZ",
            p_weight_str="weight",
        )
        sys_config += sys_entry
    # save
    config_name = f"{mass_str}_cut_{dnn_label}_sys.config"
    with sys_dir.joinpath(config_name).open("w", encoding="utf-8") as f:
        f.write(sys_config)

    fit_script_name = "fit_all.sh"
    copyfile(f"./{fit_script_name}", stats_dir.joinpath(fit_script_name))
    copyfile(f"./{fit_script_name}", sys_dir.joinpath(fit_script_name))


# This is a sample Python script.

import os
import argparse

def main(database: str, url_list_file: str):
    print("We are going to work with " + database)
    print("We are going to scan " + url_list_file)

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-db", "--database", help="SQLite file name")
    parser.add_argument("-i", "--input", help="File containing urls to read")
    args = parser.parse_args()
    database_file = args.database
    input_file = args.input
    main(database=database_file, url_list_file=input_file)

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


import logging

import boto3
from botocore.client import BaseClient
from botocore.exceptions import ClientError
from decouple import config
from fastapi import UploadFile

from app.utils.date_utils import D

class S3:
    s3_client: BaseClient = boto3.client(
        service_name="s3",
        aws_access_key_id=config("AWS_ACCESS_KEY"),
        aws_secret_access_key=config("AWS_SECRET_KEY")
    )
    BUCKET_NAME = "fleapto-files"
    url = "https://{bucket}.s3.ap-northeast-2.amazonaws.com/{filename}"

    @classmethod
    def upload_file_to_bucket(cls, file: UploadFile):
        filename = f"{D.datetimenum()}_{file.filename}"
        try:
            response = cls.s3_client.upload_fileobj(
                file.file,
                cls.BUCKET_NAME,
                filename,
                ExtraArgs={'ACL': 'public-read'}
            )
        except ClientError as e:
            logging.error(e)
            return None

        url = cls.url.format(bucket=cls.BUCKET_NAME, filename=filename)
        return url


# -*- coding: utf-8 -*-
"""
Created on Sat Jul 17 13:07:36 2021

@author: Stephen
https://github.com/thekitchenscientist/pydotART

Sample programs for the 41935 Set
https://rebrickable.com/sets/41935-1/lots-of-dots/#parts
"""

import pydotART as da

from itertools import combinations_with_replacement
from itertools import permutations, chain
import numpy as np

### Basic Configuration ###
# What tiles are available? [Colour,Shape,Amount]
palette = np.array([[15,1.,36],
                    [15,3.,36],
                    [15,4.,36],
                    [4,1.,36],
                    [4,3.,36],
                    [4,4.,36],
                    [212,2.,36]
                    ])

# Canvas Size and Colour
x=6
y=6
colour=15

# How wide should the untiled border around the edge be?
border=0

# What is the location and size of a central gap [x,y,x_length, y_length]
cutout=np.array([0,0,0,0])

# Where should the tiling start from?
canvas_seed=[0,0]

# Where should the next tile be placed relative to the previous?
translation=np.array([0,0])

width_x = 3
width_y = 3

colour = 15
colour_mode = 'random'
canvas_seed = [0,0]
border=0
cutout=np.array([0,0,0,0])

#inputs to function
max_worm_length = 3
canvas = da.Canvas(width_x,width_y,colour,border,cutout)
starting_x = 0
starting_y = 0
tile_ID = 1

#generate sequence based on width X and width Y
down_sequence = [1]*width_y
along_sequence = [1]*width_x
down_sequence[0] = along_sequence[0] = 3.0
down_sequence[-1] = along_sequence[-1] = 3.0

def generate_worm(canvas,starting_y = 0,max_worm_length=1000,tile_ID=1):

    pattern = canvas
    width_x = canvas[0]
    width_y = canvas[1]
    sequence = [1]*width_x
    sequence[0] = sequence[-1] = 3.0
    worm_length = 0

    #check can start
    for i in range(0,width_y):
        if starting_y >= width_y:
            #print('no space')
            return pattern
        slice_y = pattern[8][0][:,starting_y]
        if np.sum(slice_y) == 0:
                break
        elif starting_y < width_y:
            starting_y += 1

    current_xy= [0,starting_y]

    #loop over all rows
    for k in range (0,canvas[1]):
        if worm_length >= max_worm_length:
            break
        if worm_length < max_worm_length:
            for tile_shape in sequence:
                #need to choose to add .2/.8 or .4/.6 to tile on start
                tile_modifier = 0.0
                if current_xy[0] == 0:
                    tile_modifier =  0.4
                elif current_xy[0] == width_x-1:
                    tile_modifier =  0.8

                if worm_length == 0:
                    pattern[8][0][current_xy[0]][current_xy[1]] = 4.2
                else:
                    pattern[8][0][current_xy[0]][current_xy[1]] = tile_shape + tile_modifier
                pattern[8][1][current_xy[0]][current_xy[1]] = tile_ID
                worm_length+=1
                if worm_length >= max_worm_length:
                    if current_xy[0] == 0:
                        tile_modifier =  0.8
                    else:
                        tile_modifier =  0.6
                    pattern[8][0][current_xy[0]][current_xy[1]] = 4 + tile_modifier
                    break
                current_xy[0]+=1

            # next row
            current_xy[1]+=1

            if current_xy[0] >= width_x:
                current_xy[0]=width_x-1
        if worm_length >= max_worm_length or current_xy[0] < 0  or current_xy[1] < 0 or current_xy[0] >=width_x  or current_xy[1] >=width_y:
            break

        #carry on back
        if worm_length < max_worm_length:
            for tile_shape in reversed(sequence):

                tile_modifier = 0.0
                if current_xy[0] == 0:
                    tile_modifier =  0.2
                elif current_xy[0] == width_x-1:
                    tile_modifier =  0.6
                pattern[8][0][current_xy[0]][current_xy[1]] = tile_shape + tile_modifier
                pattern[8][1][current_xy[0]][current_xy[1]] = tile_ID
                worm_length+=1
                if worm_length >= max_worm_length:
                    if current_xy[0] == width_x-1:
                        tile_modifier =  0.8
                    else:
                        tile_modifier =  0.2
                    pattern[8][0][current_xy[0]][current_xy[1]] = 4 + tile_modifier
                    break
                current_xy[0]-=1

            # next row
            current_xy[1]+=1

            if current_xy[0] < 0:
                current_xy[0]=0

        if worm_length >= max_worm_length or current_xy[0] < 0  or current_xy[1] < 0 or current_xy[0] >=width_x  or current_xy[1] >=width_y:
            break
    pattern[9] =  tile_ID
    return pattern

#loop here to keep starting worms till no space left
#increment tile_ID each time
def fill_with_worms(worm_canvas,starting_y,max_worm_length,tile_ID):
    for j in range (0,width_y):
        worm_canvas = generate_worm(worm_canvas,starting_y=j,max_worm_length=max_worm_length,tile_ID=tile_ID)
        tile_ID =worm_canvas[9]
        tile_ID +=1
    #fill in remainder with circles
    worm_canvas[8][0][np.where(worm_canvas[8][0]==0)]=2
    worm_canvas[8][1][np.where(worm_canvas[8][1]==0)]=tile_ID
    return worm_canvas

def fill_with_worm(worm_canvas,starting_y,max_worm_length,tile_ID):
    worm_canvas = generate_worm(worm_canvas,starting_y=0,max_worm_length=max_worm_length,tile_ID=tile_ID)
    tile_ID =worm_canvas[9]
    tile_ID +=1
    #fill in remainder with circles
    worm_canvas[8][0][np.where(worm_canvas[8][0]==0)]=2
    worm_canvas[8][1][np.where(worm_canvas[8][1]==0)]=tile_ID
    return worm_canvas

def Larger_Canvas_Rotation(original):
    rot_90 = da.Rotate_Pattern(original[8][0], angle=90)
    rot_ID_90 = np.rot90(original[8][1], k=-1)
    rot_180 = da.Rotate_Pattern(rot_90, angle=90)
    rot_ID_180 = np.rot90(rot_ID_90, k=-1)
    rot_270 = da.Rotate_Pattern(rot_180, angle=90)
    rot_ID_270 = np.rot90(rot_ID_180, k=-1)
    larger_canvas = da.Canvas(original[0]*2,original[1]*2,colour,border,cutout)
    #tidy way to apply pattern to a larger canvas
    larger_canvas[8][0][0:original[0], 0:original[1]] = original[8][0]
    larger_canvas[8][1][0:original[0], 0:original[1]] = original[8][1]
    larger_canvas[8][0][0:original[0], original[1]:larger_canvas[1]] = rot_90
    larger_canvas[8][1][0:original[0], original[1]:larger_canvas[1]] = rot_ID_90
    larger_canvas[8][0][original[0]:larger_canvas[0], original[1]:larger_canvas[1]] = rot_180
    larger_canvas[8][1][original[0]:larger_canvas[0], original[1]:larger_canvas[1]] = rot_ID_180
    larger_canvas[8][0][original[0]:larger_canvas[0], 0:original[1]] = rot_270
    larger_canvas[8][1][original[0]:larger_canvas[0], 0:original[1]] = rot_ID_270
    return larger_canvas

canvas = da.Canvas(width_x*width_y,width_x*width_y,colour,border,cutout)
pattern_list = []
for i in range(2,width_x*width_y+1):
    worm_canvas = da.Canvas(width_x,width_y,colour,border,cutout)
    starting_y = 0
    result = fill_with_worms(worm_canvas,starting_y,i,tile_ID)
    tile_ID =result[9]
    tile_ID +=1
    pattern_list.append(result)

palette = np.array([[22,1.,36],
                    [15,1.,36],
                    [14,2.,36]
                    ])
colour_mode = 'sequence'

larger_canvas_list = []
for i in range(0,len(pattern_list)):
    larger_canvas = Larger_Canvas_Rotation(pattern_list[i])
    larger_canvas_list.append(larger_canvas)

canvas_scale = int(np.sqrt(len(pattern_list)))
canvas = da.Canvas(width_x*width_x*canvas_scale,width_y*width_y*canvas_scale,colour,border,cutout)
canvas = da.Spiral_Pattern_List(canvas,canvas_seed,larger_canvas_list,direction=1,rotate=0,tile_ID = 1)

colour_pattern = da.Colour_Pattern(canvas,palette,colour_mode,tiles_check=False)
da.Ldraw_Pattern(canvas,"tiled rotated worms patterns" +str(width_x)+ "x" +str(width_y),add_steps=True)


from depositapi.serializers import DepositSerializer
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
import datetime
from dateutil.relativedelta import relativedelta

class DepositCalculate(generics.CreateAPIView):
    serializer_class = DepositSerializer
    def post(self, request):
        error_message = { 'error': 'Описание ошибки'}
        date = request.data.get('date')
        date = request.data.get('date')
        periods = int(request.data.get('periods'))
        amount = int(request.data.get('amount'))
        rate = float(request.data.get('rate'))
        deposit = {}
        try: # проверяем что дата введена в нужном формате
            date_time_obj = datetime.datetime.strptime(date, '%d.%m.%Y') # переводим дату-строку в объект календарной даты
        except ValueError:
            return Response(error_message, status=status.HTTP_400_BAD_REQUEST)
        else:
            if 1<=periods<=60 and 10000<=amount<=3000000 and 1<=rate<=8: # валидация входных данных
                newdeposit = DepositSerializer(data=request.data)
                for i in range(periods):
                    amount = amount * (1 + rate/12/100) # к сумме вклада добавляется сумма по процентам за этот месяц
                    deposit[date] = round(amount, 2) # округляем число до двух знаков после запятой
                    date_time_obj = date_time_obj + relativedelta(months=+1, day=31) # увеличиваем на один месяц и добавляем максимальное количество дней в месяце, чтобы получить последний день месяца
                    date = datetime.datetime.strftime(date_time_obj, '%d.%m.%Y') # форматируем дату обратно в строку
                # newdeposit = Deposit(date=date, periods=periods, amount=amount, rate=rate, deposit=deposit)
                newdeposit.deposit = deposit
                newdeposit.save
                return Response(newdeposit.deposit, status=status.HTTP_200_OK)
            else:
                return Response(error_message, status=status.HTTP_400_BAD_REQUEST)


from .accounts import Accounts, IRAAccount, RothAccount, TaxableAccount
from .tax import CAPITAL_TAX_TABLE, FED_TAX_TABLE, REGULAR_TAX, STATE_TAX_TABLE

NEED_EXPENSES = 45000
WANT_EXPENSES = 10000

ACA_PREMIUMS = 15000
MEDICARE_PREMIUMS = 5000

MINIMUM_ACCOUNT_BALANCE_PERCENT = 0.1

SS_AMOUNT = 47500

class Plan:
    def portfolio(self, age):
        return {"stocks": 0.75, "bonds": 0.2, "cash": 0.05}

    def pre_tax_expenses(self, age):
        """Calculate the years expenses before tax expenses are added."""
        base_expenses = NEED_EXPENSES + WANT_EXPENSES
        if age < 65:
            return base_expenses + ACA_PREMIUMS

        expenses = base_expenses + MEDICARE_PREMIUMS
        if age >= 70:
            expenses = max(expenses - SS_AMOUNT, 0)
        return expenses

    def income_source(self, age, starting):
        """

        Returns:
            tuple: Tuple of floats that should sum to 1.  Represents what percent of
            expenses comes from which account (taxable, ira, roth)

        At present it's all or nothing, but that could change.
        """
        if age < 60:
            return (1, 0, 0)
        if (
            starting.ira.balance - self.pre_tax_expenses(age)
            > starting.net_worth * MINIMUM_ACCOUNT_BALANCE_PERCENT
        ):
            return (0, 1, 0)
        if (
            starting.taxable.balance - self.pre_tax_expenses(age)
            > starting.net_worth * MINIMUM_ACCOUNT_BALANCE_PERCENT
        ):
            return (1, 0, 0)
        return (0, 0, 1)

    def roth_conversion(self, age):
        if age < 0:
            return 20000
        return 0

class Year:
    def __init__(
        self, age: int, taxable_value: float, ira_value: float, roth_value: float
    ):
        self.processed = False
        # Age on January 1st
        self.age = age
        # assets at the beginning of the year
        self.starting = Accounts(
            TaxableAccount(taxable_value),
            IRAAccount(ira_value),
            RothAccount(roth_value),
        )
        # Assets at the end of the year
        self.ending = None

        self.stock_growth = None
        self.bond_growth = None
        self.inflation = None

        self.plan: Plan = Plan()

    @property
    def growth(self):
        if self.stock_growth is None or self.bond_growth is None:
            return None
        portfolio = self.plan.portfolio(self.age)
        growth = 0
        growth += self.stock_growth * portfolio["stocks"]
        growth += self.bond_growth * portfolio["bonds"]
        return growth

    def _calculate_taxable_income(self, expenses):
        """
        Return the amount of taxable income broken up in to capital income, and
        regular income.
        """
        regular_income = 0
        capital_income = 0

        needed_extra_income = max(expenses - (regular_income + capital_income), 0)
        source = self.plan.income_source(self.age, self.starting)
        capital_income += needed_extra_income * source[0]
        regular_income += needed_extra_income * source[1]

        capital_income, regular_income = self._adjust_for_forced_income(
            capital_income, regular_income
        )

        regular_income += self.plan.roth_conversion(self.age)
        # print(regular_income, capital_gains)
        return capital_income, regular_income

    def _adjust_for_forced_income(self, capital_income, regular_income):
        """
        Adjust the taxable income values based on the amount of forced taxable income.

        TODO: Doesn't consider roth as a location to adjust money too, from.
        """
        forced_regular_income = 0
        forced_capital_income = 0

        for acct in (self.starting.taxable, self.starting.ira):
            if acct.TAX_TYPE == REGULAR_TAX:
                forced_regular_income += acct.forced(self.age)
            else:
                forced_capital_income += acct.forced(self.age)

        if (
            capital_income < forced_capital_income
            and regular_income < forced_regular_income
        ):
            capital_income = forced_capital_income
            regular_income = forced_regular_income
        elif capital_income < forced_capital_income:
            diff = forced_capital_income - capital_income
            capital_income = forced_capital_income
            regular_income = max(regular_income - diff, 0)
        elif regular_income < forced_regular_income:
            diff = forced_regular_income - regular_income
            regular_income = forced_regular_income
            capital_income = max(capital_income - diff, 0)
        return capital_income, regular_income

    def _calculate_taxes(self, capital_gains, regular_income):
        est_fed_taxes = FED_TAX_TABLE.calculate_tax(regular_income)
        est_state_taxes = STATE_TAX_TABLE.calculate_tax(regular_income + capital_gains)
        est_capital_taxes = CAPITAL_TAX_TABLE.calculate_tax(
            capital_gains, regular_income
        )
        # print((est_fed_taxes, est_state_taxes, est_capital_taxes))
        taxes = est_fed_taxes + est_state_taxes + est_capital_taxes
        return taxes

    def taxes(self, expenses):
        """
        TODO: Return detailed tax information:
            * amount in each bracket for each type of tax
            * Marginal rate
            * total amount per tax type.
        """
        capital_gains, regular_income = self._calculate_taxable_income(expenses)
        taxes = self._calculate_taxes(capital_gains, regular_income)

        return taxes

    def __str__(self):
        return f"<Year age:{self.age}, net worth:{self.starting.net_worth}>"

    def _annual_adjustment(self, value) -> float:
        """Apply inflation adjusted growth to the passed in value"""
        return value * (1 + self.growth - self.inflation)

    def process_year(
        self, stock_growth: float, bond_growth: float, inflation: float
    ) -> "Year":
        """Do changes to transform starting values to ending values"""
        self.stock_growth = stock_growth
        self.bond_growth = bond_growth
        self.inflation = inflation
        taxable, ira, roth = (
            self._annual_adjustment(balance)
            for balance in self.starting.balances.values()
        )

        expenses = self.plan.pre_tax_expenses(self.age)
        print(f"Pre-tax Expenses: ${expenses:,}")
        taxes = expenses * 0.3
        for _ in range(7):
            taxes = self.taxes(expenses + taxes)
            # print(f"{taxes=}")
        total_expenses = expenses + taxes
        print(f"Taxes: ${taxes:,.2f}")
        print(f"Total Expenses: ${total_expenses:,.2f}")

        source = self.plan.income_source(self.age, self.starting)
        taxable -= total_expenses * source[0]
        ira -= total_expenses * source[1]
        roth -= total_expenses * source[2]

        taxable += self.starting.ira.forced(self.age)
        ira -= self.starting.ira.forced(self.age)

        ira -= self.plan.roth_conversion(self.age)
        roth += self.plan.roth_conversion(self.age)

        self.ending = Accounts(
            TaxableAccount(taxable),
            IRAAccount(ira),
            RothAccount(roth),
        )

        self.processed = True

    def get_next_year(self):
        """Create a Year object based off our ending values and age."""
        age = self.age + 1
        if not self.processed:
            raise ValueError("can only get next after this year has been processed")
        return self.__class__(age, *self.ending.balances.values())


#WAPP to print salary sheet
class Employee:
    def get(self):
        self.en = input('Enter the name of employee : ')
        self.no = int(input('Enter the no of employee : '))

class Dept(Employee):
    def input(self):
        self.deptnm = input('Enter the department of employee : ')
class Job:
    def put(self):
        self.desig = input('Enter the designation : ')
class Pay(Dept,Job):
    def calc(self):
        self.basic = int(input('Enter the basic salary : '))
        self.da = self.basic*60//100
        self.hra = self.basic*10//100
        print(self.en,'\n',self.no,'\n',self.deptnm,'\n',self.basic,'\n',self.da,'\n',self.hra,'\n',self.desig)

e = Pay()
e.get()
e.input()
e.put()
e.calc()


import sys

input = sys.stdin.readline

N = int(input())
num = [int(input()) for i in range(N)]
num.sort()
cnt = {}

for n in num:
    if n in cnt:
        cnt[n] += 1
    else:
        cnt[n] = 1

tmp = [k for k, v in cnt.items() if v == max(cnt.values())]

print(round(sum(num) / N))
print(num[N // 2])
print(tmp[0]) if len(tmp) == 1 else print(tmp[1])
print(num[-1] - num[0])


"""Escreva um código que pergunte o salário de um funcionario e de um aumento de
15% caso o salário for maior que 1250 reais, caso contrário 10%"""

wage = float(input("Me informe o salário\n"))
if wage > 1250:
    incr = 0.15 * wage
else:
    incr = 0.10 * wage
result = (wage + incr)

print(f"O aumento é de {incr} resultado é {result}!")


from __future__ import annotations
from itertools import islice
import re
from pathlib import Path
from typing import Optional, Set, Union, Iterator, List, TYPE_CHECKING, Tuple, Type
from logging import getLogger

from .base import HConfigBase
from .child import HConfigChild

if TYPE_CHECKING:
    from .host import Host

logger = getLogger(__name__)

class HConfig(HConfigBase):  # pylint: disable=too-many-public-methods

    """
    A class for representing and comparing Cisco configurations in a
    hierarchical tree data structure.

    Example usage:

    .. code:: python

        # Setup basic environment

        from hier_config import HConfig, Host
        import yaml

        options = yaml.safe_load(open('./tests/fixtures/options_ios.yml'))
        host = Host('example.rtr', 'ios', options)

        # Build HConfig object for the Running Config

        running_config_hier = HConfig(host=host)
        running_config_hier.load_from_file('./tests/fixtures/running_config.conf')

        # Build Hierarchical Configuration object for the Generated Config

        generated_config_hier = HConfig(host=host)
        generated_config_hier.load_from_file('./tests/fixtures/generated_config.conf')

        # Build Hierarchical Configuration object for the Remediation Config

        remediation_config_hier = running_config_hier.config_to_get_to(generated_config_hier)

        for line in remediation_config_hier.all_children():
            print(line.cisco_style_text())

    See:

        ./tests/fixtures/tags_ios.yml and ./tests/fixtures/options_ios.yml

        for test examples of options and tags.
    """

    def __init__(self, host: Host):
        super().__init__()
        assert hasattr(host, "hostname")
        assert hasattr(host, "os")
        assert hasattr(host, "hconfig_options")
        self.host = host
        self.parent = self
        self.real_indent_level = -1

        self.options.setdefault("negation", "no")
        self._logs: List[str] = []

    def __repr__(self) -> str:
        return f"HConfig(host={self.host})"

    def __hash__(self) -> int:
        return id(self)

    @property
    def root(self) -> HConfig:
        """returns the HConfig object at the base of the tree"""
        return self

    @property
    def options(self) -> dict:
        return self.host.hconfig_options

    @property
    def is_leaf(self) -> bool:
        """returns True if there are no children and is not an instance of HConfig"""
        return False

    @property
    def logs(self) -> List[str]:
        return self._logs

    @property
    def is_branch(self) -> bool:
        """returns True if there are children or is an instance of HConfig"""
        return True

    @property
    def _child_class(self) -> Type[HConfigChild]:
        return HConfigChild

    @property
    def tags(self) -> Set[Optional[str]]:
        """Recursive access to tags on all leaf nodes"""
        found_tags: Set[Optional[str]] = set()
        for child in self.children:
            found_tags.update(child.tags)
        return found_tags

    @tags.setter
    def tags(self, value: Set[str]) -> None:
        """Recursive access to tags on all leaf nodes"""
        for child in self.children:
            child.tags = value  # type: ignore

    def merge(self, other: HConfig) -> None:
        """Merges two HConfig objects"""
        for child in other.children:
            self.add_deep_copy_of(child, merged=True)

    def lineage(self) -> Iterator[HConfigChild]:
        """
        Yields the lineage of parent objects, up to but excluding the root
        """
        yield from ()

    def load_from_file(self, file_path: Union[str, Path]) -> None:
        """Load configuration text from a file"""
        with open(file_path) as file:  # pylint: disable=unspecified-encoding
            config_text = file.read()
        self.load_from_string(config_text)

    def load_from_string(self, config_text: str) -> None:
        """Create Hierarchical Configuration nested objects from text"""
        for sub in self.options["full_text_sub"]:
            config_text = re.sub(sub["search"], sub["replace"], config_text)

        self._load_from_string_lines(config_text)

        if self.host.os == "ios":
            self._remove_acl_remarks()
            self._add_acl_sequence_numbers()
            self._rm_ipv6_acl_sequence_numbers()

    def load_from_dump(self, dump: List[dict]) -> None:
        """Load an HConfig dump"""
        last_item: Union[HConfig, HConfigChild] = self
        for item in dump:
            # parent is the root
            if item["depth"] == 1:
                parent: Union[HConfig, HConfigChild] = self
            # has the same parent
            elif last_item.depth() == item["depth"]:
                parent = last_item.parent
            # is a child object
            elif last_item.depth() + 1 == item["depth"]:
                parent = last_item
            # has a parent somewhere closer to the root but not the root
            else:
                # last_item.lineage() = (a, b, c, d, e), new_item['depth'] = 2,
                # parent = a
                parent = next(
                    islice(last_item.lineage(), item["depth"] - 2, item["depth"] - 1)
                )
            # also accept 'line'
            # obj = parent.add_child(item.get('text', item['line']), force_duplicate=True)
            obj = parent.add_child(item["text"], force_duplicate=True)
            obj.tags = set(item["tags"])
            obj.comments = set(item["comments"])
            obj.new_in_config = item["new_in_config"]
            last_item = obj

    def dump(self, lineage_rules: Optional[List[dict]] = None) -> List[dict]:
        """Dump a list of loaded HConfig data"""
        if lineage_rules:
            children = self.all_children_sorted_with_lineage_rules(lineage_rules)
        else:
            children = self.all_children_sorted()

        output = []
        for child in children:
            output.append(
                {
                    "depth": child.depth(),
                    "text": child.text,
                    "tags": list(child.tags),
                    "comments": list(child.comments),
                    "new_in_config": child.new_in_config,
                }
            )

        return output

    def add_tags(self, tag_rules: list, strip_negation: bool = False) -> None:
        """
        Handler for tagging sections of Hierarchical Configuration data structure
        for inclusion and exclusion.
        """
        for rule in tag_rules:
            for child in self.all_children():
                if child.lineage_test(rule, strip_negation):
                    if "add_tags" in rule:
                        child.append_tags(rule["add_tags"])
                    if "remove_tags" in rule:
                        child.remove_tags(rule["remove_tags"])

    def depth(self) -> int:
        """Returns the distance to the root HConfig object i.e. indent level"""
        return 0

    def difference(self, target: HConfig) -> HConfig:
        """
        Creates a new HConfig object with the config from self that is not in target

        Example usage:
        whats in the config.lines v.s. in running config
        i.e. did all my configuration changes get written to the running config

        :param target: HConfig - The configuration to check against
        :return: HConfig - missing config additions
        """
        delta = HConfig(host=self.host)
        difference = self._difference(target, delta)
        # Makes mypy happy
        if not isinstance(difference, HConfig):
            raise TypeError
        return difference

    def config_to_get_to(
        self, target: HConfig, delta: Optional[HConfig] = None
    ) -> HConfig:
        """
        Figures out what commands need to be executed to transition from self to target.
        self is the source data structure(i.e. the running_config),
        target is the destination(i.e. generated_config)

        """
        if delta is None:
            delta = HConfig(host=self.host)

        root_config = self._config_to_get_to(target, delta)
        if not isinstance(root_config, HConfig):
            raise TypeError

        return root_config

    def add_ancestor_copy_of(
        self, parent_to_add: HConfigChild
    ) -> Union[HConfig, HConfigChild]:
        """
        Add a copy of the ancestry of parent_to_add to self
        and return the deepest child which is equivalent to parent_to_add
        """
        base: Union[HConfig, HConfigChild] = self
        for parent in parent_to_add.lineage():
            base = base.add_shallow_copy_of(parent)

        return base

    def set_order_weight(self) -> None:
        """Sets self.order integer on all children"""
        for child in self.all_children():
            for rule in self.options["ordering"]:
                if child.lineage_test(rule):
                    child.order_weight = rule["order"]

    def add_sectional_exiting(self) -> None:
        """
        Adds the sectional exiting text as a child
        """
        for child in self.all_children():
            for rule in self.options["sectional_exiting"]:
                if child.lineage_test(rule):
                    exit_line = child.get_child("equals", rule["exit_text"])
                    if exit_line is None:
                        exit_line = child.add_child(rule["exit_text"])

                    exit_line.tags = child.tags
                    exit_line.order_weight = 999

    def future(self, config: HConfig) -> HConfig:
        """
        EXPERIMENTAL - predict the future config after config is applied to self

        The quality of the this method's output will in part depend on how well
        the OS options are tuned. Ensuring that idempotency rules are accurate is
        especially important.
        """
        future_config = HConfig(host=self.host)
        self._future(config, future_config)
        return future_config

    def with_tags(self, tags: Set[str]) -> HConfig:
        """
        Returns a new instance containing only sub-objects
        with one of the tags in tags
        """
        new_instance = HConfig(self.host)
        result = self._with_tags(tags, new_instance)
        # Makes mypy happy
        if not isinstance(result, HConfig):
            raise ValueError
        return new_instance

    def all_children_sorted_by_tags(
        self, include_tags: Set[str], exclude_tags: Set[str]
    ) -> Iterator[HConfigChild]:
        """Yield all children recursively that match include/exclude tags"""
        for child in sorted(self.children):
            yield from child.all_children_sorted_by_tags(include_tags, exclude_tags)

    @staticmethod
    def _load_from_string_lines_end_of_banner_test(
        config_line: str, banner_end_lines: Set[str], banner_end_contains: List[str]
    ) -> bool:
        if config_line.startswith("^"):
            return True
        if config_line in banner_end_lines:
            return True
        if any([c in config_line for c in banner_end_contains]):
            return True
        return False

    # pylint: disable=too-many-locals,too-many-branches,too-many-statements
    def _load_from_string_lines(self, config_text: str) -> None:
        current_section: Union[HConfig, HConfigChild] = self
        most_recent_item: Union[HConfig, HConfigChild] = current_section
        indent_adjust = 0
        end_indent_adjust = []
        temp_banner = []
        banner_end_lines = {"EOF", "%", "!"}
        banner_end_contains: List[str] = []
        in_banner = False

        for line in config_text.splitlines():
            # Process banners in configuration into one line
            if in_banner:
                if line != "!":
                    temp_banner.append(line)

                # Test if this line is the end of a banner
                if self._load_from_string_lines_end_of_banner_test(
                    str(line), banner_end_lines, banner_end_contains
                ):
                    in_banner = False
                    most_recent_item = self.add_child("\n".join(temp_banner), True)
                    most_recent_item.real_indent_level = 0
                    current_section = self
                    temp_banner = []
                continue

            # Test if this line is the start of a banner and not an empty banner
            # Empty banners matching the below expression have been seen on NX-OS
            if line.startswith("banner ") and line != "banner motd ##":
                in_banner = True
                temp_banner.append(line)
                banner_words = line.split()
                try:
                    banner_end_contains.append(banner_words[2])
                    banner_end_lines.add(banner_words[2][:1])
                    banner_end_lines.add(banner_words[2][:2])
                except IndexError:
                    pass
                continue

            actual_indent = len(line) - len(line.lstrip())
            line = " " * actual_indent + " ".join(line.split())
            for sub in self.options["per_line_sub"]:
                line = re.sub(sub["search"], sub["replace"], line)
            line = line.rstrip()

            # If line is now empty, move to the next
            if not line:
                continue

            # Determine indentation level
            this_indent = len(line) - len(line.lstrip()) + indent_adjust

            line = line.lstrip()

            # Walks back up the tree
            while this_indent <= current_section.real_indent_level:
                current_section = current_section.parent

            # Walks down the tree by one step
            if this_indent > most_recent_item.real_indent_level:
                current_section = most_recent_item

            most_recent_item = current_section.add_child(line, True)
            most_recent_item.real_indent_level = this_indent

            for expression in self.options["indent_adjust"]:
                if re.search(expression["start_expression"], line):
                    indent_adjust += 1
                    end_indent_adjust.append(expression["end_expression"])
                    break
            if end_indent_adjust and re.search(end_indent_adjust[0], line):
                indent_adjust -= 1
                del end_indent_adjust[0]
        assert not in_banner, "we are still in a banner for some reason"

    def _add_acl_sequence_numbers(self) -> None:
        """
        Add ACL sequence numbers for use on configurations with a style of 'ios'
        """
        ipv4_acl_sw = "ip access-list"
        # ipv6_acl_sw = ('ipv6 access-list')
        if self.host.os in ["ios"]:
            acl_line_sw: Tuple[str, ...] = ("permit", "deny")
        else:
            acl_line_sw = ("permit", "deny", "remark")
        for child in self.children:
            if child.text.startswith(ipv4_acl_sw):
                sequence_number = 10
                for sub_child in child.children:
                    if sub_child.text.startswith(acl_line_sw):
                        sub_child.text = f"{sequence_number} {sub_child.text}"
                        sequence_number += 10

    def _rm_ipv6_acl_sequence_numbers(self) -> None:
        """If there are sequence numbers in the IPv6 ACL, remove them"""
        for acl in self.get_children("startswith", "ipv6 access-list "):
            for entry in acl.children:
                if entry.text.startswith("sequence"):
                    entry.text = " ".join(entry.text.split()[2:])

    def _remove_acl_remarks(self) -> None:
        for acl in self.get_children("startswith", "ip access-list "):
            for entry in acl.children:
                if entry.text.startswith("remark"):
                    acl.children.remove(entry)

    def _duplicate_child_allowed_check(self) -> bool:
        """Determine if duplicate(identical text) children are allowed under the parent"""
        return False


# Task: Below are the steps:
#
# ->Build a Number guessing game, in which the user selects a range.
# ->Let’s say User selected a range, i.e., from A to B, where A and B belong to Integer.
# ->Some random integer will be selected by the system and the user has to guess that integer in the minimum number of guesses

import random
import math

lower_bound = int(input("Enter lower bound: "))
upper_bound = int(input("Enter upper bound: "))

x = random.randint(lower_bound,upper_bound)
print('\n\tYou have only', round(math.log(upper_bound - lower_bound + 1, 2)), " Chances to guess the integer!\n")

count = 0

while count < math.log(upper_bound - lower_bound +1,2):
    count += 1
    guess = int(input("guess number:- "))

    if x == guess:
        print("Congratulations you dit it in ",count," try")
        break
    elif x > guess:
        print("You guessed too small!")
    elif x < guess:
        print("you guessed too high!")

if count >= math.log(upper_bound - lower_bound +1,2):
    print(f"The number is {x}")
    print("Better luck next time!")


data = [30,-50,20,8,16,15,10]

def selection_sort(arr):
    n = len(arr)
    for i in range(n-1):
        min_val = arr[i]
        min_index = i
        for j in range(i+1,n):
            if arr[j] < min_val:
                min_val = arr[j]
                min_index = j
        arr[i],arr[min_index] = arr[min_index], arr[i]

print(data)
selection_sort(data)
print(data)


#!/usr/bin/env python

from __future__ import with_statement

from setuptools import setup, find_packages

with open("README") as readme:
    documentation = readme.read()

setup(
    name="yatfs",
    version="0.4.0",
    description="FUSE-based torrent-backed filesystem",
    long_description=documentation,
    author="AllSeeingEyeTolledEweSew",
    author_email="allseeingeyetolledewesew@protonmail.com",
    url="http://github.com/AllSeeingEyeTolledEweSew/yatfs",
    license="Unlicense",
    packages=find_packages(),
    use_2to3=True,
    entry_points={
        "console_scripts": [
            "yatfs = yatfs.main:main"
        ]
    },
    install_requires=[
        "deluge-client-sync>=1.0.0",
        "better-bencode>=0.2.1",
        "PyYAML>=3.12",
	"llfuse>=1.3,<2.0",
	"btn>=1.0.0",
    ],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: End Users/Desktop",
        "License :: Public Domain",
        "Programming Language :: Python",
        "Topic :: Communications :: File Sharing",
        "Topic :: System :: Filesystems",
        "Topic :: System :: Networking",
        "Operating System :: POSIX :: Linux",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: POSIX :: BSD :: FreeBSD",
        "License :: Public Domain",
    ],
)


# passing a group of elements to a fun

def calculate(l):
    sum = 0
    for j in l:
        sum = sum+j
    print("sum of all values is:", sum)

lst = [int(i) for i in input("enter a list of numbers:").split()]
calculate(lst)


import chatchat as cc

# data.json:
# {
#     "xunfei": {
#         "app_id": "x",
#         "api_secret": "y",
#         "api_key": "z"
#     }
# }
completion = cc.xunfei.Completion('./data.json')
json = {
    "header": {
        "app_id": completion.jdata['app_id'],
    },
    "parameter": {
        "chat": {
            "domain": 'generalv2',
        }
    },
    "payload": {
        "message": {
            "text": [
                {"role": "user", "content": "请给我详细介绍一下相对论，字数不少于三百字！"}
            ]
        }
    }
}
r = completion.create(json, stream=True)


"""
Implements the game of Rock-Paper-Scissors!

History:
This classic game dates back to the Han Dynasty, over 2200 years ago.
The First International Rock-Paper-Scissors Programming Competition
was held in 1999 and was won by a team called "Iocaine Powder"

The Game:
Each player choses a move (simultaneously) from the choices:
rock, paper or scissors.
If they chose the same move the game is a tie. Otherwise:
rock beats scissors
scissors beats paper
paper beats rock.

In this program a human plays against an AI. The AI choses randomly
(we promise). The game is repeated N_GAMES times and the human gets
a total score. Each win is worth +1 points, each loss is worth -1
"""
import random

N_GAMES = 3

def main():

    for x in range(N_GAMES):
        player_move = human_choice()
        ai_move = ai_choice()

        winner = get_winner(ai_move, player_move)
        print(winner + " wins!")
        print('')
    points = score(winner)
    print("Score: " + str(points))

def print_welcome():
    print('Welcome to Rock Paper Scissors')
    print('You will play '+str(N_GAMES)+' games against the AI')
    print('rock beats scissors')
    print('scissors beats paper')
    print('paper beats rock')
    print('----------------------------------------------')
    print('')

def ai_choice():
    ran_number = random.randint(0,2)
    choices = ['scissors','paper','rock']
    ai_play = choices[ran_number]
    return ai_play

def human_choice():
    while True:
        player_choice = input("Please enter your choice: ")
        if is_valid_move(player_choice):
            return player_choice
        else:
            print("Invalid choice!")

def is_valid_move(move):
    if move == 'rock':
        return True
    elif move == 'scissors':
        return True
    elif move == 'paper':
        return True
    else:
        return False

def get_winner(ai_choice, player_choice):
    if ai_choice == player_choice:
        return "Noone"
    elif ai_choice == 'rock':
        if player_choice == 'scissors':
            return 'ai'
        return 'human'
    elif ai_choice == 'paper':
        if player_choice == 'rock':
            return 'ai'
        return 'human'
    elif ai_choice == 'scissors':
        if player_choice == 'paper':
            return 'ai'
        return 'human'

def score(winner):
    score = 0
    if winner == 'human':
        score += 1
    elif winner == 'ai':
        score -= 1
    else:
        score += 0
    return score

if __name__ == '__main__':
    main()


# Program 4
# Jennifer King
# October 2, 2017
# This program is a Caesar Cypher- encryption and decryption mode.
# The user provides the text to encrypt or decrypt, and the key
# that either defines the encryption result or successfully
# decrypts the text to the original message.

def encrypt():2
    # the function to encrypt a phrase using a Caesar cipher.
    # it takes the phrase and adds the chosen key to the
    # ascii value of each letter, changing the text.
plainText = input("Enter a phrase with no spaces, letters only:")
plainText = plainText.upper()
print(plainText)
    # user input of the phrase to encrypt
key = int(input("Enter the key value to encrypt phrase- 1 to 26: "))
    # user input of the key which is the amount to move the ascii value
code = "" # placeholder for the encrypted code
for ch in plainText: # this starts an iteration through the string
        ordValue = ord(ch)  # obtains the ascii value of each letter
        cipherValue = ordValue + key  # adds the key value to the ascii value
        if cipherValue > ord('Z'): # tests for result outside of alphabet
                   cipherValue = ord('A') + key - \
                   (ord('Z') - ordValue +1) # if the resulting value is past letter z
                                            # this returns the value back to a
        code += chr(cipherValue)  # places the encryption of each letter in the code placeholder
print(code)  # prints the resulting encrypted code

def decrypt():
    # the function to decrypt a phrase that used a Caesar cipher
    # it takes the coded text and subtracts the needed key to the
    # ascii value ot each letter, changing the text back to original
    codeText = input("Enter the coded text to decipher: ")
    codeText = codeText.upper()
    print(codeText)
    # user input of the coded text to decipher
    key = int(input("Enter the key to decipher the coded text, 1 to 26: "))
    # user input of the key needed to decipher the code
    code = "" # placeholder for the decrypted text
    for ch in codeText: # this starts an iteration through the string
        ordValue = ord(ch)  # obtains teh ascii value of each letter
        cipherValue = ordValue - key # subtracts the key from each ascii value
        if cipherValue < ord('A'):
          # tests for the result outside of the alphabet
            cipherValue = (ord('Z') - (key - ord('A') - (cipherValue + 1)))
                                    # if the resulting value is less than the letter a
                                    # this returns the value to the letter z
        code += chr(cipherValue)  # places the decrypted text of each letter in the code placeholder
    print(code) # prints the resulting decrypted code

def main():
    # the main function to select encryption or decryption
    userSelect = int(input("Enter 1 for encryption and 2 for decryption: "))
    result = ""  # placeholder for the result
    if userSelect == 1:
        result = encrypt() # sends the program to the encryption function
    if userSelect == 2:
        result = decrypt() # sends the program to the decryption function
main()


#!/usr/local/bin/python3

class SeqList(object):
	#__nodes = []	# 顺序表元素列表
	#__length = 0	# 顺序表长度
	#__maxsize = 10	# 顺序表最大长度

	def __init__(self):	# 构造函数
		print('Initiating list...')
		self.__length = 0			# 顺序表长度
		self.__maxsize = 10000		# 顺序表最大长度
		self.__nodes = [0] * self.__maxsize	# 顺序表元素列表
		print('Initiated.')

	def __del__(self):	# 析构函数
		print('Del list')
		del self

	def __repr__(self):	# 打印、转换
		#print(self.__nodes)
		if self.__length > 0:
			print('List start:')
			for index in range(0, self.__length):
				print('No.%d: %d' % (index + 1, self.__nodes[index]))
			return 'List ends.'
		else:
			return 'Empty list.'

	def __setitem__(self, index: int, value: int):	# 按索引赋值
		#print('setitem')
		if 0 <= index < self.__length:
			self.__nodes[index] = value
		else:
			print('Invalid index')
		return

	def __getitem__(self, index: int):	# 按索引取值
		return self.__nodes[index] if 0 <= index < self.__length else -1

	def __len__(self):	# 获取长度
		print('List length: ', end = '')
		return self.__length

	def isEmpty(self):		# 顺序表判空
		return True if self.__length <= 0 else False

	def isFull(self):		# 顺序表判满
		return True if self.__length >= self.__maxsize else False

	def insert(self, index: int, value: int):
		if index < 0 or index > self.__length:
			print('Invalid Index')
			return
		if self.__length > self.__maxsize:
			print('List is full')
			return

		for i in range(self.__length - 1, index - 1):
			self.__nodes[i + 1] = self.__nodes[i]

		self.__nodes[index] = value
		self.__length += 1

	def appendAtHead(self, value: int):
		if self.__length > self.__maxsize:
			print('List is full')
			return

		for i in range(self.__length - 1, 0 - 1):
			self.__nodes[i + 1] = self.__nodes[i]
		self.__nodes[0] = value
		self.__length += 1

	def append(self, value: int):
		if self.__length > self.__maxsize:
			print('List is full')
			return

		self.__nodes[self.__length] = value
		self.__length += 1

	def createSeqList(self, num: int):
		if num < 0:
			print('Invalid num')
			return

		for index in range(0, num):
			print('Please input No.%d element: ' % (index + 1), end = '')
			value = input()
			self.append(int(value))

		self.__length = num

	def removeAt(self, index: int):
		if index < 0 or index > self.__length:
			print('Invalid index')
			return
		for i in range(index, self.__length):
			self.__nodes[i - 1] = self.__nodes[i]
		self.__length -= 1

	def removeFor(self, value: int):
		index = 0
		while index < self.__length and self.__nodes[index] != value:
			index += 1
		for i in range(index, self.__length):
			self.__nodes[i] = self.__nodes[i + 1]
		self.__length -= 1

	def removeAll(self):
		for i in range(0, self.__length):
			self.__nodes[i] = 0
		self.__length = 0

	def removeAtHead(self):
		for i in range(1, self.__length):
			self.__nodes[i - 1] = self.__nodes[i]
		self.__length -= 1

def main():
	seqList = SeqList()
	for i in range(0, 10000 - 1):
		seqList.append(i)
	for i in range(0, 10000):
		seqList.insert(50, 99)
		seqList.removeAt(50)

	#print(seqList)
	#print(len(seqList))
	#print(seqList.isEmpty())
	#seqList.createSeqList(5)
	#print(seqList)
	#print(seqList)

if __name__ == '__main__':
	main()


import numpy as np
import matplotlib.pyplot as plt
from funcs import load_dataset
from Evaluation import Laplacian_scores
from IMAPCE import IMAPCE
from ContrastivePCA import Baselines
plt.rcParams['figure.dpi'] = 100

datasets = ["MNIST", "Fashion-MNIST", "UCI dataset", "MNIST and FMNIST", "synthetic", "adult"]
dataset_name = datasets[-1] # select a dataset from the list of datasets

num_samples = 30000
# num_samples = 'All'

input_data, labels_data = load_dataset(dataset_name, num_samples) # load a data to define its background samples
bg_data = 0*np.random.rand(input_data.shape[0], input_data.shape[1])

# synthetic data prior
# bg_data[:,0:4] = input_data[:, 0:4] #Synthetic dims 1-4

#UCI adult data priors
# bg_data[:, 2] = input_data[:, 2] # ethnicity
# bg_data[:, 3] = input_data[:, 3] #gender

# prior samples of MNIST with class '3'
# patterns_ind = np.where(labels_data == 3)[0]

# prior samples of MNIST with class 'FOLIAGE'
# patterns_ind = np.where(labels_data == 'FOLIAGE')[0] # example of background class in UCI dataset

# background_samples = input_data[patterns_ind]
background_samples = bg_data # assuming some prior knowledge

# if there are no prior data
# background_samples = None

# background data for MNIST and FMNIST data
# background_samples, _ = load_dataset('MNIST', 1000)

#
#
framework = IMAPCE(dataset_name = dataset_name,
                                                    num_samples = num_samples,
                                                    selection = "automatic",
                                                    clustering_algorithm = "DPGMM",
                                                    min_cluster_size = 400,
                                                    max_clusters_num = 5,
                                                    max_exploration_iterations = 25,
                                                    exploration = False,
                                                    background_samples = background_samples,
                                                    alpha = 1,
                                                    mu = 250,
                                                    seed = 5)
framework.Explore()

method = "original cPCA" # select a Baseline from Baselines_methods

framework = Baselines(dataset_name = dataset_name,
                      method = method,
                      num_samples = num_samples,
                      num_alphas = 40,
                      selection = "automatic",
                      clustering_algorithm = "DPGMM",
                      min_cluster_size = 400,
                      max_clusters_num = 5,
                      max_exploration_iterations = 25,
                      exploration = False,
                      background_samples = background_samples)

framework.Explore()
dataset_name = "synthetic"
labels = ''
# if dataset is synthetic or adult then the Laplacian scores plots are obtained by:
# labels = 'ethnicity' or 'gender' or 'gender-ethnicity'
Laplacian_scores(dataset_name, labels)