# coding: utf-8

from openerp import models, fields, api

class fill_questionnaire(models.TransientModel):
    """
    Fill a  questionnaire for a sale order line
    """
    _name = 'fill.questionnaire'
    _description = 'Fill a  questionnaire for a sale order line'

    #===========================================================================
    # COLUMNS
    #===========================================================================
    questionnaire_id = fields.Many2one('variants.questionnaire', string='Questionnaire', required=True, ondelete='cascade')
    sale_order_line_id = fields.Many2one('sale.order.line', string='Sale order line', required=False, ondelete='cascade')
    mo_id = fields.Many2one('mrp.manufacturingorder', string='Manufacturing order', required=False, ondelete='cascade')
    answer_ids = fields.One2many('fill.questionnaire.answer', 'fill_questionnaire_id',  string='Answers')
    last_replied_question_stack = fields.Char(string='Previous', default='', required=False)

    @api.multi
    def fill(self):
        first_question = self.questionnaire_id.question_ids.sorted(key=lambda r:r.sequence)[0]
        return {
                'type':'ir.actions.act_window',
                'res_model':'fill.questionnaire.answer',
                'target':'new',
                'views': [[False, 'form']],
                'context': {
                            'default_fill_questionnaire_id': self.id,
                            'default_question_id':first_question.id,
                            'default_question_label': first_question.label,
                            'default_help_text': first_question.help_text,
                            'default_dimension_limit_type': first_question.dimension_limit_type,
                            }
                }

    def save_all_answers(self):
        options, variants, dimensions = self.get_save_values()
        if self.sale_order_line_id:
            self.sale_order_line_id.parameter_ids.unlink()
            self.sale_order_line_id.option_lines_ids.unlink()
            self.sale_order_line_id.write({
                                           'option_lines_ids': [(0, 0, {'option_id':opt.id, 'price_unit':opt.price_unit}) for opt in options],
                                           'variant_category_value_ids': [(6, 0, [variant.id for variant in variants])],
                                           'parameter_ids': [(0,0,vals) for vals in dimensions],
                                           })
            #Recalcule du prix par rapport aux extra price
            self.sale_order_line_id._onchange_sec_uom_qty()

        else:
            self.mo_id.parameter_ids.unlink()
            self.mo_id.write({
                                           'option_ids': [(6, 0, [opt.id for opt in options])],
                                           'variant_value_ids': [(6, 0, [variant.id for variant in variants])],
                                           'parameter_ids': [(0,0,vals) for vals in dimensions],
                                           })
    def get_save_values(self):
        options = []
        variants = []
        dimensions = []
        for answer in self.answer_ids:
            question_type = answer.question_id.type
            if question_type == "option":
                options.append(answer.value_option)
            elif question_type == "variant":
                variants.append(answer.value_variant)
            elif question_type == "dimension":
                dimensions.append({
                                   'name': answer.question_id.dimension_type.name,
                                   'value': answer.value_dimension,
                                   'type_param_id': answer.question_id.dimension_type.id,
                                   'sale_order_line_id': self.sale_order_line_id
                                   })

        options_all = self.env['mrp.option']
        for option in options:
            options_all = options_all | option
        return (options_all, variants, dimensions)

class fill_questionnaire_answer(models.TransientModel):
    """
    Answer to a question
    """
    _name = 'fill.questionnaire.answer'
    _description = 'Answer to a question'

    @api.model
    def default_get(self, fields_list):
        res = super(fill_questionnaire_answer, self).default_get(fields_list=fields_list)
        question_id = self.env['variants.question'].browse(self.env.context['default_question_id'])
        if question_id.type == 'dimension' and question_id.dimension_limit_type == 'between':
            res['value_dimension'] = question_id.dimension_limit_min
        return res
    #===========================================================================
    # COLUMNS
    #===========================================================================
    fill_questionnaire_id = fields.Many2one('fill.questionnaire', string='Fill questionnaire', required=True, ondelete='cascade')
    question_id = fields.Many2one('variants.question', string='Question', required=True, ondelete='cascade')
    value_bool = fields.Boolean(string='Value', required=False)
    value_option = fields.Many2many('mrp.option')
    value_variant = fields.Many2one('variant.category.value')
    value_dimension = fields.Float(string="Value")
    value_dimension_selection = fields.Many2one('dimension.value', string="Value", domain="[('question_id', '=', default_question_id)]")
    question_label = fields.Char(related='question_id.label')
    help_text = fields.Char(related='question_id.help_text')
    dimension_limit_type = fields.Selection(related="question_id.dimension_limit_type")

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        name_type = {
                     'variant':'view_form_fill_questionnaire_answer_variant',
                     'option':'view_form_fill_questionnaire_answer_option',
                     'dimension':'view_form_fill_questionnaire_answer_dimension',
                     'boolean':'view_form_fill_questionnaire_answer_boolean',
                     }
        question_id = self.pool['variants.question'].browse(cr, uid, context['default_question_id'])
        name_for_type = name_type[question_id.type]
        view_id = self.pool['ir.ui.view'].search(cr, uid, [('name', '=', name_for_type)])
        return super(fill_questionnaire_answer, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)

    @api.multi
    def next(self):
        if self.question_id.type == 'variant' and not self.value_variant:
            raise Warning('You must fill the value')
        if len(self.fill_questionnaire_id.last_replied_question_stack):
            new_list = self.fill_questionnaire_id.last_replied_question_stack.split('|')
            new_list.append(unicode(self.id))
            self.fill_questionnaire_id.last_replied_question_stack = "|".join(new_list)
        else:
            self.fill_questionnaire_id.last_replied_question_stack = self.id
        next_question_ids = self.env['variants.question'].search([
                                                                  ('questionnaire_id', '=', self.fill_questionnaire_id.questionnaire_id.id),
                                                                  ('sequence', '>', self.question_id.sequence)
                                                                  ], order = 'sequence')

        def compare(a, b, op):
            if op == '=':
                return a == b
            elif op == '!=':
                return a != b
            elif op =='>':
                return b > a
            elif op == '<':
                return a < b
            elif op == 'in' and b and len(b) > 0:
                return a in b
            elif op == 'not in' and b and len(b) > 0:
                return a not in b
            else:
                return False

        next_question = None
        for question in next_question_ids:
            if not question.condition_question:
                next_question = question
                break
            else:
                condition_question_answer = self.env['fill.questionnaire.answer'].search([
                                                                                ('question_id', '=', question.condition_question.id),
                                                                                ('fill_questionnaire_id', '=', self.fill_questionnaire_id.id)])
                if compare(question.get_condition_value(), condition_question_answer.get_value(), question.condition_operator):
                    next_question = question
                    break

        # no next question, questionnaire is finished
        if not next_question:
            self.fill_questionnaire_id.save_all_answers()
            return {
                    'type': 'ir.actions.act_window_close',
                    }
        return {
                'type':'ir.actions.act_window',
                'res_model':'fill.questionnaire.answer',
                'target':'new',
                'views': [[False, 'form']],
                'context': {
                            'default_fill_questionnaire_id': self.fill_questionnaire_id.id,
                            'default_question_id': next_question.id,
                            'default_question_label': next_question.label,
                            'default_help_text': next_question.help_text,
                            'default_dimension_limit_type': next_question.dimension_limit_type,
                            },
                }

    @api.multi
    def previous(self):
        prev_reply = int(self.fill_questionnaire_id.last_replied_question_stack.split('|')[-1])
        prev_reply = self.browse(prev_reply)
        prev_question = prev_reply.question_id
        if prev_question:
            fill_questionnaire_id = self.fill_questionnaire_id
            fill_questionnaire_id.last_replied_question_stack = "|".join(fill_questionnaire_id.last_replied_question_stack.split('|')[:-1])
            prev_reply.unlink()
            self.unlink()
            return {
                    'type':'ir.actions.act_window',
                    'res_model':'fill.questionnaire.answer',
                    'target':'new',
                    'views': [[False, 'form']],
                    'context': {
                                'default_fill_questionnaire_id': fill_questionnaire_id.id,
                                'default_question_id': prev_question.id,
                                'default_question_label': prev_question.label,
                                'default_help_text': prev_question.help_text,
                                'default_dimension_limit_type': prev_question.dimension_limit_type,
                                },
                    }
        else:
            return {
                    'type':'ir.actions.act_window_noclose',
                    }

    def get_value(self):
        question_type = self.question_id.type
        if question_type == 'boolean':
            return self.value_bool
        elif question_type == 'dimension':
            return self.value_dimension
        elif question_type == 'variant':
            return self.value_variant
        elif question_type == 'option':
            return self.value_option

    @api.onchange('value_dimension')
    def _onchange_value_dimension(self):
        question = self.env['variants.question'].browse(self.env.context['default_question_id'])
        if question.dimension_limit_type == 'between' and (self.value_dimension < question.dimension_limit_min or self.value_dimension > question.dimension_limit_max):
            return {'warning':{'title':'Warning', 'message':'{} < Value < {}'.format(question.dimension_limit_min, question.dimension_limit_max)}}
        elif question.dimension_limit_type == 'selection' and self.value_dimension:
            possible_values = [x.value for x in question.dimension_possible_values]
            if self.value_dimension not in possible_values:
                return {'warning':{'title':'Warning', 'message':'Value in '.format(possible_values)}}
            else:
                return

    @api.onchange('value_dimension_selection')
    def _onchange_value_dimension_selection(self):
        if self.question_id.dimension_limit_type == 'selection':
            self.value_dimension = float(self.value_dimension_selection.value)


import os
import webbrowser
import subprocess
import pyttsx3
import speech_recognition as sr
import random
import datetime

engine =pyttsx3.init()
voices = engine.getProperty('voices')
rate = engine.getProperty('rate')
engine.setProperty('rate', 170)
r=sr.Recognizer()

random.seed()
#asking to continue dictionary///////
asktocont={1:"Do you want to continue?", 2:"Something else?", 3:"Maybe, you want something?",4:"Please, say no, i want  to go!"}
amount_asktocont=0
for i in asktocont:
	amount_asktocont+=1

#GREETINGS //////////
greetings={1:"Hello, my name is Hans!",2:"Hi, Hans is here!",3:"Welcome to my kingdom,buddy!",4:"Greetings, my boss!"}
#amount of frases////////////////////
amount = 0
for i in greetings:
	amount+=1
num = random.randint(1,amount)
if num==1:
	engine.say(greetings[1])
	engine.runAndWait()
if num ==2:
	engine.say(greetings[2])
	engine.runAndWait()
if num ==3:
	engine.say(greetings[3])
	engine.runAndWait()
if num ==4:
	engine.say(greetings[4])
	engine.runAndWait()
ans = "yes"
while ans == "yes":

		#LISTENING///////////
	with sr.Microphone() as source:
		r.adjust_for_ambient_noise(source)
		engine.say("What can i do for you?")
		engine.runAndWait()
		print("What can i do for you?: ")
		audio= r.listen(source)
	try:
		command=r.recognize_google(audio)
		engine.say(command)
		engine.runAndWait()
		print(command)
	except sr.UnknownValueError:
		print("Could not undertand audio")
	except sr.RequestError as e:
		print("Could not request results; {0}".format(e))

		#COMMANDS////////////////////////////////////

		#what can u do////////////
	if command == "commands" or command == "show the commands" or command == "command" or command == "what can you do" or command == "what do you can":
		print("Aviable commands:")
		engine.say("Here you can see the avaible commands.")
		engine.runAndWait()
		print("Open the browser")
		print("Open link")
		print("Search the web")
		print("Open telegram")
		print("Tell me the date")
		print("What is the time")
		print("Today or this day")

		#date/////////////////
	if command == "tell me the date" or command == "date" or command == "the date":
		datevar = datetime.date.today().strftime("%B %d, %Y")
		print(datevar)
		engine.say(datevar)
		engine.runAndWait()

		#time/////////////////////
	if command  == "what is the time" or command == "time" or command == "show time":
		datevar = datetime.datetime.now().strftime("%I:%M%p")
		print(datevar)
		engine.say(datevar)
		engine.runAndWait()

		#everything about this day/////////////
	if command == "today" or command == "this day":
		datevar = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
		print(datevar)
		engine.say("Today is "); engine.say(datevar)
		engine.runAndWait()

		#open the browser///////////////////
	if command == "open the browser" or command == "browser":
		engine.say("Okay, my boss!")
		engine.runAndWait()
		webbrowser.open('http://google.com')

		#open the link////////////////////////
	if command == "open link" or command == "link":
		link = input("Enter your link: ")
		webbrowser.open(link)

		#serch the web////////////////////////
	if command == "search the web" or command == "search" or command == "web" or command == "search web":
		with sr.Microphone() as source:
			r.adjust_for_ambient_noise(source)
			engine.say("What do you want to search?")
			engine.runAndWait()
			print("What do you want to search?")
			audio= r.listen(source)
		try:
			whattosearch = r.recognize_google(audio)
			engine.say(whattosearch)
			engine.runAndWait()
			print(whattosearch)
		except sr.UnknownValueError:
			print("Could not undertand audio")
		except sr.RequestError as e:
			print("Could not request results; {0}".format(e))
		url = "https://www.google.com.ua/search?q={0}".format(whattosearch)
		webbrowser.open(url)

		#open telegram/////////////////
	if command == "open telegram" or command == "telegram":
		os.system("telegram-desktop")

	#do you want to continue////////////////
	with sr.Microphone() as source:
		r.adjust_for_ambient_noise(source)
		#choosing what to say/////////////4
		num=random.randint(1,amount_asktocont)
		engine.say(asktocont[num])
		engine.runAndWait()
		print(asktocont[num])
		audio= r.listen(source)
	try:
		ans=r.recognize_google(audio)
		print(ans)
	except sr.UnknownValueError:
		print("Could not undertand audio")
		break
	except sr.RequestError as e:
		print("Could not request results; {0}".format(e))

#ENDING////////////////
endings = {1:"Goodbye, boss, i love you!", 2:"See you later!", 3:"Have a nice day", 4:"So, i can do everything i want?"}
#amount/////////
amount = 0
for i in endings:
	amount+=1
num = random.randint(1,amount)
engine.say(endings[num])
engine.runAndWait()


# -*- coding: utf-8 -*-
"""
Created on Sat Apr 10 03:09:12 2021

@author: Alice
"""

import os
import dash
import dash_table
import json
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from plotly.offline import plot
from utils import diff_dashtable, get_table_data, update_table_data

app = dash.Dash(__name__)
app.title = 'MerryDining - Restaurant Portal'
statuses = ['empty', 'reserved', 'occupied']
diets = ['none', 'vegan', 'vegetarian', 'gluten-free', 'kosher', 'halal']
allergies = ['none', 'dairy', 'peanuts', 'soy', 'shellfish']
def layout_function():
    return html.Div([
    html.Div(id='topbar', children=[html.Img(id='icon', src='/assets/favicon.ico'),
                                    html.H5("MerryDining", 'title')]),
    dcc.Graph(id='choropleth'),

    dash_table.DataTable(
        id='restaurant-table',
        columns=[{"name": ["Table ID"], "id": "tableid"},
                 {"name": ["Status"], "id": "status", "presentation": "dropdown"},
                 {"name": ["Diet"], "id": "diet", "presentation": "dropdown"},
                 {"name": ["Allergy"], "id": "allergy", "presentation": "dropdown"}],
        editable=True,
        data=get_table_data().to_dict(orient='records'),
        dropdown={
            'status': {'options': [{'label': i, 'value': i} for i in statuses],
                     'clearable':False},
            'diet': {'options': [{'label': i, 'value': i} for i in diets],
                     'clearable':False},
            'allergy': {'options': [{'label': i, 'value': i} for i in allergies],
                        'clearable':False}
        }
    ),

    html.Br(),
    dcc.Store(id="diff-store"),
    html.Div(id="data-diff")
])

app.layout = layout_function

# track changes in restaurant table
@app.callback(
    [Output("diff-store", "data"),
     Output("data-diff", "children")],
    [Input("restaurant-table", "data_timestamp")],
    [State("restaurant-table", "data"),
     State("restaurant-table", "data_previous"),
     State("diff-store", "data")],
)
def capture_diffs(ts, data, data_previous, diff_store_data):
    if ts is None:
        raise PreventUpdate
    diff_store_data = diff_store_data or {}

    changed_rows = diff_dashtable(data, data_previous, 'tableid')
    diff_store_data[ts] = changed_rows
    if diff_store_data:
        response = []
        for row in changed_rows:
            response = update_table_data(row['tableid'], row['status'], row['diet'], row['allergy'])
        return diff_store_data, str(response)#str(changed_rows)

    return diff_store_data, "No Changes to DataTable"

# create and display restaurant map
@app.callback(
    Output(component_id="choropleth", component_property="figure"),
    Input("restaurant-table", "data"))
def display_choropleth(input_table):
    with open(os.path.join(os.path.dirname(__file__), 'map_full.geojson'), "r") as f:
        geo_world = json.load(f)

    # get data directly from table
    df = pd.DataFrame.from_dict(input_table)

    colorscales = [[0.0, 'rgb(255, 232.05, 214.2)'],
                   [0.5, 'rgb(255, 181.0, 130.1)'],
                   [1.0, 'rgb(255, 132.6, 51.0)']]
    tickdict = {"empty": 0.0, "reserved": 0.9, "occupied": 2.0}
    hover_template_choro="Table %{customdata[0]}" \
                         "<extra>Status: %{customdata[1]}
" \
                         "Diet: %{customdata[2]}
"\
                         "Allergies: %{customdata[3]}</extra>"

    df["status_z"] = df["status"].replace(tickdict)

    # Create figure
    fig = go.Figure(go.Choropleth(geojson=geo_world,
                                  locations=df['tableid'],
                                  z=df['status_z'],
                                  zmin=0,
                                  zmax=2,
                                  customdata=np.stack(([df['tableid'], df['status'], df['diet'], df['allergy']]), axis=-1),
                                  hovertemplate=hover_template_choro,
                                  text=df['tableid'],
                                  colorscale=colorscales,
                                  colorbar_tickvals=list(tickdict.values()),
                                  colorbar_ticktext=list(tickdict.keys()),
                                  colorbar_tickmode="array",
                                  colorbar_x=-0.03,
                                  colorbar_y=0,
                                  colorbar_yanchor="bottom",
                                  colorbar_thickness=10,
                                  colorbar_tickfont_family="Poppins",
                                  colorbar_title_text="Table Status",
                                  colorbar_title_font_family="Poppins"))
    fig.update_layout(dragmode=False,
                      font_family="Poppins",
                      margin={"r":0,"t":0,"l":0,"b":0})
    fig.update_geos(center=dict(lon=0.002, lat=0.002),
                    lataxis_range=[-0.005, 0.006],
                    lonaxis_range=[-0.005, 0.006],
                    visible=False)

    df_dots = pd.json_normalize(geo_world['features'])
    hover_template_scatter="Table %{customdata[0]}
" \
                         "Status: %{customdata[1]}
" \
                         "Diet: %{customdata[2]}
"\
                         "Allergies: %{customdata[3]}"
    # add dietary dots
    diet_colors = {'halal': '#76ac49', 'vegan': '#faff00',
                   'vegetarian': '#aeff6a', 'kosher':'#589ad6', 'gluten-free': '#fc620b'}
    for diet in list(diet_colors.keys()):
        df_dots_diet = df_dots[df['diet'].str.contains(diet)]
        df_diet = df[df['diet'].str.contains(diet)]
        fig.add_trace(go.Scattergeo(
            lon = df_dots_diet['properties.center'].apply(lambda x: x[0])+0.0001,
            lat = df_dots_diet['properties.center'].apply(lambda x: x[1]),
            name = diet,
            marker = dict(
                size = 20,
                opacity = 0.7,
                color = diet_colors[diet]),
            customdata=np.stack(([df_diet['tableid'], df_diet['status'],
                                  df_diet['diet'], df_diet['allergy']]), axis=-1),
            hovertemplate=hover_template_scatter))
    # add allergy dots
    allergy_colors = {'dairy': '#4ff4ff', 'peanuts': '#fff84f', 'soy': '#a9a53b',
                      'shellfish': '#942288'}
    for allergy in list(allergy_colors.keys()):
        df_dots_allergy = df_dots[df['allergy'].str.contains(allergy)]
        df_allergy = df[df['allergy'].str.contains(allergy)]
        fig.add_trace(go.Scattergeo(
            lon = df_dots_allergy['properties.center'].apply(lambda x: x[0])-0.0001,
            lat = df_dots_allergy['properties.center'].apply(lambda x: x[1]),
            name = allergy,
            marker = dict(
                size = 20,
                opacity = 0.7,
                color = allergy_colors[allergy]),
            customdata=np.stack(([df_allergy['tableid'], df_allergy['status'],
                                  df_allergy['diet'], df_allergy['allergy']]), axis=-1),
            hovertemplate=hover_template_scatter))
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)


import sys
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from argparse import ArgumentParser

from clair.utils import setup_environment

def plot_tensor(ofn, XArray):
    plot = plt.figure(figsize=(15, 8))

    plot_min = -30
    plot_max = 30
    plot_arr = ["A+", "C+", "G+", "T+", "A-", "C-", "G-", "T-"]

    plt.subplot(4, 1, 1)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 0].transpose(), vmin=0, vmax=plot_max, interpolation="nearest", cmap=plt.cm.hot)
    plt.colorbar()

    plt.subplot(4, 1, 2)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 1].transpose(), vmin=plot_min, vmax=plot_max, interpolation="nearest", cmap=plt.cm.bwr)
    plt.colorbar()

    plt.subplot(4, 1, 3)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 2].transpose(), vmin=plot_min, vmax=plot_max, interpolation="nearest", cmap=plt.cm.bwr)
    plt.colorbar()

    plt.subplot(4, 1, 4)
    plt.xticks(np.arange(0, 33, 1))
    plt.yticks(np.arange(0, 8, 1), plot_arr)
    plt.imshow(XArray[0, :, :, 3].transpose(), vmin=plot_min, vmax=plot_max, interpolation="nearest", cmap=plt.cm.bwr)
    plt.colorbar()

    plot.savefig(ofn, dpi=300, transparent=True, bbox_inches='tight')
    plt.close(plot)

def create_png(args):
    f = open(args.array_fn, 'r')
    array = f.read()
    f.close()
    import re
    array = re.split("\n", array)
    array = [x for x in array if x]
    print(array)

    splitted_array = []
    for i in range(len(array)):
        splitted_array += re.split(",", array[i])

    print("splitted array length")
    print(len(splitted_array))
    print(splitted_array[0])
    # for i in range(len(splitted_array)):
    #     splitted_array[i] = int(splitted_array[i])

    XArray = np.array(splitted_array, dtype=np.float32).reshape((-1, 33, 8, 4))
    XArray[0, :, :, 1] -= XArray[0, :, :, 0]
    XArray[0, :, :, 2] -= XArray[0, :, :, 0]
    XArray[0, :, :, 3] -= XArray[0, :, :, 0]

    _YArray = np.zeros((1, 16))
    varName = args.name
    print("Plotting %s..." % (varName), file=sys.stderr)

    # Create folder
    if not os.path.exists(varName):
        os.makedirs(varName)

    # Plot tensors
    plot_tensor(varName+"/tensor.png", XArray)

def ParseArgs():
    parser = ArgumentParser(
        description="Visualize tensors and hidden layers in PNG")

    parser.add_argument('--array_fn', type=str, default="vartensors",
                        help="Array input")

    parser.add_argument('--name', type=str, default=None,
                        help="output name")

    args = parser.parse_args()

    if len(sys.argv[1:]) == 0:
        parser.print_help()
        sys.exit(1)

    return args

def main():
    args = ParseArgs()
    setup_environment()
    create_png(args)

if __name__ == "__main__":
    main()


"""
Stacked Autoencoder
"""
from collections import OrderedDict
import numpy as np

import tensorflow as tf
from tensorflow.contrib import layers, framework

def show_reconstructed_digits(X, outputs, model_path = None, n_test_digits = 2):
    with tf.Session() as sess:
        if model_path:
            saver.restore(sess, model_path)
        X_test = mnist.test.images[:n_test_digits]
        outputs_val = outputs.eval(feed_dict={X: X_test})

    fig = plt.figure(figsize=(8, 3 * n_test_digits))
    for digit_index in range(n_test_digits):
        plt.subplot(n_test_digits, 2, digit_index * 2 + 1)
        plot_image(X_test[digit_index])
        plt.subplot(n_test_digits, 2, digit_index * 2 + 2)
        plot_image(outputs_val[digit_index])

class tfStackedAutoEncoder(object):
    """
    Train a Stacked AE in a single graph, using multiple "phases"
    """

    def __init__(self, h_layers, lr=1e-2, l2_pen=1e-4, nb_epoch=100,
            batch_size=None, act_fn='elu'):
        self.h_layers = h_layers
        self.lr = lr
        self.nb_epoch = nb_epoch
        self.batch_size = batch_size
        self.l2_pen = l2_pen

        if act_fn == 'elu':
            self.act_fn=tf.nn.elu
        elif act_fn == 'relu':
            self.act_fn = tf.nn.relu
        else:
            self.act_fn = act_fn

        self.reg_fn = layers.l2_regularizer(l2_pen)
        self.init_fn = layers.variance_scaling_initializer()

    def fit(self, X):
        X_data = X

        X = tf.placeholder(tf.float32, shape=(None,X_data.shape[-1]))

        # create weights/bias dictionary
        layer_shapes = [X_data.shape[1]] + self.h_layers + [X_data.shape[1]]
        w_dict = OrderedDict()
        b_dict = OrderedDict()
        with tf.name_scope('vars'):
            for i in range(len(layer_shapes)-1):
                w_name = 'w_%i'%i
                b_name = 'b_%i'%i
                w_shape = (layer_shapes[i],layer_shapes[i+1])
                w_dict[w_name] = tf.Variable(self.init_fn(w_shape), dtype=tf.float32, name=w_name)
                b_shape = layer_shapes[i+1]
                b_dict[b_name] = tf.Variable(tf.zeros(b_shape), dtype=tf.float32, name=b_name)

        # create layers
        layers = {}
        layers[0] = X
        with tf.name_scope('layers'):
            for i, (w,b) in enumerate(zip(w_dict.values(),b_dict.values())):
                if i < len(w_dict)-1:
                    layers[i+1] = self.act_fn(tf.matmul(layers[i],w)+b)
                else:
                    layers[i+1] = tf.matmul(layers[i],w)+b

        # create phases
        mid_idx = int((len(w_dict)-1) / 2)
        n_phases = mid_idx
        phase_training_ops = []

        for phase_idx in range(n_phases):
            pass

if __name__=='__main__':
    tf.reset_default_graph()
    from keras.datasets.mnist import load_data
    (xtrain,xtest),(ytrain,ytest) = load_data()
    from sklearn.preprocessing import StandardScaler, MinMaxScaler
    xtrain = MinMaxScaler((0,1)).fit_transform(xtrain.astype('float64').reshape(xtrain.shape[0],-1))

    h_layers = [300, 150, 300]
    act_fn = 'elu'
    lr = 1e-2
    l2_pen = 1e-4
    sae = tfStackedAutoEncoder(h_layers=h_layers)
    layers = sae.fit(xtrain)


from insertion import *
from connexion import *
from affichage import *
from suppression import *
from time import sleep

def main():
    """Fonction pricipale"""
    #Connexion à la BDD
    conn, cur = connexion()
    continuer = True
    # Boucle principale
    while continuer:
        afficheMenuPrincipal()
        #Demande du choix de l'utilisateur
        reponse = int(input("Votre choix : "))
        #Tant que la reponse n'est pas valide
        while reponse < 1 or reponse > 9:
            print("Veuillez entrer un numero correct.")
            reponse = int(input("Votre choix : "))

        #Si l'utilisateur choisit l'option d'ajout
        if reponse == 1:
            afficheMenuInsertion()
            repInsertion = int(input("Votre choix : "))
            while repInsertion < 1 or repInsertion > 3:
                print("Veuillez entrer un numero correct.")
                repInsertion = int(input("Votre choix : "))
            if repInsertion == 1:
                insererClient(conn, cur)
                sleep(2)
            elif repInsertion == 2:
                afficheMenuInsertionCompte()
                repInsertionCompte = int(input("Votre choix : "))
                while repInsertionCompte < 1 or repInsertionCompte > 4:
                    print("Veuillez entrer un numero correct.")
                    repInsertionCompte = int(input("Votre choix : "))
                if repInsertionCompte == 1:
                    insererCompteCourant(conn, cur)
                    sleep(2)
                elif repInsertionCompte == 2:
                    insererCompteRevolving(conn, cur)
                    sleep(2)
                elif repInsertionCompte == 3:
                    insererCompteEpargne(conn, cur)
                    sleep(2)
            elif repInsertion == 3:
                insererAppartenir(conn, cur)
                sleep(2)
            else:
                insererOperation(conn, cur)
                sleep(2)
        #Si l'utilisateur choisit l'option de modification
        elif reponse == 2:
            afficheMenuModification()
            repModification = int(input("Votre choix : "))
            while repModification < 1 or repModification > 2:
                print("Veuillez entrer un numero correct.")
                repModification = int(input("Votre choix : "))
            if repModification == 1:
                UpdateClient(conn, cur)
            else:
                UpdateCompte(conn, cur)

        #Si l'utilisateur choisit l'option de suppression
        elif reponse == 3:
            afficheMenuSuppression()
            repSuppresion = int(input("Votre choix : "))
            while repSuppresion < 1 or repSuppresion > 3:
                print("Veuillez entrer un numero correct.")
                repSuppresion = int(input("Votre choix : "))
            if repSuppresion == 1:
                supprimerClient(conn, cur)
                sleep(2)
            elif repSuppresion == 2:
                supprimerCompte(conn, cur)
                sleep(2)
            else:
                supprimeAppartenance(conn, cur)
                sleep(2)
        # Affichage de la BDD
        elif reponse == 4:
            dico_tables = {"1" : "Client", "2" : "Compte", "3" : "Appartenir", "4" : "Operation", "5" : "MinMaxMois"}
            afficherMenuAffichage()
            repAffiche = input("Entrez le numero correspondant à une table : ")
            while (repAffiche not in [str(num) for num in range(1,6)]):
                repAffiche = input("Numero invalide. Veuillez entrer un numero de table valide : ")
            nb_resultats = int(input("Nombre de résultats souhaités : "))
            while nb_resultats < 0:
                nb_resultats = int(input("Nombre de résultats souhaités : "))
            afficherTable(cur, dico_tables[repAffiche], nb_resultats)
            sleep(2)
        elif reponse == 5:
            print("*** Solde d'un compte ***")
            date_creation = input("Date de creation du compte (YYYY-MM-DD) : ")
            #Montant d'un compte
            solde = getSoldeCompte(cur, date_creation)
            if solde is None:
                #Compte inexistant
                print("Aucun compte cree à cette date.")
            else:
                print(f"Le solde du compte est de : {solde}")
            sleep(2)
        #Si l'utilisateur veut savoir le nombre d'operation faite sur un compte
        elif reponse == 6:
            print("*** Nombre des cheques emis par un client ***")
            numero = input("Numero de telephone du client : ")
            nombreChequeEmis = getNbCheque(cur, numero, "E")
            #Si le numero de telephone ne correspond à aucun numero de la BDD
            if nombreChequeEmis is None:
                print("Aucun compte avec ce numero de telephone")
            else:
                print(f"Le nombre de cheques emis par ce client est de : {nombreChequeEmis}")
            sleep(2)
        #Historique des opérations
        elif reponse == 7:
            print("*** Historique des opérations effectuées par un client ***")
            numero = input("Numéro de téléphone du client : ")
            date1 = input("Date de début de période (YYYY-MM-DD) : ")
            date2 = input("Date de fin de période (YYYY-MM-DD) : ")
            getHistoriqueOperation(cur, numero, date1, date2)
            sleep(2)
        elif reponse == 8:
            print("*** Somme des montants des opérations effectuées par un client ***")
            numero = input("Numéro de téléphone du client : ")
            total = getSommeTotale(cur, numero)
            if total is None:
                print("Le client n'a jamais effectué d'opérations.")
            else:
                print(f"Le client a effectué des opérations pour un montant total de {total} €.")
            sleep(2)
        #Si l'utilisateur souhaite quitter le programme
        else:
            print("Vous allez quitter le programme.")
            continuer = False
            close(conn)
            sleep(2)

if __name__ == "__main__":
    main()


from itertools import chain

from django.contrib.auth.models import User
from django import forms
from django.db.models import CharField, Value

from .models import Review, Ticket, UserFollows

def get_users_viewable_reviews(user: User):
    # Get it own reviews
    user_reviews = Review.objects.filter(user__username=user.username)
    user_reviews = user_reviews.annotate(
        content_type=Value('REVIEW', CharField()))
    return user_reviews

def get_users_viewable_tickets(user: User):
    # Get it own tickets
    user_tickets = Ticket.objects.filter(user__username=user.username)
    user_tickets = user_tickets.annotate(
        content_type=Value('TICKET', CharField()))
    return user_tickets

def get_followed_users_viewable_reviews(user: User):
    # Get reviews of followed users
    users_follow = UserFollows.objects.filter(user__username=user.username)
    followers_reviews = Review.objects.none()
    for user_follow in users_follow:
        user_follow_review = Review.objects.filter(
            user__username=user_follow.followed_user.username)
        user_follow_review = user_follow_review.annotate(
            content_type=Value('REVIEW', CharField()))
        followers_reviews = chain(followers_reviews, user_follow_review)
    return followers_reviews

def get_followed_users_viewable_tickets(user: User):
    # Get tickets of followed users
    users_follow = UserFollows.objects.filter(user__username=user.username)
    followers_tickets = Ticket.objects.none()
    for user_follow in users_follow:
        user_follow_ticket = Ticket.objects.filter(
            user__username=user_follow.followed_user.username)
        user_follow_ticket = user_follow_ticket.annotate(
            content_type=Value('TICKET', CharField()))
        followers_tickets = chain(followers_tickets, user_follow_ticket)
    return followers_tickets

def get_followed_users(user: User):
    # Get the list of all users followed by user
    users_follow = UserFollows.objects.filter(user=user)
    followed = []
    for user_follow in users_follow:
        followed.append(user_follow.followed_user)
    return followed

def get_users_subscriber(user: User):
    # Get the list of all users which follow the user
    users_follow = UserFollows.objects.filter(followed_user=user)
    followers = []
    for user_follow in users_follow:
        followers.append(user_follow.user)
    return followers

def get_user_by_id(id: str):
    return User.objects.filter(id=id)

def get_user_by_name(username: str):
    return User.objects.filter(username=username)

def get_users_by_name(username: str):
    return User.objects.filter(username__icontains=username)

def get_ticket_by_pk(pk: str):
    ticket = Ticket.objects.filter(pk=pk)
    ticket = ticket.annotate(
        content_type=Value('REVIEW', CharField()))
    return ticket

def get_review_by_pk(pk: str):
    review = Review.objects.filter(pk=pk)
    review = review.annotate(
        content_type=Value('REVIEW', CharField()))
    return review

def get_all_reviews():
    # Get all reviews
    reviews = Review.objects.all()
    reviews = reviews.annotate(
        content_type=Value('REVIEW', CharField()))
    return reviews

def save_ticket(request, form: forms):
    ticket = Ticket()
    ticket.title = form.cleaned_data["title"]
    ticket.description = form.cleaned_data["description"]
    ticket.user = request.user
    ticket.image = request.FILES.get('image_download', None)
    ticket.save()
    return ticket

def save_updated_ticket(request, form: forms, ticket: Ticket):
    ticket.title = form.cleaned_data["title"]
    ticket.description = form.cleaned_data["description"]
    image = request.FILES.get('image_download', None)
    if image is not None:
        ticket.image = image
    ticket.save()
    return ticket

def delete_ticket(ticket: Ticket):
    ticket.delete()

def save_review(request, form: forms):
    review = Review()
    if 'ticket_pk' in request.POST:
        review.ticket = get_ticket_by_pk(request.POST.get('ticket_pk'))[0]
        review.ticket.already_reviewed = True
    else:
        review.ticket = save_ticket(request, form)
    review.rating = form.cleaned_data["rating"]
    rating = int(review.rating)
    rating_empty_star = "12345"
    rating_full_star = rating_empty_star[:rating]
    rating_empty_star = rating_empty_star[rating:]
    review.rating_full_star = rating_full_star
    review.rating_empty_star = rating_empty_star
    review.headline = form.cleaned_data["headline"]
    review.body = form.cleaned_data["body"]
    review.user = request.user
    review.save()

def save_updated_review(request, form: forms, review: Review):
    if 'ticket_pk' in request.POST:
        review.ticket = get_ticket_by_pk(request.POST.get('ticket_pk'))[0]
        review.ticket.already_reviewed = True
    else:
        review.ticket = save_updated_ticket(request, form, review.ticket)
    review.rating = form.cleaned_data["rating"]
    rating = int(review.rating)
    rating_empty_star = "12345"
    rating_full_star = rating_empty_star[:rating]
    rating_empty_star = rating_empty_star[rating:]
    review.rating_full_star = rating_full_star
    review.rating_empty_star = rating_empty_star
    review.headline = form.cleaned_data["headline"]
    review.body = form.cleaned_data["body"]
    review.save()

def delete_review(review: Review):
    review.delete()

def save_subscribtion(user: User, followed_user: User):
    for user_follows in UserFollows.objects.all():
        # Check if this user is not always followed
        if (
                user_follows.user == user
                and
                user_follows.followed_user == followed_user):
            return
    user_follow = UserFollows()
    user_follow.user = user
    user_follow.followed_user = followed_user
    user_follow.save()

def delete_subscribtion(user: User, followed_user: User):
    # Get all users followed by user
    user_follow = UserFollows.objects.filter(
        user=user,
        followed_user=followed_user)
    user_follow.delete()
    # users_follow = UserFollows.objects.all()
    # for user_follow in users_follow:
    #     if (
    #             user_follow.user == user
    #             and
    #             user_follow.followed_user == followed_user):
    #         user_follow.delete()
    #         break

def username_exists(username):
    if User.objects.filter(username=username).exists():
        return True

    return False

def check_password_confirmation(form: forms):
    if (
            form.cleaned_data['password']
            ==
            form.cleaned_data['password_confirmation']):
        return True
    else:
        # The password confirmation doesn't correspond to the
        # password, we need to informed the user to its mistake.
        form.add_error(
            'password_confirmation',
            'Vous n\'avez pas renseigné '
            'deux fois le même mot de passe.')
        return False


import requests

product_id = input("Give me pk of Item ")

endpoint = f"http://127.0.0.1:8000/api/products/{int(product_id)}/delete/"

get_response = requests.delete(endpoint)

print("-"*20)

print(get_response.status_code)


# CamJam EduKit 3 - Robotics
# Worksheet 6 - Measuring Distance

import time  # Import the Time library

from gpiozero import DistanceSensor  # Import GPIO Zero Library

# Define GPIO pins to use on the Pi
pintrigger = 17
pinecho = 18

sensor = DistanceSensor(echo=pinecho, trigger=pintrigger)

print("Ultrasonic Measurement")

try:
    # Repeat the next indented block forever
    while True:
        print("Distance: %.1f cm" % (sensor.distance * 100))
        time.sleep(0.5)

# If you press CTRL+C, cleanup and stop
except KeyboardInterrupt:
    exit()

CamJam Edukit 3 - GPIO Zero/Code/6-distance.py


import os
from typing import Union, Optional
import gridfs
import pika
import json

from flask import Flask, request, send_file, Response
from flask_pymongo import PyMongo
from bson.objectid import ObjectId

from auth import validate
from auth_svc import access
from storage import util

# Create server
server = Flask(__name__)

# Allow PyMongo to manage connections between server and mongo video/mp3 db (store video and converted mp3 files)
mongo_vid = PyMongo(server, uri="mongodb://host.minikube.internal:27017/videos")
mongo_mp3 = PyMongo(server, uri="mongodb://host.minikube.internal:27017/mp3s")

# Use MongoDB grid fs (grid file storage) (i.e. spec for storing large files in shards)
# (one collection stores file chunks, other collection stores metadata)
fs_vid = gridfs.GridFS(mongo_vid.db)
fs_mp3 = gridfs.GridFS(mongo_mp3.db)

# Create connection to RabbitMQ (queue to send messages for video processing jobs)
connection = pika.BlockingConnection(pika.ConnectionParameters(host="rabbitmq"))
channel = connection.channel()

# login route
@server.route("/login", methods=["POST"])
def login() -> Union[Optional[str], tuple[str, Optional[int]]]:
    # Attempt to log user in
    token, err = access.login(request)

    # Return result
    if err != None:
        return token
    else:
        return err

# video upload route
@server.route("/upload", methods=["POST"])
def upload() -> Union[str, tuple[str, int]]:
    # Attempt to valid user's provided JWT token
    valid_access, err = validate.validate_token(request)
    if err:
        return err

    # Deserialize JSON access string to Python string
    valid_access = json.loads(valid_access)

    # Check if user has admin privileges
    if valid_access["admin"]:
        if len(request.files) != 1:
            return "Only one file required", 400

        for f in request.files.values():
            # Upload file
            err = util.upload(f, fs_vid, channel, valid_access)

            # Return error
            if err:
                return err

        return "Upload successful", 200
    else:
        return "Unauthorized user", 401

# MP3 download route
@server.route("/download", methods=["GET"])
def download() -> Union[tuple[str, int], Response]:
    # Attempt to valid user's provided JWT token
    valid_access, err = validate.validate_token(request)
    if err:
        return err

    # Deserialize JSON access string to Python string
    valid_access = json.loads(valid_access)

    # Check if user has admin privileges
    if valid_access["admin"]:
        # Check that mp3 file ID exists
        fid = request.args.get("fid")
        if fid is None:
            return "File ID must be provided", 401

        # Retrieve MP3 file from fs_mp3
        try:
            mp3_file = fs_mp3.get(ObjectId(fid))
            return send_file(mp3_file, download_name=f"{fid}.mp3")
        except Exception as err:
            print(err)
            return "Internal server error", 400
    return "Unauthorized user", 401

if __name__ == "__main__":
    server.run(host="0.0.0.0", port=8080)


import sys
def isBingo():

    res = 0
    # 가로 확인
    for i in range(5):
        flag = True
        if 0 in check[i]:
            flag = False
        if flag:
            res += 1

    # 세로 확인
    check_T = list(map(list,zip(*check)))
    for i in range(5):
        flag = True
        if 0 in check_T[i]:
            flag = False
        if flag:
            res += 1

    # 대각선
    r_flag, l_flag = True, True
    for i in range(5):
        if check[i][i] == 0:
            r_flag = False
        if check[i][4-i] == 0:
            l_flag = False
    if r_flag:
        res += 1
    if l_flag:
        res += 1

    if res >= 3:
        return True
    return False

bingo = list()
numbers = list()
check = [[0] * 5 for _ in range(5)]
count = 0

for _ in range(5):
    bingo.append(list(map(int, sys.stdin.readline().split())))
for _ in range(5):
    numbers.append(list(map(int, sys.stdin.readline().split())))

for number in numbers:
    while number:
        num = number.pop(0)
        count += 1

        for i in range(5):
            for j in range(5):
                if bingo[i][j] == num:
                    check[i][j] = 1
                    i = 5
                    break

        if count >= 5:
            if isBingo() == True:
                print(count)
                exit()

# def check1():
#     total=0
#
#     for i in range(5):
#         f=True
#         if 0 in check[i]:
#             f=False
#         if f:
#             total+=1
#
#     t_check = list(map(list, zip(*check)))
#     for i in range(5):
#         f=True
#         if 0 in t_check[i]:
#             f=False
#         if f:
#             total+=1
#
#
#     r,c=True,True
#     for i in range(5):
#         if check[i][i]!=0:
#             r=False
#         if check[i][4-i]!=0:
#             c=False
#     if r:
#         total+=1
#     if c:
#         total+=1
#
#     if total>=3:
#         return True
#     return False
#
#
# binggo=[list(map(int,input().split())) for _ in range(5)]
# teacher=[list(map(int,input().split())) for _ in range(5)]
# check = [[0] * 5 for _ in range(5)]
# cnt=0
#
# for i in teacher:
#     while i:
#         num=i.pop(0)
#         cnt+=1
#         for x in range(5):
#             for y in range(5):
#                 if binggo[x][y]==num:
#                     check[x][y]=1
#                     x=5
#                     break
#         if cnt>=5:
#             if check1()==True:
#                 print(cnt)
#                 exit()


from model.players import Players

class Board:
    EMPTY_CELL = ''

    def __init__(self, size):
        """Initializes board attributes

        Args:
            size(int) = user input size
        """
        self.size = size

        #allocate the board with empty squares
        self.board = [[self.EMPTY_CELL] * size for _ in range(size)]

        #initialize starting positions
        self.mid = size // 2
        self.board[self.mid-1][self.mid] = 'X'
        self.board[self.mid - 1][self.mid - 1] = 'O'
        self.board[self.mid][self.mid - 1] = 'X'
        self.board[self.mid][self.mid] = 'O'

    def update_cell(self, row, column, player):
        self.board[row][column] = player

    def get_item(self, index):
        """Added board[][] undex syntax
        index: subscript index as TUPLE
        return: value 'X', 'O', or '' at index
        """
        x,y = index[0], index[1]
        return self.board[x][y]

    def convert_to_tup(self, action):
        """Convert the input that comes in as a string into a tuple representing indices of matrix
        Args:
            action {str} -- ex1) 'A1'  ex2) 'B4'
        Ret:
            action {tup} ex1) (0,0) ex2) (3,1)
        """
        row, col = str(action[1]).upper(), str(action[0]).upper()

        if row in '12345678' and col in 'ABCDEFGH': #if row and col exist in selection area

            x, y = '12345678'.index(row), 'ABCDEFGH'.index(col)
            return x, y

    def is_valid_location(self, row, col):
        """Returns True/False if row, col are within board range

        Args:
            row(list): row index of board matrix
            col(list): column index of board matrix
        """
        return row >= 0 and row <= self.size - 1 and col >= 0 and col <= self.size - 1

    def count_tiles(self):
        """ Will count the tiles for each player and return a dict {'X': count , 'O': count}
        """
        tiles = {}  # key = player symbol, value = disks number

        #iterate through matrix
        for row in self.board:
            for i in row:
                if i in tiles: #if already in return dict
                    tiles[i] += 1 #add to certain
                else:
                    tiles[i] = 1
        return tiles

    def is_full(self):
        """Go through each cell and see if empty.
        Args:
            n/a
        Return:
            TRUE if cells are EMPTY
            FALSE if cells are NOT EMPTY
        """
        for row in self.board:
            if self.EMPTY_CELL not in row:
                pass
            else:
                return False
        return True


from lxml import etree
from lxml.etree import SubElement
from lxml.builder import E
import spyne.const.xml as ns
from spyne.const.xml import WSDL11
from spyne.interface.wsdl.wsdl11 import check_method_port, _in_header_msg_suffix, _out_header_msg_suffix

def add_message_for_object(self, root, messages, obj, message_name):
    if obj is not None and not (message_name in messages):
        messages.add(message_name)

        message = SubElement(root, WSDL11("message"))
        if (message_name.endswith('Response')):
            message.set('name', message_name + 'Msg')
        elif (message_name.endswith('Fault')):
            message.set('name', f"{message_name.split('_')[0][:-6]}_{message_name.split('_')[1]}Msg")
            # import ipdb
            # ipdb.set_trace()
        else:
            message.set('name', message_name + 'RequestMsg')

        if isinstance(obj, (list, tuple)):
            objs = obj
        else:
            objs = (obj,)

        for obj in objs:
            part = SubElement(message, WSDL11("part"))
            if (message_name.endswith('Response')):
                part.set('name', message_name[:-8] + 'Result')
            elif (message_name.endswith('Fault')):
                part.set('name', message_name.split('_')[1])
        # <xsd:element name="sendMessageFault1_sendMessageFault" must match with method name
            else:
                part.set('name', message_name + 'Parameters')

            part.set('element', obj.get_element_name_ns(self.interface))

def add_port_type(self, service, root, service_name, types, url):
    cb_port_type = self._add_callbacks(service, root, types,
                                                            service_name, url)
    applied_service_name = self._get_applied_service_name(service)

    port_binding_names = []
    port_type_list = service.get_port_types()
    if len(port_type_list) > 0:
        for port_type_name in port_type_list:
            port_type = self._get_or_create_port_type(port_type_name)
            port_type.set('name', port_type_name)

            binding_name = self._get_binding_name(port_type_name)
            port_binding_names.append((port_type_name, binding_name))

    else:
        port_type = self._get_or_create_port_type(service_name)
        port_type.set('name', service_name)

        binding_name = self._get_binding_name(service_name)
        port_binding_names.append((service_name, binding_name))

    for method in service.public_methods.values():
        check_method_port(service, method)

        if method.is_callback:
            operation = SubElement(cb_port_type, WSDL11("operation"))
        else:
            operation = SubElement(port_type, WSDL11("operation"))

        operation.set('name', method.operation_name)

        if method.doc is not None:
            operation.append(E(WSDL11("documentation"), method.doc))

        operation.set('parameterOrder', method.in_message.get_element_name())

        op_input = SubElement(operation, WSDL11("input"))
        op_input.set('name', method.in_message.get_element_name() + 'Request')
        op_input.set('message',
                        method.in_message.get_element_name_ns(self.interface) + 'RequestMsg')

        if (not method.is_callback) and (not method.is_async):
            op_output = SubElement(operation, WSDL11("output"))
            op_output.set('name', method.out_message.get_element_name())
            op_output.set('message', method.out_message.get_element_name_ns(
                                                            self.interface) + 'Msg')

            if not (method.faults is None):
                for f in method.faults:
                    fault = SubElement(operation, WSDL11("fault"))
                    fault.set('name',  method.in_message.get_element_name() + 'Fault')
                    fault.set('message', '%s:%s' % (
                                    f.get_namespace_prefix(self.interface),
                                    f"{method.in_message.get_element_name()}_{method.in_message.get_element_name()}FaultMsg"))

    ser = self.service_elt_dict[applied_service_name]
    for port_name, binding_name in port_binding_names:
        self._add_port_to_service(ser, port_name, binding_name)

def add_bindings_for_methods(self, service, root, service_name,
                                    cb_binding):

    pref_tns = self.interface.get_namespace_prefix(self.interface.get_tns())
    input_binding_ns = ns.get_binding_ns(self.interface.app.in_protocol.type)
    output_binding_ns = ns.get_binding_ns(self.interface.app.out_protocol.type)

    def inner(method, binding):
        operation = etree.Element(WSDL11("operation"))
        operation.set('name', method.operation_name)

        soap_operation = SubElement(operation, input_binding_ns("operation"))
        soap_operation.set('soapAction', '')

        # get input
        input = SubElement(operation, WSDL11("input"))
        input.set('name', method.in_message.get_element_name() + 'Request')

        soap_body = SubElement(input, input_binding_ns("body"))
        soap_body.set('use', 'literal')

        # get input soap header
        in_header = method.in_header
        if in_header is None:
            in_header = service.__in_header__

        if not (in_header is None):
            if isinstance(in_header, (list, tuple)):
                in_headers = in_header
            else:
                in_headers = (in_header,)

            if len(in_headers) > 1:
                in_header_message_name = ''.join((method.name,
                                                    _in_header_msg_suffix))
            else:
                in_header_message_name = in_headers[0].get_type_name()

            for header in in_headers:
                soap_header = SubElement(input, input_binding_ns('header'))
                soap_header.set('use', 'literal')
                soap_header.set('message', '%s:%s' % (
                            header.get_namespace_prefix(self.interface),
                            in_header_message_name))
                soap_header.set('part', header.get_type_name())

        if not (method.is_async or method.is_callback):
            output = SubElement(operation, WSDL11("output"))
            output.set('name', method.out_message.get_element_name())

            soap_body = SubElement(output, output_binding_ns("body"))
            soap_body.set('use', 'literal')

            # get output soap header
            out_header = method.out_header
            if out_header is None:
                out_header = service.__out_header__

            if not (out_header is None):
                if isinstance(out_header, (list, tuple)):
                    out_headers = out_header
                else:
                    out_headers = (out_header,)

                if len(out_headers) > 1:
                    out_header_message_name = ''.join((method.name,
                                                    _out_header_msg_suffix))
                else:
                    out_header_message_name = out_headers[0].get_type_name()

                for header in out_headers:
                    soap_header = SubElement(output, output_binding_ns("header"))
                    soap_header.set('use', 'literal')
                    soap_header.set('message', '%s:%s' % (
                            header.get_namespace_prefix(self.interface),
                            out_header_message_name))
                    soap_header.set('part', header.get_type_name())

            if not (method.faults is None):
                for f in method.faults:
                    wsdl_fault = SubElement(operation, WSDL11("fault"))
                    # wsdl_fault.set('name', f.get_type_name())
                    wsdl_fault.set('name', method.in_message.get_element_name() + 'Fault')

                    soap_fault = SubElement(wsdl_fault, input_binding_ns("fault"))
                    # soap_fault.set('name', f.get_type_name())
                    soap_fault.set('name', method.in_message.get_element_name() + 'Fault')
                    soap_fault.set('use', 'literal')

        if method.is_callback:
            relates_to = SubElement(input, input_binding_ns("header"))

            relates_to.set('message', '%s:RelatesToHeader' % pref_tns)
            relates_to.set('part', 'RelatesTo')
            relates_to.set('use', 'literal')

            cb_binding.append(operation)

        else:
            if method.is_async:
                rt_header = SubElement(input, input_binding_ns("header"))
                rt_header.set('message', '%s:ReplyToHeader' % pref_tns)
                rt_header.set('part', 'ReplyTo')
                rt_header.set('use', 'literal')

                mid_header = SubElement(input, input_binding_ns("header"))
                mid_header.set('message', '%s:MessageIDHeader' % pref_tns)
                mid_header.set('part', 'MessageID')
                mid_header.set('use', 'literal')

            binding.append(operation)

    port_type_list = service.get_port_types()
    if len(port_type_list) > 0:
        for port_type_name in port_type_list:

            # create binding nodes
            binding = SubElement(root, WSDL11("binding"))
            binding.set('name', self._get_binding_name(port_type_name))
            binding.set('type', '%s:%s'% (pref_tns, port_type_name))

            transport = SubElement(binding, input_binding_ns("binding"))
            transport.set('style', 'document')
            transport.set('transport', self.interface.app.transport)

            for m in service.public_methods.values():
                if m.port_type == port_type_name:
                    inner(m, binding)

    else:
        # here is the default port.
        if cb_binding is None:
            cb_binding = SubElement(root, WSDL11("binding"))
            cb_binding.set('name', service_name)
            cb_binding.set('type', '%s:%s'% (pref_tns, service_name))

            transport = SubElement(cb_binding, input_binding_ns("binding"))
            transport.set('style', 'document')
            transport.set('transport', self.interface.app.transport)

        for m in service.public_methods.values():
            inner(m, cb_binding)

    return cb_binding


from asyncio.windows_events import NULL
from timeit import repeat
from selenium.webdriver.common.by import By
from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import os
import subprocess

def get_element(xpath = "", driver = NULL):
    # searches for an element from the web driver
    # at the given xpath
    tryAgain = 50
    while tryAgain:
        try:
            button = driver.find_element(By.XPATH, xpath)
            tryAgain = 0
        except Exception as e:
            print("Element not found!")
            tryAgain -= 1
            time.sleep(1)
    return button

def driver_setup():
    # sets all the options for the chrome driver, opens it
    # and returns
    chrome_options = Options()
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--verbose")
    chrome_options.add_experimental_option("debuggerAddress", "localhost:9222")

    driver = webdriver.Chrome(service = Service(".\\chromedriver_win32_105\\chromedriver.exe"), options = chrome_options)
    driver.get("https://music.youtube.com/")
    return driver

def isDriverClosed(driver):
    if driver:
        if not driver.window_handles:
            return True
        else:
            return False

def pressButton(button):
    # tries to call .click() method on the elemnt given
    # returns true or false
    try:
        button.click()
        return True
    except Exception as e:
        print("Can't press button")
        return False

def main():
    # command = './Chrome/Application/chrome.exe --remote-debugging-port=9222 --user-data-dir="./chromedriver_win32_105/localhost"\n'
    # subprocess.run(command)
    # print("SetUping")

    expandedMenuIsClicked = False

    driver = driver_setup()
    print("Setup done!")
    buttonNext = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[1]/div/tp-yt-paper-icon-button[5]")
    buttonPrev = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[1]/div/tp-yt-paper-icon-button[1]")
    buttonPlayPause = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[1]/div/tp-yt-paper-icon-button[3]/tp-yt-iron-icon")
    buttonMute = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[3]/ytmusic-player-expanding-menu/tp-yt-paper-icon-button[1]/tp-yt-iron-icon")
    buttonExpandMenu = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[3]/div/tp-yt-paper-icon-button[4]/tp-yt-iron-icon")
    buttonRepeat = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[3]/ytmusic-player-expanding-menu/tp-yt-paper-icon-button[2]")
    expandMenuState = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[3]/ytmusic-player-expanding-menu")
    buttonShuffle = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[3]/ytmusic-player-expanding-menu/tp-yt-paper-icon-button[3]/tp-yt-iron-icon")
    playPauseState = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[1]/div/tp-yt-paper-icon-button[3]")
    muteState = get_element(driver=driver, xpath="/html/body/ytmusic-app/ytmusic-app-layout/ytmusic-player-bar/div[3]/ytmusic-player-expanding-menu/tp-yt-paper-icon-button[1]")

    while 1:
        cmd = input("Give command: ")
        if cmd == 'n' :  # next
            if pressButton(buttonNext):
                print("Next")
            continue
        if cmd == 'p' :  # previous
            if pressButton(buttonPrev):
                print("Previous")
            continue
        if cmd == 'P' :  # pause/play
            print(playPauseState.get_attribute('aria-label'))
            pressButton(buttonPlayPause)
            continue
        if cmd == 'm' :  # mute/unmute
            if expandMenuState.get_attribute('aria-hidden') == 'true':
                pressButton(buttonExpandMenu)
            if pressButton(buttonMute) :
                time.sleep(0.2)
                if muteState.get_attribute('aria-pressed') == 'false' :
                    print("Unmute")
                else :
                    print("Mute")
            continue
        if cmd == 'r' :  # repeat
            if expandMenuState.get_attribute('aria-hidden') == 'true':
                pressButton(buttonExpandMenu)
            if pressButton(buttonRepeat) :
                print(buttonRepeat.get_attribute('title'))
            continue
        if cmd == 's' :  # shuffle
            if expandMenuState.get_attribute('aria-hidden') == 'true':
                pressButton(buttonExpandMenu)
            if pressButton(buttonShuffle) :
                print("Shuffle")
            continue
        if cmd == 'q':  # quit
            break
        print("Button unrecognised")

    driver.quit()
if __name__ == '__main__':
    main()


__author__ = "Steven Lee"

goods_list = [["1", "iphone", "5800"], ["2", "mac", "12000"], ["3", "starbuck coffee", "31"], ["4", "python book", "81"]
    , ["5", "bike", "800"]]
goods_num = []
shopping_cart = []
salary = input("Please input your salary:")

while True:
    print("")
    print("your account balance is ", salary)
    if len(shopping_cart):
        print("your shopping cart have: ", shopping_cart)
    else:
        print("your shopping cart have nothing!")
    print("")
    print("goods list is:", goods_list)

    buy = input("Please input which goods(number) you want to buy:")
    if str(buy) == "Q" or str(buy) == "q":
        print("Out of your shopping trip!")
        break
    for i in goods_list:
        if buy == i[0] and int(salary) > int(i[2]):
            shopping_cart.append(i)
            salary = int(salary)
            salary -= int(i[2])
            print("added {_goods} to you shopping cart!".format(_goods=i))
            break
        elif buy == i[0] and int(salary) < int(i[2]):
            print("Your balance is not enough to buy goods ", i)
        else:
            continue


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

from tracker_view import *
import glumpy
import glumpy.atb as atb
from ctypes import *
from Queue import Empty
import os
import sys
import re
from coxlab_eyetracker.settings import global_settings

import logging

try:
    from collections import OrderedDict
except:
    from ordereddict import OrderedDict

# Utility functions for use with atb

def binding_getter(o, key):

    def get_wrapper():
        val = getattr(o, key)
        if val is None:
            val = 0
        return val

    return get_wrapper

def binding_setter(o, key):

    def ff_wrapper(val):
        setattr(o, key, val)
        o.update_parameters()

    def regular_wrapper(val):
        setattr(o, key, val)

    if hasattr(o, 'update_parameters') and callable(getattr(o,
            'update_parameters')):
        return ff_wrapper
    else:
        return regular_wrapper

# Do a tiny bit of trickiness to make glumpy.atb less tiresome

def new_add_var(self, name=None, value=None, **kwargs):
    t = kwargs.pop('target', None)
    p = kwargs.pop('attr', None)

    if t is not None and p is not None:
        kwargs['getter'] = binding_getter(t, p)
        kwargs['setter'] = binding_setter(t, p)
    return self.old_add_var(name, value, **kwargs)

atb.Bar.old_add_var = atb.Bar.add_var
atb.Bar.add_var = new_add_var

class EyeTrackerGUI:

    def __init__(self, c):

        self.controller = c
        self.tracker_view = TrackerView()

        self.show_feature_map = c_bool(False)
        self.display_starburst = c_bool(False)
        self.n_frames = 0
        self.frame_count = 0
        self.frame_rate_accum = 0.0
        self.frame_rates = []
        self.start_time = None
        self.last_time = 0
        self.last_update_time = time.time()

        self.calibration_file = ''

        atb.init()
        self.window = glumpy.Window(900, 600)

        # ---------------------------------------------------------------------
        #   STAGE CONTROLS
        # ---------------------------------------------------------------------

        self.gaze_bar = atb.Bar(
            name='gaze',
            label='Gaze Info',
            iconified='false',
            help='Current Gaze',
            position=(10, 10),
            size=(100, 200))

        self.gaze_bar.add_var('Gaze/Status', label='Calibration Status',
                            target=c, attr='calibration_status', readonly=True)
        self.gaze_bar.add_var('Gaze/H', label='Horizontal Gaze', target=c,
                            attr='gaze_azimuth', readonly=True)
        self.gaze_bar.add_var('Gaze/V', label='Vertical Gaze', target=c,
                            attr='gaze_elevation', readonly=True)
        self.gaze_bar.add_var('FPS', label='FPS', target=c,
                            attr='conduit_fps', readonly=True)

        self.stages_bar = atb.Bar(
            name='stages',
            label='Stage Controls',
            iconified='true',
            help='Controls for adjusting stages',
            position=(10, 10),
            size=(200, 300),
            )

        self.stages_bar.add_var('X/x_set', label='set value', target=c,
                                attr='x_set')
        self.stages_bar.add_button('go_rel_x', lambda: c.go_rel_x(), group='X',
                                   label='move relative')
        self.stages_bar.add_button('go_abs_x', lambda: c.go_x(), group='X',
                                   label='move absolute')

        self.stages_bar.add_var('Y/y_set', label='set value', target=c,
                                attr='y_set')
        self.stages_bar.add_button('go_rel_y', lambda: c.go_rel_y(), group='Y',
                                   label='move relative')
        self.stages_bar.add_button('go_abs_y', lambda: c.go_y(), group='Y',
                                   label='move absolute')

        self.stages_bar.add_var('R/r_set', label='set value', target=c,
                                attr='r_set')
        self.stages_bar.add_button('go_rel_r', lambda: c.go_rel_r(), group='R',
                                   label='move relative')
        self.stages_bar.add_button('go_abs_r', lambda: c.go_r(), group='R',
                                   label='move absolute')

        self.stages_bar.add_button('up', lambda: c.up(), group='Jog',
                                   label='up')
        self.stages_bar.add_button('down', lambda: c.down(), group='Jog',
                                   label='down')
        self.stages_bar.add_button('left', lambda: c.left(), group='Jog',
                                   label='left')

        self.stages_bar.add_button('right', lambda: c.right(), group='Jog',
                                   label='right')

        # ---------------------------------------------------------------------
        #   FOCUS AND ZOOM CONTROLS
        # ---------------------------------------------------------------------

        self.focus_zoom_bar = atb.Bar(
            name='focus_and_zoom',
            label='Focus/Zoom Controls',
            iconified='true',
            help='Controls for adjusting power focus and zoom',
            position=(10, 10),
            size=(200, 300),
            )

        self.focus_zoom_bar.add_var('Focus/focus_step', label='focus step',
                                    target=c, attr='focus_step')
        self.focus_zoom_bar.add_button('focus_plus', lambda: c.focus_plus(),
                                       group='Focus', label='focus plus')
        self.focus_zoom_bar.add_button('focus_minus', lambda: c.focus_minus(),
                                       group='Focus', label='focus minus')

        self.focus_zoom_bar.add_var('Zoom/zoom_step', label='zoom step',
                                    target=c, attr='zoom_step')
        self.focus_zoom_bar.add_button('zoom_plus', lambda: c.zoom_plus(),
                                       group='Zoom', label='zoom plus')
        self.focus_zoom_bar.add_button('zoom_minus', lambda: c.zoom_minus(),
                                       group='Zoom', label='zoom minus')

        # ---------------------------------------------------------------------
        #   LED CONTROLS
        # ---------------------------------------------------------------------

        self.led_bar = atb.Bar(
            name='leds',
            label='LED Controls',
            iconified='true',
            help='Controls for adjusting illumination',
            position=(20, 20),
            size=(200, 180),
            )

        self.led_bar.add_var(
            'Side/Ch1_mA',
            #target=c,
            #attr='IsetCh1',
            label='I Ch1 (mA)',
            vtype=atb.TW_TYPE_UINT32,
            setter=lambda x: c.leds.set_current(1, x),
            getter=lambda: c.leds.soft_current(1),
            min=0,
            max=1000,
            )

        self.led_bar.add_var('Side/Ch1_status', label='Ch1 status',
                             vtype=atb.TW_TYPE_BOOL8,
                             getter=lambda: c.leds.soft_status(1),
                             setter=lambda x: c.leds.set_status(1, x))

        self.led_bar.add_var(
            'Top/Ch2_mA',
            #target=c,
            #attr='IsetCh2',
            label='I Ch2 (mA)',
            vtype=atb.TW_TYPE_UINT32,
            setter=lambda x: c.leds.set_current(2, x),
            getter=lambda: c.leds.soft_current(2),
            min=0,
            max=1000,
            )
        self.led_bar.add_var('Top/Ch2_status', vtype=atb.TW_TYPE_BOOL8,
                             getter=lambda: c.leds.soft_status(2),
                             setter=lambda x: c.leds.set_status(2, x))

        #self.led_bar.add_var(
        #    'Channel3/Ch3_mA',
        #    target=c,
        #    attr='IsetCh3',
        #    label='I Ch3 (mA)',
        #    setter=lambda x: c.leds.set_current(3,x),
        #    min=0,
        #    max=250,
        #    )
        # self.led_bar.add_var('Channel3/Ch3_status', label='Ch3 status',
        #                              vtype=atb.TW_TYPE_BOOL8,
        #                              getter=lambda: c.leds.soft_status(3),
        #                              setter=lambda x: c.leds.set_status(3, x))
        #
        #         self.led_bar.add_var(
        #             'Channel4/Ch4_mA',
        #             target=c,
        #             attr='IsetCh4',
        #             label='I Ch4 (mA)',
        #             setter=lambda x: c.leds.set_current(4,x),
        #             min=0,
        #             max=250,
        #             )
        #         self.led_bar.add_var('Channel4/Ch4_status', label='Ch4 status',
        #                              vtype=atb.TW_TYPE_BOOL8,
        #                              getter=lambda: c.leds.soft_status(4),
        #                              setter=lambda x: c.leds.set_status(4, x))

        # ---------------------------------------------------------------------
        #   RADIAL FEATURE FINDER
        # ---------------------------------------------------------------------
        radial_ff = c.radial_ff

        self.radial_ff_bar = atb.Bar(
            name='RadialFF',
            label='Radial Symmetry',
            help='Parameters for initial (symmetry-based) image processing',
            iconified='true',
            position=(30, 30),
            size=(250, 180),
            )

        self.radial_ff_bar.add_var(
            'target_kpixels',
            label='Target kPixels',
            vtype=atb.TW_TYPE_FLOAT,
            min=50.,
            max=1000.,
            step=10.,
            target=radial_ff,
            attr='target_kpixels',
            )
        self.radial_ff_bar.add_var(
            'min_radius_fraction',
            label='Min. radius (fraction)',
            vtype=atb.TW_TYPE_FLOAT,
            min=0.01,
            max=0.5,
            step=0.01,
            target=radial_ff,
            attr='min_radius_fraction',
            )
        self.radial_ff_bar.add_var(
            'max_radius_fraction',
            label='Max. radius (fraction)',
            vtype=atb.TW_TYPE_FLOAT,
            min=0.1,
            max=0.8,
            step=0.01,
            target=radial_ff,
            attr='max_radius_fraction',
            )
        self.radial_ff_bar.add_var(
            'radius_steps',
            label='Radius steps',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=10,
            step=1,
            target=radial_ff,
            attr='radius_steps',
            )
        self.radial_ff_bar.add_var(
            'alpha',
            label='Alpha',
            vtype=atb.TW_TYPE_FLOAT,
            min=1.,
            max=50.,
            step=1.,
            target=radial_ff,
            attr='alpha',
            )

        self.radial_ff_bar.add_var('show_transform', label='Show Transform',
                                   vtype=atb.TW_TYPE_BOOL8, target=self,
                                   attr='show_feature_map')

        self.radial_ff_bar.add_var('Albino/albino_mode_enable',
                                   label='Mode Enabled',
                                   vtype=atb.TW_TYPE_BOOL8, target=radial_ff,
                                   attr='albino_mode')
        self.radial_ff_bar.add_var(
            'Albino/albino_threshold',
            label='Threshold',
            vtype=atb.TW_TYPE_FLOAT,
            min=0.1,
            max=50.,
            step=1.,
            target=radial_ff,
            attr='albino_threshold',
            )

        self.radial_ff_bar.add_var(
            'RestrictRegion/top',
            label='top',
            vtype=atb.TW_TYPE_UINT32,
            min=0,
            max=300,
            step=1,
            target=radial_ff,
            attr='restrict_top',
            )
        self.radial_ff_bar.add_var(
            'RestrictRegion/left',
            label='left',
            vtype=atb.TW_TYPE_UINT32,
            min=0,
            max=300,
            step=1,
            target=radial_ff,
            attr='restrict_left',
            )

        self.radial_ff_bar.add_var(
            'RestrictRegion/right',
            label='right',
            vtype=atb.TW_TYPE_UINT32,
            min=0,
            max=300,
            step=1,
            target=radial_ff,
            attr='restrict_right',
            )

        self.radial_ff_bar.add_var(
            'RestrictRegion/bottom',
            label='bottom',
            vtype=atb.TW_TYPE_UINT32,
            min=0,
            max=300,
            step=1,
            target=radial_ff,
            attr='restrict_bottom',
            )

        # ---------------------------------------------------------------------
        #   STARBURST FEATURE FINDER
        # ---------------------------------------------------------------------

        self.sb_ff_bar = atb.Bar(
            name='StarburstFF',
            label='Starburst',
            iconified='true',
            help="Parameters for the refinement phase ('starburst') image processing",
            position=(40, 40),
            size=(200, 250),
            )

        sb_ff = c.starburst_ff

        self.sb_ff_bar.add_var(
            'Pupil/n_pupil_rays',
            label='n rays',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=100,
            step=1,
            target=sb_ff,
            attr='pupil_n_rays',
            )

        self.sb_ff_bar.add_var(
            'Pupil/pupil_min_radius',
            label='min radius',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=100,
            step=1,
            target=sb_ff,
            attr='pupil_min_radius',
            )

        self.sb_ff_bar.add_var(
            'Pupil/pupil_threshold',
            label='edge detect threshold',
            vtype=atb.TW_TYPE_FLOAT,
            min=0.1,
            max=5.0,
            step=0.1,
            target=sb_ff,
            attr='pupil_threshold',
            )

        self.sb_ff_bar.add_var(
            'CR/n_cr_rays',
            label='n rays',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=100,
            step=1,
            target=sb_ff,
            attr='cr_n_rays',
            )

        self.sb_ff_bar.add_var(
            'CR/cr_min_radius',
            label='min radius',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=100,
            step=1,
            target=sb_ff,
            attr='cr_min_radius',
            )

        self.sb_ff_bar.add_var(
            'CR/cr_threshold',
            label='edge detect threshold',
            vtype=atb.TW_TYPE_FLOAT,
            min=0.1,
            max=5.0,
            step=0.1,
            target=sb_ff,
            attr='cr_threshold',
            )

        fit_algos = {0: 'circle_least_squares',
                     1: 'circle_least_squares_ransac',
                     2: 'ellipse_least_squares'}

        fit_algos_rev = dict([(val, key) for (key, val) in fit_algos.items()])

        FittingAlgorithm = atb.enum('FittingAlgorithm', {'circle lst sq': 0,
                                    'circle ransac': 1, 'ellipse lst sq': 2})
        self.sb_ff_bar.add_var('Fitting/circle_fit', label='circle fit method',
                               vtype=FittingAlgorithm, getter=lambda: \
                               fit_algos_rev[sb_ff.fitting_algorithm],
                               setter=lambda x: \
                               setattr(sb_ff, 'fitting_algorithm', fit_algos[x]))

        self.sb_ff_bar.add_var('Display/show_rays', self.display_starburst)

        # ---------------------------------------------------------------------
        #   CALIBRATION
        # ---------------------------------------------------------------------
        self.cal_bar = atb.Bar(
            name='Calibration',
            label='Calibration',
            iconified='true',
            help='Auto-calibration steps',
            position=(50, 50),
            size=(250, 300),
            refresh=0.5
            )

        self.cal_bar.add_button('calibrate', lambda: c.calibrate(),
                                label='Calibrate (full)')

        self.cal_bar.add_separator('Sub-phases')
        self.cal_bar.add_button('cal_center_h', lambda: \
                                c.calibrate_center_horizontal(),
                                label='Center Horizontal')
        self.cal_bar.add_button('cal_center_v', lambda: \
                                c.calibrate_center_vertical(),
                                label='Center Vertical')
        self.cal_bar.add_button('cal_center_d', lambda: \
                                c.calibrate_center_depth(), label='Center Depth'
                                )
        #self.cal_bar.add_button('align_pupil_cr', lambda: \
        #                        c.calibrate_align_pupil_and_cr(),
        #                        label='Align Pupil and CR')
        self.cal_bar.add_button('cal_pupil_rad', lambda: \
                                c.calibrate_find_pupil_radius(),
                                label='Find Pupil Radius')

        self.cal_bar.add_separator('Info')
        self.cal_bar.add_var('d', label='Distance to CR curv. center',
                             vtype=atb.TW_TYPE_FLOAT, target=c.calibrator,
                             attr='d')  # readonly = True,
        self.cal_bar.add_var('Rp', label='Pupil rotation radius (Rp)[mm]',
                             vtype=atb.TW_TYPE_FLOAT, target=c.calibrator,
                             attr='Rp_mm')  # readonly = True,

        # Calibration Files
        try:
            self.refresh_calibration_file_list()

            self.cal_bar.add_separator('Calibration Files')

            self.cal_bar.add_var('current_calibration_file',
                                 vtype=self.cal_enum, label='Calibration File',
                                 getter=lambda: \
                                 self.get_calibration_file_atb(),
                                 setter=lambda x: \
                                 self.set_calibration_file_atb(x))
                                  # setter = lambda x: sb_ff.__dict__.__setitem__('fitting_algorithm', fit_algos[x]))
                                  # getter=lambda: self.get_calibration_file_atb,
                                  # setter=lambda x: self.set_calibration_file_atb(x))

            self.cal_bar.add_separator('Calibration Save')
            self.cal_file_save_name = ctypes.c_char_p('')

            self.cal_bar.add_var('calibration_file_save_name',
                                 vtype=atb.TW_TYPE_CDSTRING, target=self,
                                 attr='cal_file_save_name')
            self.cal_bar.add_button('save_calibration', lambda: \
                                    self.save_calibration_file_atb(self.cal_file_save_name))
        except Exception as E:
            logging.warning("Error setting calibration file list: %s" % E)
            logging.warning("""Unable to use calibration-file saving
                               infrastructure.  A patched version of glumpy
                               is required to enable this feature.""")

        # --------------------------------------------------------------------
        #   CAMERA
        # --------------------------------------------------------------------

        self.cam_bar = atb.Bar(
            name='Camera',
            label='Camera',
            iconified='true',
            help='Camera acquisition parameters',
            position=(60, 60),
            size=(200, 180),
            )

        def saving(x=None):
            if not hasattr(c.feature_finder, 'save'):
                return False
            if x is None:
                return c.feature_finder.save
            c.feature_finder.save = x

        self.cam_bar.add_var(
            'save',
            label='save',
            vtype=atb.TW_TYPE_BOOL8,
            getter=lambda: saving(),
            setter=lambda x: saving(x),
        )

        self.cam_bar.add_var(
            'binning',
            label='binning',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=16,
            step=1,
            target=c,
            attr='binning',
            )

        self.cam_bar.add_var(
            'gain',
            label='gain',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=16,
            step=1,
            target=c,
            attr='gain',
            )

        self.cam_bar.add_var(
            'exposure',
            label='exposure',
            vtype=atb.TW_TYPE_UINT32,
            min=5000,
            max=30000,
            step=1000,
            target=c,
            attr='exposure',
            )

        self.cam_bar.add_var(
            'ROI/roi_width',
            label='width',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=800,
            step=1,
            target=c,
            attr='roi_width',
            )

        self.cam_bar.add_var(
            'ROI/roi_height',
            label='height',
            vtype=atb.TW_TYPE_UINT32,
            min=1,
            max=800,
            step=1,
            target=c,
            attr='roi_height',
            )

        self.cam_bar.add_var(
            'ROI/roi_offset_x',
            label='offset x',
            vtype=atb.TW_TYPE_UINT32,
            min=0,
            max=800,
            step=1,
            target=c,
            attr='roi_offset_x',
            )

        self.cam_bar.add_var(
            'ROI/roi_offset_y',
            label='offset y',
            vtype=atb.TW_TYPE_UINT32,
            min=0,
            max=800,
            step=1,
            target=c,
            attr='roi_offset_y',
            )

        # Event Handlers
        def on_init():
            self.tracker_view.prepare_opengl()

        def on_draw():
            self.window.clear()
            self.tracker_view.draw((self.window.width, self.window.height))

        def on_idle(dt):
            # if dt < 0.02:
            #    return
            self.update_tracker_view()
            self.window.draw()

        def on_key_press(symbol, modifiers):
            if symbol == glumpy.key.ESCAPE:
                c.stop_continuous_acquisition()
                logging.debug("Controller has %i refs" % sys.getrefcount(c))
                c.release()
                self.controller = None
                logging.debug("Controller has %i refs" % sys.getrefcount(c))
                c.shutdown()
                #print "Shutting down controller..."
                #print "Shut down controller", c.shutdown()
                #c.continuously_acquiring = False
                #c.acq_thread.join()
                sys.exit()

        self.window.push_handlers(atb.glumpy.Handlers(self.window))
        self.window.push_handlers(on_init, on_draw, on_key_press, on_idle)
        self.window.draw()

    def __del__(self):
        logging.debug("GUI __del__ called")
        self.controller.stop_continuous_acquisition()
        self.controller.release()
        self.controller.shutdown()
        self.controller = None

    def mainloop(self):
        self.window.mainloop()

    def get_calibration_file_atb(self):
        # return 0
        # return ctypes.c_int(0)
        if self.controller.calibration_file is None:
            calibration_filename = None
        else:
            calibration_filename = os.path.split(self.controller.calibration_file)[-1]
            calibration_filename = os.path.splitext(calibration_filename)[0]
        return self.cal_enum_dict.get(calibration_filename, 0)

        # return self.cal_enum_dict.get(self.controller.calibration_file,0)

    def set_calibration_file_atb(self, x):
        if self.cal_lookup_dict[x] == 'None':
            return
        self.calibration_file = self.cal_lookup_dict[x]
        base_path = os.path.expanduser(global_settings['calibration_path'])
        cal_path = os.path.join(base_path, '%s.pkl' % self.calibration_file)
        self.controller.calibrator.load_parameters(cal_path, self.controller)

        # self.controller.calibration_file = self.cal_lookup_dict[x]

    def refresh_calibration_file_list(self):

        # read in saved calibration files
        try:
            cal_path = os.path.expanduser(global_settings['calibration_path'])
        except KeyError:
            logging.warning('A calibration_path was not found in the config file')
            logging.warning('Loaded global settings: %s' % global_settings)

        if not os.path.exists(cal_path):
            os.makedirs(cal_path)

        cal_files = os.listdir(cal_path)
        cal_files = filter(lambda x: re.match(r'.*\.pkl', x), cal_files)

        cal_names = [x.split('.')[0] for x in cal_files]
        cal_names.insert(0, 'None')

        # add back in the rest of the path
        cal_files = [os.path.join(cal_path, x) for x in cal_files]
        cal_files.insert(0, '<none>')

        cal_ids = range(0, len(cal_names))
        self.cal_enum_dict = OrderedDict(zip(cal_names, cal_ids))
        self.cal_lookup_dict = OrderedDict(zip(cal_ids, cal_names))

        logging.debug('Calibration files: %s' % self.cal_enum_dict)
        logging.debug('Calibration lookup: %s' % self.cal_lookup_dict)

        self.cal_enum = atb.enum('CalibrationFile', self.cal_enum_dict)

    def save_calibration_file_atb(self, cal_name):
        base_path = os.path.expanduser(global_settings['calibration_path'])
        cal_path = os.path.join(base_path, '%s.pkl' % cal_name)
        self.controller.save_calibration(cal_path)
        #self.controller.calibrator.save_parameters(cal_path, self.controller)
        # self.controller.save_calibration(cal_path)
        self.refresh_calibration_file_list()

    def update_tracker_view(self):
        if (self.controller is None) or (self.controller.camera_device is None):
            return

        try:
            features = self.controller.ui_queue.get_nowait()
        except Empty:
            return

        if 'frame_time' in features:
            toc = features['frame_time']
        else:
            toc = 1

        if self.show_feature_map:
            transform_im = features['transform']
            if transform_im is not None:
                transform_im -= min(ravel(transform_im))
                transform_im = transform_im * 255 / max(ravel(transform_im))
                # ravelled = ravel(transform_im)
                self.tracker_view.im_array = transform_im.astype(uint8)
        else:
            self.tracker_view.im_array = features['im_array']

        if 'pupil_position_stage1' in features:
            self.tracker_view.stage1_pupil_position = \
                features['pupil_position_stage1']

        if 'cr_position_stage1' in features:
            self.tracker_view.stage1_cr_position = features['cr_position_stage1'
                    ]

        if 'cr_radius' in features:
            self.tracker_view.cr_radius = features['cr_radius']

        if 'pupil_radius' in features:
            self.tracker_view.pupil_radius = features['pupil_radius']

        if 'pupil_position' in features:
            self.tracker_view.pupil_position = features['pupil_position']

        if 'cr_position' in features:
            self.tracker_view.cr_position = features['cr_position']

        if self.display_starburst:
            self.tracker_view.starburst = features.get('starburst', None)
        else:
            self.tracker_view.starburst = None

        self.tracker_view.is_calibrating = features.get('is_calibrating', False)

        self.tracker_view.restrict_top = features.get('restrict_top', None)
        self.tracker_view.restrict_bottom = features.get('restrict_bottom',
                None)
        self.tracker_view.restrict_left = features.get('restrict_left', None)
        self.tracker_view.restrict_right = features.get('restrict_right', None)

        self.n_frames += 1
        self.frame_count += 1

        time_between_updates = 0.4

        self.frame_rate_accum += 1. / toc

        self.frame_rates.append(1. / toc)

        time_since_last_update = time.time() - self.last_update_time

        if time_since_last_update > time_between_updates:
            self.last_update_time = time.time()

            self.frame_rate = mean(array(self.frame_rates))
            self.frame_rates = []
            self.frame_rate_accum = 0

            self.last_time = time.time()
            self.n_frames = 0

            if 'sobel_avg' in features:
                self.sobel_avg = features['sobel_avg']


# 2022-03-12
# SK Famliy FE/App 1차 코딩테스트 1번

def cmpCoin(c1, c2, costs):
    coins = [1, 5, 10, 50, 100, 500]

    if costs[c1] * (coins[c2] // coins[c1]) < costs[c2]:
        return c1
    else:
        return c2

def selectCoin(costs):
    result = [-1] * 6

    result[0] = 0  # 1원은 1원동전쓰기
    result[1] = cmpCoin(0, 1, costs)  # 1원5개, 5원1개 중에 고르기

    for i in range(2, 6):
        result[i] = cmpCoin(result[i - 1], i, costs)

    return result

def solution(money, costs):
    answer = 0
    result = selectCoin(costs)

    coins = [1, 5, 10, 50, 100, 500]

    for c in range(len(costs)):
        m = money // coins[len(costs) - 1 - c]
        need = coins[len(costs) - 1 - c] // coins[result[len(costs) - 1 - c]]
        answer += m * need * costs[result[len(costs) - 1 - c]]
        money -= m * coins[len(costs) - 1 - c]
    return answer

print(solution(4578, [1, 4, 99, 35, 50, 1000]))