from Optimizer import sort_array_by_col
import numpy as np
import matplotlib.pyplot as plt
import copy

class MultiObjectiveOptimizer:
    def __init__(self, x, fitness, n_generations=5, population_size=5, n_objectives=2, constraint=None,
                 generation_func=None, constraint_func_input="design"):
        """Initialize the optimizer
        x: list that contains a series of dictionaries that define the x values for the optimizer where
        type is either continuous or integer. and min and max are the minimum and maximum values of the variable this
        should follow the form [{'type': ('integer' or 'continuous'), 'bounds': (min, max)]] with a new dict for each
        x value

        fitness: function that accepts x array in the same order as given in the x input, and returns the fitness of
        each design.

        n_generations: the number of generations to carry out

        population_size: the number of members in the population at each generation

        n_objectives: the number of objectives that are returned by the fitness function

        constraint: function that accepts x array in the same order as given in x and returns a vector that contains
        the constraint violation state of each constraint where >0 suggests that the constraint is violated and <=0
        suggests that the constraint is satisfied.

        generation_func: function that is called with each passing generation.  calls the generation function with
        the current population of the algorithm.  This is useful for things like plotting the generation at each
        iteration of the algorithm, but could be used for other fun things

        constraint_func_input: string, either "design" or "full" if design the constraint function is called with just
        the design, if full the constraint function is called with a 1d array where the 0th value is the maximin fitness
        of the design, the next n values are the n objectives returned by the fitness function, and the last n values
        are the n values that define the design.  It is useful to define full if the fitness and constraints are based
        on the same values and they are somewhat expensive to obtain.
        """
        self.num_generations = n_generations
        self.num_population = np.trunc(population_size)
        if self.num_population % 2 != 0:
            self.num_population += 1
        self.num_population = int(self.num_population)
        self.num_x = len(x)
        self.fitness_func = fitness
        self.constraint_func = constraint
        self.x_def = x
        self.num_objectives = n_objectives
        self.generation_call = generation_func
        self.constraint_func_input = constraint_func_input

        self.tournament_size = 2
        self.crossover_prob = 0.5
        self.mutation_prob = 0.13
        self.cross_eta = 0.5
        self.mutation_beta = 0.13

        # initialize the parent array
        # stored in the form ([fitness, x1, x2, x3, ..., xn])
        self.population = np.zeros((self.num_population, self.num_x + n_objectives + 1))
        for i in range(self.num_population):
            x_new = np.zeros(self.num_x)
            for j, val in enumerate(x):
                if val['type'] == 'integer':
                    x_new[j] = np.random.randint(val['bounds'][0], val['bounds'][1] + 1)
                elif val['type'] == 'continuous':
                    x_new[j] = np.random.uniform(val['bounds'][0], val['bounds'][1])
                else:
                    print("error unknown variable type")
            self.population[i, 1:n_objectives+1] = self.fitness_func(x_new)
            self.population[i, n_objectives+1:] = x_new
        self.population = sort_array_by_col(self.population, 0)
        self.population = self.calc_maximin(self.population)
        self.population = self.apply_constraints(self.population)
        if self.generation_call is not None:
            self.generation_call(self.population)
        return

    def select_parents(self):
        """select the parents from the current population of the optimization"""
        # randomize the order of the population
        np.random.shuffle(self.population)
        # preallocate the array to hold the parents
        parents = np.zeros_like(self.population)
        # self.population = self.calc_maximin(self.population)
        # select random people from the population for tournament selection
        for row in range(parents.shape[0]):
            rand_indicies = np.random.randint(parents.shape[0], size=self.tournament_size)
            competitors = self.population[rand_indicies]
            sorted_competitors = sort_array_by_col(competitors, 0)
            parents[row, :] = sorted_competitors[0]
        return parents

    def calc_maximin(self, population):
        """calculates the maximin values for each point of the supplied population.  Uses a bunch of information stored
        in the class, so probably not a good idea to pass in random populations, unless you know what you're doing."""
        for idx in range(population.shape[0]):
            # get function values
            fVals = copy.deepcopy(population[:, 1:self.num_objectives+1])
            for col_idx in range(self.num_objectives):
                test_val = fVals[idx, col_idx]
                fVals[:, col_idx] = -(fVals[:, col_idx] - test_val)
            fVals = np.delete(fVals, idx, 0)
            population[idx, 0] = np.nanmax(np.nanmin(fVals, 1))
        return population

    def apply_constraints(self, population):
        """ applies appropriate penalties for designs that are outside of the permissible bounds.  Requires that a
        constraint function be defined that returns the constraints in a row vector"""
        if self.constraint_func is None:
            return population
        max_fitness = np.nanmax(population[:, 0])
        for row in population:
            design = row[self.num_objectives+1:]
            if self.constraint_func_input == "design":
                cons = self.constraint_func(design)
            elif self.constraint_func_input == "full":
                cons = self.constraint_func(row)
            else:
                print("unrecognized constraint input term check constraint_func_input argument at initialization")
                quit()
            if np.max(cons) > 0:
                row[0] = max_fitness + np.max(cons)
        return population

    def find_min(self):
        generations = []
        for generation in range(self.num_generations):
            # select reproducing parents
            parents = self.select_parents()
            children = np.zeros_like(parents)
            # for each set of parents
            for idx in range(0, parents.shape[0], 2):
                child1 = copy.deepcopy(parents[idx, self.num_objectives+1:])
                child2 = copy.deepcopy(parents[idx+1, self.num_objectives+1:])
                for x_idx in range(len(child1)):
                    crossover = np.random.random()
                    mutate1 = np.random.random()
                    mutate2 = np.random.random()
                    if crossover < self.crossover_prob:
                        # perform the crossover
                        self.crossover(child1, child2, x_idx)
                    if mutate1 < self.mutation_prob:
                        child1 = self.mutate(child1, x_idx, self.x_def[x_idx]['bounds'],
                                             self.x_def[x_idx]['type'], generation)
                    if mutate2 < self.mutation_prob:
                        child2 = self.mutate(child2, x_idx, self.x_def[x_idx]['bounds'],
                                             self.x_def[x_idx]['type'], generation)
                # put the children into the children array
                child1_fitness = self.fitness_func(child1)
                child2_fitness = self.fitness_func(child2)
                children[idx, 1:self.num_objectives+1] = child1_fitness
                children[idx, self.num_objectives+1:] = child1
                children[idx + 1, 1:self.num_objectives+1] = child2_fitness
                children[idx + 1, self.num_objectives+1:] = child2
            # perform elitism
            population_pool = np.append(parents, children, axis=0)
            population_pool = self.calc_maximin(population_pool)
            population_pool = self.apply_constraints(population_pool)
            sorted_pool = sort_array_by_col(population_pool, 0)
            self.population = sorted_pool[0:self.num_population]
            # generations.append(copy.deepcopy(self.population))
            print(generation)
            if self.generation_call is not None:
                self.generation_call(self.population)
        return self.population

    def crossover(self, child1, child2, x_idx):
        """
        Performs crossover between the two children at the specifiec index.  The children must be numpy arrays or
        some other object that is mutable so that the changes persist
        :param child1: Child 1 to be crossed a numpy array of the values
        :param child2: Child 2 to be crossed a numpy array of the values
        :param x_idx: Index location for the crossover.
        :return: none
        """
        r = np.random.random()
        if r <= 0.5:
            a = ((2 * r) ** (1 / self.cross_eta)) / 2
        else:
            a = 1 - ((2 - 2 * r) ** (1 / self.cross_eta)) / 2
        child1_val = child1[x_idx]
        child2_val = child2[x_idx]
        y1 = a * child1_val + (1 - a) * child2_val
        y2 = (1 - a) * child1_val + a * child2_val
        child1[x_idx] = y1
        child2[x_idx] = y2
        # truncate the values if needed
        if self.x_def[x_idx]['type'] == 'integer':
            child1[x_idx] = int(np.round(child1[x_idx]))
            child2[x_idx] = int(np.round(child2[x_idx]))

    def mutate(self, child, idx, bounds, type, generation):
        """
        Perform a mutation on the child at the specified location
        :param child: array of values that represent the child to be mutated
        :param idx: the index where the mutation should occur
        :param bounds: bound of the value that is being mutated
        :param type: Type of the variable
        :param generation: generation number for the mutation.
        :return: the mutated child
        """
        min = bounds[0]
        max = bounds[1]
        r = np.random.uniform(min, max)
        alpha = (1 - (generation) / self.num_generations) ** self.mutation_beta
        if r <= child[idx]:
            child[idx] = min + (r - min) ** alpha * (child[idx] - min) ** (1 - alpha)
        else:
            child[idx] = max - (max - r) ** alpha * (max - child[idx]) ** (1 - alpha)
        if type == 'integer':
            child[idx] = np.round(child[idx])
        return child

def calc_fitness(x):
    width = x[0]
    height = x[1]

    length = 20
    force = 10
    modulus = 39000000
    density = 4.65 / 16

    max_weight = 200
    max_defl = 2

    deflection = (force * length**3) / (3 * modulus * (width * height**3)/12)
    # deflection = saturate(deflection, max_defl)/max_defl
    weight = length * width * height * density
    # weight = saturate(weight, max_weight)/max_weight
    return [deflection, weight]

def calc_fitness2(x):
    width = x[0]
    height = x[1]

    length = 20
    force = 10
    modulus = 39000000
    density = 4.65 / 16

    max_weight = 200
    max_defl = 2

    deflection = (force * length**3) / (3 * modulus * (width * height**3)/12)
    # deflection = saturate(deflection, max_defl)/max_defl
    weight = length * width * height * density
    # weight = saturate(weight, max_weight)/max_weight
    return [deflection]

def calc_constraints(x):
    width = x[0]
    height = x[1]

    length = 20
    force = 10
    modulus = 39000000
    density = 4.65 / 16

    max_deflection = 0.04
    max_weight = 10
    max_stress = 36000

    moment = length * force
    I = (width * height ** 3) / 12
    stress = moment * (height / 2) / I
    stress_constraint = (stress - max_stress) / max_stress

    deflection = (force * length ** 3) / (3 * modulus * (width * height ** 3) / 12)
    deflection_constraint = (deflection - max_deflection) / max_deflection

    weight = length * width * height * density
    weight_constraint = (weight - max_weight) / max_weight
    return [deflection_constraint, weight_constraint, stress_constraint]

def saturate(val, max_val):
    if val > max_val:
        val = max_val
    return val

if __name__ == "__main__":
    z = [{'type': 'continuous', 'bounds': (0, 2)},
         {'type': 'continuous', 'bounds': (0, 2)}]
    n_gen = 100
    opt = MultiObjectiveOptimizer(z, calc_fitness2, n_objectives=1, population_size=10, n_generations=n_gen,
                                  constraint=calc_constraints)
    # opt.calc_maximin(opt.population)
    generations = opt.find_min()

    # x_start = generations[0][:, 1]
    # y_start = generations[0][:, 2]
    #
    # x_middle = generations[int(n_gen/2)-1][:, 1]
    # y_middle = generations[int(n_gen/2)-1][:, 2]
    #
    # x_end = generations[-1][:, 1]
    # y_end = generations[-1][:, 2]

    # plt.plot(x_start, y_start, 'o', label='1st generation')
    # plt.plot(x_middle, y_middle, 'o', label='middle generation', alpha=0.5)
    # plt.plot(x_end, y_end, 'o', label='last generation', alpha=0.5)
    # plt.xlabel('deflection')
    # plt.ylabel('weight')
    # plt.title('weight vs. deflection pareto front')
    # # plt.xlim((0, 0.025))
    # # plt.ylim((0, 10))
    # plt.legend()
    # plt.show()

    plt.ion()
    for i, generation in enumerate(generations):
        # if i > 5:
        #     points.clear()
        points = plt.plot(generation[:, 1], generation[:, 2], 'o')
        plt.xlim((0, 0.05))
        plt.ylim((0, 3))
        plt.xlabel('deflection')
        plt.ylabel('weight')
        plt.title('weight vs. deflection pareto front')
        # plt.xlim((0, 1))
        # plt.ylim((0, 1))
        plt.pause(0.5)


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 09:53:06 2019

@author: CEC
"""

file = open("devices.txt", "a")
while True:
    newItem = input("New item:")
    if newItem == "exit":
        print("All done")
        break
    else:
        file.write(newItem + "\n")
file.close


import json
import sqlite3
from flask import Flask, render_template, request, g, jsonify

app = Flask(__name__)

DATABASE = './ass7.sqlite'

def make_dicts(cursor, row):
    return dict((cursor.description[idx][0], value)
                for idx, value in enumerate(row))

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
        db.row_factory = make_dicts
    return db

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            c = f.read()
            db.cursor().executescript(c)
            db.commit()

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    get_db().commit()
    return (rv[0] if rv else None) if one else rv

@app.route('/delete', methods=['POST'])
def delete_exercise():
    data = request.json.get('date_submitted', -1)
    if isinstance(data, int) and data > 0:
        query_db('DELETE FROM exercises WHERE date_submitted = ?;',
                args=(data,))
        return jsonify({'date_submitted': data})
    else:
        resp = jsonify({
            'error': 'Invalid date_submitted',
            'date_submitted': data
        })
        resp.status_code = 400
        return resp

def validate_request(req):
    if 'date_submitted' not in req:
        return {'error': 'date_submitted is a required field'}, 400
    elif not isinstance(req.get('reps', 0), int):
        return {'error': 'reps must be an integer', 'reps': req.get('reps')}, 400
    elif not isinstance(req.get('weight', 0), int):
        return {'error': 'weight must be an integer', 'weight': req.get('weight')}, 400
    elif not isinstance(req.get('name', ''), (str, unicode)):
        return {'error': 'name must be a string'}, 400
    elif not isinstance(req.get('lbs', True), bool):
        return {'error': 'lbs must be a boolean'}, 400
    elif not isinstance(req.get('date_submitted', 0), int):
        return {'error': 'date_submitted must be a unix epochinteger'}, 400
    else:
        return None, 200

@app.route('/create', methods=['POST'])
def create_exercise():
    error, status = validate_request(request.json)
    if status != 200:
        resp = jsonify(error)
        resp.status_code = status
        return resp

    args = (request.json.get('name', ''),
            request.json.get('reps', 0),
            request.json.get('weight', 0),
            request.json.get('lbs', True),
            request.json.get('date_submitted'))
    try:
        query_db('INSERT INTO exercises VALUES ((?), (?), (?), (?), (?))',
                args=args)
    except sqlite3.IntegrityError:
        resp = jsonify({'error': 'duplicate date submitted',
            'date_submitted': request.json.get('date_submitted')})
        resp.status_code = 400
        return resp
    return jsonify({'date_submitted': request.json.get('date_submitted')})

@app.route('/update', methods=['POST'])
def update_exercise():
    error, status = validate_request(request.json)
    if status != 200:
        resp = jsonify(error)
        resp.status_code = status
        return resp

    args = (request.json.get('name', ''),
            request.json.get('reps', 0),
            request.json.get('weight', 0),
            request.json.get('lbs', True),
            request.json.get('date_submitted'))
    query_db('UPDATE exercises SET name=?, reps=?, weight=?, lbs=? ' +
             'WHERE date_submitted=(?);', args=args)
    return jsonify({'date_submitted': request.json.get('date_submitted')})

@app.route('/edit', methods=['POST'])
def edit_exercise():

    ds = request.form.get('date_submitted', None)
    try:
        ds = int(ds)
    except:
        return render_template('oops.html', ds=ds)
    ds = int(ds)
    exercise = query_db('select * from exercises where date_submitted=(?)', args=[ds], one=True);
    if exercise:
        return render_template('edit.html', exercise=exercise)
    else:
        return render_template('oops.html', ds=ds)

@app.route('/')
def show_exercises():
    exercises = query_db('select * from exercises')
    return render_template('view.html', exercises=exercises)

if __name__ == '__main__':
    app.run()


import tkinter as tk
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
import time
from numpy import DataSource
from upload import Upload as up

class Application():

    def __init__(self,ws):
        self.up = up()
        self.ws=ws
        ws.title('Excel Worker')
        ws.geometry('400x200')
        self.create_widgets(ws)

    def create_widgets(self,ws):
        input = Label(ws, text='Upload first Input file in xlsx format')
        input.grid(row=0, column=0, padx=10)

        inputbtn = Button(ws, text ='Choose File', command = lambda:self.up.open_file('i',self.show_label_for_file_upload))
        inputbtn.grid(row=0, column=1)

        output = Label(ws, text='Upload secomd Input file in xlsx format')
        output.grid(row=1, column=0, padx=10)

        outputbtn = Button(ws, text ='Choose File ', command = lambda:self.up.open_file('o',self.show_label_for_file_upload))
        outputbtn.grid(row=1, column=1)

        filter = Label(ws,text='Upload filter data excel in xlsx format ')
        filter.grid(row=2, column=0, padx=10)

        filterbtn = Button(ws, text ='Choose File', command = lambda:self.up.open_file('f',self.show_label_for_file_upload))
        filterbtn.grid(row=2, column=1)

        upld = Button(ws, text='Upload Files', command=self.uploadFiles)
        upld.grid(row=3, columnspan=3, pady=10)

    def uploadFiles(self):
        if (self.up.hasValue(self.up.input1_file) and self.up.hasValue(self.up.filter_file)) \
            or (self.up.hasValue(self.up.input2_file) and self.up.hasValue(self.up.filter_file)):
            Label(ws, text='', foreground='green').grid(row=4, columnspan=3, pady=10)
            pb1 = Progressbar(
                ws,
                orient=HORIZONTAL,
                length=300,
                mode='determinate'
                )
            pb1.grid(row=4, columnspan=3, pady=20)
            self.up.uploadFiles()
            for i in range(5):
                ws.update_idletasks()
                pb1['value'] += 20
                time.sleep(1)
            pb1.destroy()
            self.show_label( text="Excel Copied Successfully!", color="green")
        else:
            self.show_label( text="Please upload a valid file", color="red")

    def show_label_for_file_upload(self,text,color):
        lbl1=Label(self.ws, text=text, foreground=color)
        lbl1.grid(row=4, columnspan=3, pady=5)

    def show_label(self,text,color):
        self.show_label_for_file_upload("                                        ","white")
        Label(self.ws, text=text, foreground=color).grid(row=6, columnspan=3, pady=10)

ws = Tk()
app = Application(ws)
ws.mainloop()


# Exo 1:
def multiplication(n1: int, n2: int) -> int:
    r = 0
    if n2 == 0:
        return r
    if n2 > 0:
        for _ in range(n2):
            r += n1
    if n2 < 0:
        for _ in range(-n2):
            r -= n1
    return r

assert multiplication(3, 5) == 15
assert multiplication(-4, -8) == 32
assert multiplication(-2, 6) == -12
assert multiplication(-2, 0) == 0

# Exo 2:
def dichotomie(tab, x):
    """
    tab : tableau d’entiers trié dans l’ordre croissant
    x : nombre entier
    La fonction renvoie True si tab contient x et False sinon
    """
    debut = 0
    fin = len(tab) - 1
    while debut <= fin:
        m = (debut+fin) // 2
        if x == tab[m]:
            return True
        if x > tab[m]:
            debut = m + 1
        else:
            fin = m - 1
    return False

assert dichotomie([15, 16, 18, 19, 23, 24, 28, 29, 31, 33], 28) == True
assert dichotomie([15, 16, 18, 19, 23, 24, 28, 29, 31, 33], 27) == False


from .configs import *
from . import query
from . import utils
from collections import OrderedDict
import subprocess
import sys

'''
parser table

Table name: _tagit_parser_{name}

Desc: Maintains metadata for parsing rules

Layout:

             rule             |    src_dtag     |      dest_dtag      | updated
------------------------------+-----------------+---------------------+--------
 awk '/^IOPS/{print \$NF}'    | _tagit_data_raw | _tagit_data_iops    | False
 awk '/^latency/{print \$NF}' | _tagit_data_raw | _tagit_data_latency | True

Columns:
- name: The name of a tag
- src_dtag: The source dtag from which the rule will get input
- dest_dtag: The destination dtag to which the rule output will be saved
- updated: Has the rule been updated or newly added since the last parsing,
           so the parsing rules affected by the rule cannot skip during report?

'''

def parser_id(exp_name: str) -> str:
    if utils.is_prohibited_name(exp_name):
        print("Interal error: wrong exp_name format")
        sys.exit(-1)

    return parser_prefix + exp_name

def is_parser_id(table: str) -> bool:
    if table.startswith(parser_prefix):
        return True

    return False

def _exists(pid):
    if query.table_exists(pid):
        return True

    return False

def exists(exp_name):
    pid = parser_id(exp_name)
    return _exists(pid)

def _create(pid):
    query.create_table(pid, ["rule", "src_dtag", "dest_dtag", "updated"])

def create(exp_name):
    pid = parser_id(exp_name)
    _create(pid)

def get(exp_name):
    pid = parser_id(exp_name)

    if _exists(pid):
        data = query.get_entities(pid, {}, [])
    else:
        data = []

    return data

def add(exp_name, rule, dtag_src, dtag_dest):
    pid = parser_id(exp_name)

    # Create parser for the experiment if it has not been created yet
    if not _exists(pid):
        _create(pid)

    params = OrderedDict([
        ("rule", rule),
        ("src_dtag", dtag_src),
        ("dest_dtag", dtag_dest),
        ("updated", "True")
        ])
    query.add_entity(pid, params)

def _delete(pid):
    _validate(pid)
    query.drop_table(pid)

def delete(exp_name):
    pid = parser_id(exp_name)
    _delete(pid)

def rename(old_exp_name, new_exp_name):
    old_pid = parser_id(old_exp_name)
    new_pid = parser_id(new_exp_name)

    query.rename_table(old_pid, new_pid)

def _validate(pid):
    if not _exists(pid):
        print("Internal error: no such parser")
        sys.exit(-1)

def validate(exp_name):
    if not exists(exp_name):
        print("Internal error: no such parser")
        sys.exit(-1)

def reset_status(exp_name: str):
    pid = parser_id(exp_name)
    if not _exists(pid):
        return

    query.update_row(pid, {}, {"updated": "False"})

def build_parsing_graph(exp_name: str):
    """
    Build the parsing graph of an experiment.

    :param exp_name: Name of the experiment
    :return: The parsing graph and if any rule is added or updated since the
    last parsing
    :rtype: (dict, bool)
    """
    pid = parser_id(exp_name)
    if not _exists(pid):
        return {}

    updated_global = False
    graph = {}
    rules = query.get_entities(pid, {}, [])
    for rule in rules:
        src = rule['src_dtag']
        dest = rule['dest_dtag']
        cmd = rule['rule']
        updated = rule['updated']
        edge = {'src': src, 'cmd': cmd, 'updated': updated}

        if dest in graph:
            graph[dest].append(edge)
        else:
            graph[dest] = [edge]

        updated_global |= updated == "True"

    return graph, updated_global

def parse_data(exp_name, src, dest, cmd, params, data):
    if data is None:
        return "\n"

    try:
        ret = subprocess.run(cmd, input=data, capture_output=True,
                shell=True, text=True)
    except TypeError:
        # Python < 3.7
        ret = subprocess.run(cmd, input=data, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, shell=True, universal_newlines=True)

    ret_stdout = ret.stdout
    ret_stderr = ret.stderr

    if ret_stderr:
        if ret_stderr.endswith('\n'):
            ret_stderr = ret_stderr[:-1]
        print(ret_stderr)

    return ret_stdout

def remove_rule(exp_name, rule_id):
    # TODO: support multi-valued rule_id
    if rule_id is None:
        print("Error: no parsing rule id is provided")
        sys.exit(-1)

    pid = parser_id(exp_name)
    query.delete_rows(pid, OrderedDict([]), offset=rule_id, limit=1)

def remove_all_rules(exp_name):
    pid = parser_id(exp_name)
    query.delete_rows(pid, OrderedDict([]))


import torch
import math
from math import cos, sin, atan
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d

class MFNN(nn.Module):
    ''' Multi-fidelity neural network (Meng and Karniadakis 2019):
        - nn_l: a neural network which generates predictions of the
        low-fidelity data
        - nn_h1: a neural network which computes linear correlation between
        the low- and high-fidelity data
        - nn_h2: a neural network which computes nonlinear correlation
        between the low- and high-fidelity data '''

    def __init__(self, nn_l, nn_h1, nn_h2, dim_out=1, use_yl2=False, tau=None):
        super(MFNN, self).__init__()
        self.nn_l = nn_l
        self.nn_h1 = nn_h1
        self.nn_h2 = nn_h2
        self.use_yl2 = use_yl2
        self.tau=tau
        self.dim_out=dim_out

    def forward(self, x):
        # Compute low-fidelity prediction (y_l) via nn_l.
        y_l = self.nn_l(x)
        if self.use_yl2 and self.tau:
            y_l2 = self.nn_l(x-self.tau)
        # Compute linear and nonlinear correlations (F_l, F_nl) via
        # nn_h1 and nn_h2.
        if self.use_yl2 and self.tau:
            F_l = self.nn_h1(torch.cat((x, y_l), 1))
            F_nl = self.nn_h2(torch.cat((x, y_l, y_l2), 1))
        else:
            F_l = self.nn_h1(torch.cat((x, y_l), 1))
            F_nl = self.nn_h2(torch.cat((x, y_l), 1))
        # Compute multi-fidelity prediction (h_1) from F_l and F_nl.
        y_h = F_l + F_nl
        return torch.cat((y_l, y_h), 1)

    def draw(self,
             number_of_neurons_in_widest_layer,
             vertical_distance_between_layers = 6,
             horizontal_distance_between_neurons = 2,
             neuron_radius = 0.5,
            ):
        network = NeuralNetwork()
        for (name, param) in self.named_parameters():
            network.add_layer(4, weights1)


"""
问题
你正在试着使用正则表达式去匹配一大块的文本，而你需要跨越多行去匹配。
"""

import re
comment = re.compile('/\*(.*?)\*/')
text1 = '/* this is a comment */'
text2 = '/* this is \
        multiline comment */'
print(comment.findall(text1))
# [' this is a comment ']
print(comment.findall(text2))
# [' this is         multiline comment ']

comment2 = re.compile('/\*(.*?|\n)\*/')
print(comment2.findall(text2))


import hashlib

key = "bgvyzdsv"
p2 = False

number = 1

s_w = '00000'
if p2:
    s_w = '000000'

while True:
    if hashlib.md5(bytes(key + str(number), 'utf-8')).hexdigest().startswith(s_w):
        print(number)
        break
    number += 1


# 숫자로 이루어진 문자열 t와 p가 주어질 때, t에서 p와 길이가 같은 부분문자열 중에서, 이 부분문자열이 나타내는 수가 p가 나타내는 수보다 작거나 같은 것이 나오는 횟수를 return하는 함수 solution을 완성하세요.
# t="3141592"이고 p="271" 인 경우, t의 길이가 3인 부분 문자열은 314, 141, 415, 159, 592입니다. 이 문자열이 나타내는 수 중 271보다 작거나 같은 수는 141, 159 2개 입니다.

# 내 풀이
def solution(t, p):
    arr = []
    cnt = 0
    for i in range(len(t)-len(p)+1):  # 이부분은 몰라서 참고했다. 문자열 t의 맨 앞부터 p의 길이를 뺀 만큼 접근해야 list index out of range가 안나온다.
        arr.append(t[i:i+len(p)])  # "시작점 ~ 시작점+p의 개수" 까지 t에서 슬라이싱
    for j in arr:
        if int(j) <= int(p):
            cnt +=1

    return cnt

# 다른사람 풀이
def solution(t, p):
    answer = 0

    for i in range(len(t) - len(p) + 1):
        if int(p) >= int(t[i:i+len(p)]):
            answer += 1

    return answer

프로그래머스/Python/1단계/크기가 작은 부분문자열.py

크기가 작은 부분문자열.py


#python
import sys
import lx
import lxu
from mecco_utils_contexts import catch

# returns current scene as an lxu.object.Scene instance
GetScene = lxu.select.SceneSelection().current

def GetItemsOfType(nameFilter, *itemTypes):
    """ Returns all items in scene of *itemTypes (item type strings or ints),
        matching nameFilter string. Empty string or None will match all items. """
    scene = GetScene()
    items = []
    nameFilter = str() or nameFilter
    for itemType in itemTypes:
        with catch('item type "%s" not found' % itemType, False, LookupError):
            if type(itemType) == str:
                itemType = svc_scene.ItemTypeLookup(itemType)
            if type(svc_scene.ItemTypename(itemType)) is type(None):
                raise LookupError

            num = scene.ItemCount(itemType)
            for n in xrange(num):
                item = scene.ItemByIndex(itemType, n)
                if nameFilter in item.UniqueName():
                    items.append(item)
    return items

def InitXfrms(item):
    """ Initializes zero-transforms for a given item.
        item = lx.object.Item or
               lxu.object.Item instance """
    with catch("InitXfrms %s" % item.UniqueName(), True):
        #get a chanWrite interface
        scene = GetScene()
        chanRead = scene.Channels(lx.symbol.s_ACTIONLAYER_EDIT, 0.0)
        chanWrite = lx.object.ChannelWrite(chanRead)

        #get a locator interface for item
        loc = lx.object.Locator(item)

        #scale
        try:
            scl = loc.GetTransformItem(lx.symbol.iXFRM_SCALE)
        except LookupError:
            scl = loc.AddTransformItem(lx.symbol.iXFRM_SCALE)[0]
        #position
        try:
            pos = loc.GetTransformItem(lx.symbol.iXFRM_POSITION)
        except LookupError:
            pos = loc.AddTransformItem(lx.symbol.iXFRM_POSITION)[0]
        #rotation
        try:
            rot = loc.GetTransformItem(lx.symbol.iXFRM_ROTATION)
        except LookupError:
            rot = loc.AddTransformItem(lx.symbol.iXFRM_ROTATION)[0]

        #write zeroes...
        for chanIdx in range(2, 5):
            chanWrite.Double(scl, chanIdx, 1.0)
            chanWrite.Double(pos, chanIdx, 0.0)
            chanWrite.Double(rot, chanIdx, 0.0)

def MakeInstance(item, transform):
    """ Creates an instance of input item based on the input transform
        item =  lx.object.Item or
                lxu.object.Item instance
        transforms = transform for new instances

        A transform is a tuple of tuples for the scale, rotation
        and position of the new instance:
        (
            (scl_x, scl_y, scl_z),
            (rot_x, rot_y, rot_z),
            (pos_x, pos_y, pos_x),
        )

        returns the new instance
    """

    scene = GetScene()
    chanRead = scene.Channels(lx.symbol.s_ACTIONLAYER_EDIT, 0.0)
    chanWrite = lx.object.ChannelWrite(chanRead)

    #create a new instance of the mesh item
    inst = scene.ItemInstance(item)

    #set the instance to be a child of the mesh
    inst.SetParent(item)

    #initialize transforms for the instance
    InitXfrms(inst)

    #get a locator interface for the instance
    loc = lx.object.Locator(inst)
    t_items = ( loc.GetTransformItem(lx.symbol.iXFRM_SCALE),
                loc.GetTransformItem(lx.symbol.iXFRM_ROTATION),
                loc.GetTransformItem(lx.symbol.iXFRM_POSITION))

    for a, b in enumerate(t_items):
        #a = (0, 1, 2)
        #b = transform item
        b = lx.object.Item(b)
        for xfrmIdx, chanIdx in zip(range(3), range(2,5)):
            # lx.out("chanIdx: %s" % chanIdx)
            # lx.out("xfrmIdx: %s" % xfrmIdx)
            chanWrite.Double(b, chanIdx, transform[a][xfrmIdx])

    return inst


# from databaseX import DatabaseX
from prettytable import PrettyTable
from colores import Colores
from dxLogic import Logic

class AlimentacionLogic(Logic):
    def __init__(self):
        super().__init__()

    def getAgregar(self, idAlimento, idUser, porcion):
        self.database.executeNonQueryBool(
            "INSERT INTO `myfitapp`.`consumoalimento`(`id_consumoAlimento`,`id_producto`,`id_usuario`,`porcion`,`fecha`) "
            + f"VALUES(0,{idAlimento},{idUser},{porcion}, CURDATE());"
        )

    def getBuscar(self, idUser, alimento):

        busqueda = self.database.executeQueryRows(
            f"SELECT * FROM myfitapp.producto WHERE nombre like '%{alimento}%' and id_usuario = 0 or id_usuario = {idUser};"
        )

        return busqueda

    def getBuscarDos(self, idAlimentacion, idUser):

        sqlCount = f"SELECT COUNT(*) FROM myfitapp.producto WHERE id_producto = {idAlimentacion} and (id_usuario = 0 or id_usuario = {idUser});"

        # Imprime para comprobar estructura del sqlCount
        # print(sqlCount)

        rowsNumDic = self.database.executeQueryOneRow(sqlCount)

        # Imprime el diccionario resultante de ejecutar sqlCount
        # print(rowsNumDic)

        rowsNum = rowsNumDic.get("COUNT(*)")

        # Imprime el numero de filas con ese ID de alimento
        # print(rowsNum)
        return rowsNum

    def crearReceta(
        self,
        nombre,
        porciones,
        calorias,
        grasaTotales,
        colesterol,
        sodio,
        azucares,
        idUser,
    ):

        self.database.executeNonQueryBool(
            "INSERT INTO `myfitapp`.`producto`(`id_producto`,`nombre`,`porcion`,`calorias`,`grasasTotales`,`colesterol`,`sodio`,`azucares`,`id_usuario`) "
            + f"VALUES(0,'{nombre}', {porciones}, {calorias}, {grasaTotales}, {colesterol}, {sodio},{azucares}, {idUser});"
        )


#!/usr/bin/env python3

import serial
import serial.tools.list_ports
import numpy as np
from threading import Lock
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QDoubleValidator
from .fl266_config_ui import Ui_FL266_Config_Window

import traceback
import logging
from PyQt5.QtCore import QObject, pyqtSignal

_SPLIT_LOG = False

if _SPLIT_LOG:
    fl266_logger = logging.getLogger("fl266")
    fl266_logger.setLevel(logging.DEBUG)
    fl266_fh = logging.FileHandler("fl266.log")
    fl266_formatter = logging.Formatter('%(asctime)s [%(component)s] - %(levelname)s - %(message)s')
    fl266_fh.setFormatter(fl266_formatter)
    fl266_logger.addHandler(fl266_fh)

    fl266_ch = logging.StreamHandler()
    fl266_ch.setFormatter(fl266_formatter)
    fl266_logger.addHandler(fl266_ch)
else:
    fl266_logger = logging.getLogger("autools_setup_main")

class FL266Man(QObject):
    """
    """
    opened = pyqtSignal()
    closed = pyqtSignal()
    power_changed = pyqtSignal(int, name='powerChanged')
    frequency_changed = pyqtSignal(int, name='frequencyChanged')
    laser_state_changed = pyqtSignal(bool, name="laserStateChanged")

    def __init__(self,
                 serial_name=None,
                 baudrate=9600,
                 parity=serial.PARITY_NONE,
                 stopbits=serial.STOPBITS_ONE,
                 uart_lock=None):
        super().__init__()
        self.com_dev = serial_name
        self.ser_baudrate = baudrate
        self.ser_parity = parity
        self.ser_stopbits = stopbits

        if self.com_dev is None:
            self.ser = None
        else:
            self.ser = serial.Serial(port=serial_name,
                                     baudrate=baudrate,
                                     bytesize=serial.EIGHTBITS,
                                     parity=parity,
                                     stopbits=stopbits)
            self.ser.inter_byte_timeout = 0.1  # when device failed to send next byte within 0.1 read will exit
            if not self.ser.is_open:
                raise IOError(f"Failed to open the device {self.com_dev}")

        if uart_lock is None:
            self.ser_lock = Lock()
        else:
            self.ser_lock = uart_lock

        self.config_window = None

    def open(self):
        if self.ser is not None and self.ser.is_open:
            self.ser.close()

        self.ser = serial.Serial(port=self.com_dev, baudrate=self.ser_baudrate, bytesize=serial.EIGHTBITS,
                                 parity=self.ser_parity, stopbits=self.ser_stopbits)

        self.ser.inter_byte_timeout = 0.1

        if not self.ser.is_open:
            raise IOError(f"Failed to open the device {self.com_dev}")
        else:
            self.opened.emit()

    def close(self):
        if self.ser is not None and self.ser.is_open:
            self.ser.close()
        self.closed.emit()
        self.ser = None

    def is_open(self):
        return self.ser is not None and self.ser.is_open

    CMD_SET=0x01
    CMD_GET=0x00

    def send_cmd(self, cmd: bytes or bytearray, cmd_type: int):
        if cmd_type not in (FL266Man.CMD_SET, FL266Man.CMD_GET):
            raise ValueError(f"Unknown command type: {cmd_type}")
        fl266_logger.debug(f"Sending command: {'GET' if cmd_type == FL266Man.CMD_GET else 'SET'}: {cmd}", extra={"component": "FL266"})
        with self.ser_lock:
            self.ser.write(cmd)
            if cmd_type == FL266Man.CMD_GET:
                ans = self.ser.read(10)
            else:
                ans = self.ser.read(9)

            return ans

    @staticmethod
    def fill_cmd_checksum(cmd: bytes or bytearray):
        if type(cmd) is bytes:
            cmd = bytearray(cmd)
        ck = sum(cmd)
        return ck&0xFF

    @staticmethod
    def compose_cmd(ch: int, cmd_type: int, data: bytes):
        if cmd_type not in (FL266Man.CMD_SET, FL266Man.CMD_GET):
            raise ValueError(f"Unknown command type: {cmd_type}")
        cmd_pre = b'\x53\x0a'+(ch&0xFF).to_bytes(1, byteorder='big') + (cmd_type&0xFF).to_bytes(1, byteorder='big') + data[0:4]
        cmd = cmd_pre + FL266Man.fill_cmd_checksum(cmd_pre).to_bytes(1, byteorder='big') + b'\x0d'
        return cmd

    @staticmethod
    def check_response(res: bytes or bytearray, ch: int, cmd_type: int):
        if cmd_type not in (FL266Man.CMD_SET, FL266Man.CMD_GET):
            raise ValueError(f"Unknown command type: {cmd_type}")
        if (cmd_type == FL266Man.CMD_GET and len(res) != 9) or \
            (cmd_type == FL266Man.CMD_SET and len(res) != 10):
            return False, f"wrong response length: {len(res)}"
        if type(res) is bytes:
            res = bytearray(res)
        # check header
        if (cmd_type == FL266Man.CMD_SET and res[0:2] != b'\x41\x09') or \
                (cmd_type == FL266Man.CMD_GET and res[0:2] != b'\x53\x0a'):
            return False, f"wrong response header: {res[0:2]}"
        # check ch
        if res[2] != ch & 0xFF:
            return False, f"wrong response CH: {res[2]}"
        if res[3] != cmd_type:
            return False, f"wrong response CMD: {res[3]}"

        if cmd_type == FL266Man.CMD_SET:
            if res[4:7] == b'\x4f\x4b\x21':
                pass
            elif res[4:7] == b'\x45\x52\x52':
                return False, f"ERROR response"
            else:
                return False, f"UNKNOWN response"

            if res[7] != FL266Man.fill_cmd_checksum(res[:7]):
                return False, f"wrong response CHKSUM: {res[7]}"
            if res[8] != b'\x0d':
                return False, f"wrong response tail: {res[8]}"
            return True, ""
        else:
            if res[8] != FL266Man.fill_cmd_checksum(res[:8]):
                return False, f"wrong response CHKSUM: {res[8]}"
            if res[9] != b'\x0d':
                return False, f"wrong response tail: {res[8]}"
            return True, res[4:8]

    def set_power_perc(self, perc: int):
        if perc < 0:
            perc = 0
        elif perc > 100:
            perc = 100
        cmd = FL266Man.compose_cmd(0x01, FL266Man.CMD_SET, perc)
        ack = self.send_cmd(cmd, FL266Man.CMD_SET)
        ok, msg = FL266Man.check_response(ack, 0x01, FL266Man.CMD_SET)
        if not ok:
            fl266_logger.error(f"Failed to set power {perc}: {msg}", extra={"component": "FL266"})
        else:
            fl266_logger.debug(f"Set power {perc} OK", extra={"component": "FL266"})
            self.power_changed.emit(perc)

    def set_frequency(self, freq: int):
        # 100kHz (0064) - 1Mhz
        # FIXME: Missing the part for freq -> payload
        cmd = FL266Man.compose_cmd(0x0e, FL266Man.CMD_SET, freq)
        ack = self.send_cmd(cmd, FL266Man.CMD_SET)
        ok, msg = FL266Man.check_response(ack, 0x0e, FL266Man.CMD_SET)
        if not ok:
            fl266_logger.error(f"Failed to set frequency {freq}: {msg}", extra={"component": "FL266"})
        else:
            fl266_logger.debug(f"Set frequency with {freq} OK", extra={"component": "FL266"})
            self.frequency_changed.emit(freq)

    def turn_on_off(self, on_off: bool):
        cmd = FL266Man.compose_cmd(0x00, FL266Man.CMD_SET, b'\x00\x00\x00\x01' if on_off else b'\x00\x00\x00\x00')
        ack = self.send_cmd(cmd, FL266Man.CMD_SET)
        ok, msg = FL266Man.check_response(ack, 0x00, FL266Man.CMD_SET)
        if not ok:
            fl266_logger.error(f"Failed to turn laser {'on' if on_off else 'off'}: {msg}", extra={"component": "FL266"})
        else:
            fl266_logger.debug(f"Turn laser {'on' if on_off else 'off'} OK", extra={"component": "FL266"})
            self.laser_state_changed.emit(on_off)

    def show_config_window(self):
        if self.config_window is None:
            self.config_window = FL266ConfigWindow(self)

        self.config_window.show()

# noinspection PyPep8Naming
def get_available_COMs():
    com_port_list = serial.tools.list_ports.comports()
    return {com.device: f'{com.manufacturer} {com.description}' for com in com_port_list}

class FL266ConfigWindow(Ui_FL266_Config_Window):
    def __init__(self, fl266man: FL266Man):
        self.fl266man = fl266man
        self.window = QWidget()
        Ui_FL266_Config_Window.__init__(self)
        self.setupUi(self.window)

        self.pushButton_COM_Refresh.clicked.connect(self.refresh_comlist)
        self.pushButton_COM_Open.clicked.connect(self.open_conn_clicked)

        self.comboBox_COM_BaudRate.currentTextChanged.connect(self.baudrate_changed)
        self.comboBox_COM_Parity.currentTextChanged.connect(self.parity_changed)
        self.comboBox_COM.currentIndexChanged.connect(self.com_changed)

        self.refresh_comlist()

        self.checkBox_LaserON.clicked.connect(self.laser_onoff_clicked)
        self.pushButton_SetPowerPerc.clicked.connect(
            lambda: self.fl266man.set_power_perc(self.spinBox_PowerPerc.value()))
        self.pushButton_SetFrequency.clicked.connect(
            lambda: self.fl266man.set_frequency(self.spinBox_Frequency.value()))

    def laser_onoff_clicked(self):
        if self.checkBox_LaserON.isChecked():
            self.fl266man.turn_on_off(True)
            self.pushButton_SetPowerPerc.setEnabled(True)
        else:
            self.fl266man.turn_on_off(False)
            self.pushButton_SetPowerPerc.setEnabled(False)

    def refresh_comlist(self):
        self.comboBox_COM.clear()
        com_dict = get_available_COMs()
        for com_dev in com_dict.keys():
            self.comboBox_COM.addItem(com_dev + ':' + com_dict[com_dev], com_dev)

    def com_changed(self):
        self.fl266man.com_dev = self.comboBox_COM.currentData()

    def parity_changed(self, p: str):
        if p == 'None':
            self.fl266man.ser_parity = serial.PARITY_NONE
        elif p == 'ODD':
            self.fl266man.ser_parity = serial.PARITY_ODD
        elif p == 'EVEN':
            self.fl266man.ser_parity = serial.PARITY_EVEN
        else:
            raise ValueError(f"Unknown parity {p}")

    def baudrate_changed(self, b: int or str):
        if type(b) is str:
            b = int(b)
        self.fl266man.ser_baudrate = b

    def open_conn_clicked(self, state):
        if not state:  # post event state
            self.close_conn()
        else:
            self.open_conn()

    def open_conn(self):
        try:
            self.fl266man.open()
            self.pushButton_COM_Open.setText("Close")
            self.pushButton_COM_Open.setChecked(True)
            # Disable the COM configuration input
            self.comboBox_COM.setDisabled(True)
            self.comboBox_COM_BaudRate.setDisabled(True)
            self.comboBox_COM_Parity.setDisabled(True)
            self.pushButton_COM_Refresh.setDisabled(True)
            # Enable the settings input
            self.groupBox_Settings.setDisabled(False)
            self.pushButton_SetPowerPerc.setDisabled(True)
            self.label_COM_Status.setStyleSheet("background: green")
            fl266_logger.info(f"FL266 COM connection opened", extra={"component": "FL266"})

            fl266_logger.debug(f"FL266 COM: {self.fl266man.com_dev} "
                              f"B:{self.fl266man.ser_baudrate} "
                              f"P:{self.fl266man.ser_parity} "
                              f"S:{self.fl266man.ser_stopbits}", extra={"component": "FL266"})
        except Exception as e:
            traceback.print_tb(e.__traceback__)
            fl266_logger.error(f"Failed to open FL266 COM connection", extra={"component": "FL266"})
            self.close_conn()

    def close_conn(self):
        self.fl266man.close()
        self.pushButton_COM_Open.setText("Open")
        self.pushButton_COM_Open.setChecked(False)
        # Enable the COM configuration input
        self.comboBox_COM.setDisabled(False)
        self.comboBox_COM_BaudRate.setDisabled(False)
        self.comboBox_COM_Parity.setDisabled(False)
        self.pushButton_COM_Refresh.setDisabled(False)
        # Disable the settings input
        self.groupBox_Settings.setDisabled(True)
        self.label_COM_Status.setStyleSheet("background: red")
        self.fl266man.turn_on_off(False)
        fl266_logger.info(f"FL266 COM connection closed", extra={"component": "FL266"})

    def show(self):
        self.window.show()

    def close(self):
        self.window.hide()

if __name__ == "__main__":
    from PyQt5.QtWidgets import QApplication

    app = QApplication([])
    fl266man = FL266Man()
    fl266man.show_config_window()
    app.exec_()


def sortuj(s):
    """
    :param s: słowo
    :return: posortowane alfabetycznie słowo
    """
    n = len(s)
    s = list(s)
    for j in range(n - 1, 0, -1):
        for i in range(j):
            if s[i] > s[i + 1]:
                s[i], s[i + 1] = s[i + 1], s[i]
    s = ''.join(s)
    return s

def anagramy():
    """
    :return: sprawdza czy podane słowa są anagramem
    """
    s1 = input("podaj pierwsze słowo: ")
    s2 = input("podaj drugie słowo: ")
    if len(s1) == len(s2):
        if sortuj(s1) == sortuj(s2):
            return True
        else:
            return False
    else:
        return False

anagramy()


import cv2
from datetime import datetime
import numpy as np
import os
import re
import sys
from tqdm import tqdm

from .detect import Detect

class Camera:
    """Manage and control the USB camera"""

    # -----------------
    # class attributes
    # -----------------

    # video source
    cam_num = 1 # 1 is the usb cam on thor
    video_path = None

    # camera configuration
    fps = None
    image_size = None
    record = None
    show_view = None
    tensor_image_size = None

    # streamers and recorder
    stream = None
    video_recorder = None
    video_detect_recorder = None

    def __init__(self, cam_num = 1, video_path = None):
        """Initialize Camera Class"""

        # set class variables
        self.cam_num = cam_num
        self.video_path = video_path

    def configure(self, fps = 30, image_size = [640, 480], record = False,
            show_view = False, tensor_image_size = [800, 600]):
        """configure camera specifications"""
        self.fps = fps
        self.image_size = (image_size[0], image_size[1])
        self.record = record
        self.show_view = show_view
        self.tensor_image_size = tensor_image_size

    def detect(self):
        """
        TODO Finish Documentation Numpy Style
        """

        if self.video_path is None: # stream from camera
            self.stream = cv2.VideoCapture(self.cam_num)
        elif self.video_path is not None: # stream from video
            self.stream = cv2.VideoCapture(self.video_path)
        else: # unexpected error
            print("An unexpected error occurred when starting video stream!")
            sys.exit(0)

        if self.record:
            self.startVideoRecorder()
            self.startVideoDetectionRecorder()

        # initialize detector
        detector = Detect()

        # start the streaming loop
        try:
            while(self.stream.isOpened()):
                # capture frame by frame
                ret, frame = self.stream.read()

                # make sure the frames are reading
                if not ret:
                    print("Unable to receive frame.")
                    break

                # send the frame through the object detector
                detect_frame = detector.inference(frame)

                # check if user wants to record
                if self.record:
                    self.video_recorder.write(frame)
                    self.video_detect_recorder.write(detect_frame)

                # check if user wants to see the cam's view
                if self.show_view:
                    cv2.imshow("Your Eye", frame)
                    cv2.imshow("God's Eye", detect_frame)

                # run until key press 'q'
                QUIT_KEY = 'q'
                if cv2.waitKey(1) == ord(QUIT_KEY):
                    break
        except KeyboardInterrupt:
            pass

        # release the capture
        self.stream.release()
        if self.record:
            self.video_recorder.release()
            self.video_detect_recorder.release()
        cv2.destroyAllWindows()

    def startVideoDetectionRecorder(self, path=None, image_size=None):
        """create recorder for detection video stream"""

        # set attributes for video recorder
        CODEC = 'XVID'
        fourcc = cv2.VideoWriter_fourcc(*CODEC)
        date = datetime.now()

        if image_size is not None:
            self.image_size = image_size

        if path is None:
            # create video recorder
            self.video_detect_recorder = cv2.VideoWriter('videos/recording_detect_'
                                + str(date.month) + '-'
                                + str(date.day) + '-'
                                + str(date.year) + '_'
                                + str(date.hour) + '-'
                                + str(date.minute) + '-'
                                + str(date.second) + '_'
                                + '.avi', fourcc, self.fps, self.image_size)
        else:
            # define regex to extract group number
            r_group = re.compile(r'(?<=/)group[0-9]{3}(?=/)')

            # get file name and group from video path
            base_name = "inference_{}".format(os.path.basename(self.video_path))
            group = re.findall(r_group, self.video_path)[0]

            # define output directory
            output_dir = 'output'

            # if output dir does not exist, make it
            if not os.path.isdir(output_dir):
                os.mkdir(output_dir)

            # if group in output dir does not exist, make it
            elif not os.path.isdir(os.path.join(output_dir, group)):
                os.mkdir(os.path.join(output_dir, group))
            else:
                pass

            # define video recorder
            self.video_detect_recorder = cv2.VideoWriter(
                                            os.path.join(output_dir,
                                                         group,
                                                         base_name),
                                            fourcc,
                                            self.fps,
                                            self.image_size)

            # end function
            return

    def startVideoRecorder(self):
        """create recorder for video stream"""

        # set attributes for video recorder
        CODEC = 'XVID'
        fourcc = cv2.VideoWriter_fourcc(*CODEC)
        date = datetime.now()

        # create video recorder
        self.video_recorder = cv2.VideoWriter('videos/recording_'
                                + str(date.month) + '-'
                                + str(date.day) + '-'
                                + str(date.year) + '_'
                                + str(date.hour) + '-'
                                + str(date.minute) + '-'
                                + str(date.second) + '_'
                                + '.avi', fourcc, self.fps, self.image_size)

    def startVideoStream(self):
        """load video stream from video or camera"""

        if self.video_path is None: # stream from camera
            stream = cv2.VideoCapture(self.cam_num)
        elif self.video_path is not None: # stream from video
            stream = cv2.VideoCapture(self.video_path)
        else: # unexpected error
            print("An unexpected error occurred when starting video stream!")
            sys.exit(0)

        # verify stream functionality
        if not stream.isOpened():
            print("ERROR: unable to load video stream.")
            sys.exit(0)

        # set stream to class attribute
        self.stream = stream

        # create video recorder
        if self.record:
            self.startVideoRecorder()

        # start the streaming loop
        try:
            while(self.stream.isOpened()):
                # capture frame by frame
                ret, frame = self.stream.read()

                # make sure the frames are reading
                if not ret:
                    print("Unable to receive frame.")
                    break

                if self.record:
                    self.video_recorder.write(frame)

                # show frame
                if self.show_view:
                    cv2.imshow("Current View", frame)

                # run until key press 'q'
                QUIT_KEY = 'q'
                if cv2.waitKey(1) == ord(QUIT_KEY):
                    break
        except KeyboardInterrupt:
            pass

        # release the capture
        self.stream.release()
        if self.record:
            self.video_recorder.release()
        cv2.destroyAllWindows()

    def process_prerecorded(self):
        """run prerecorded videos through ml pipeline"""

        # start video stream
        self.stream = cv2.VideoCapture(self.video_path)

        # get length of video
        num_frames = self.stream.get(cv2.CAP_PROP_FRAME_COUNT)

        # initialize detector
        detector = Detect()

        # define tqdm object
        progressBar = tqdm(total=num_frames, ncols=100)

        # start the streaming loop
        try:
            while(self.stream.isOpened()):
                # capture frame by frame
                ret, frame = self.stream.read()

                # make sure the frames are reading
                if ret:
                    # check if video recorder has been initialized
                    if self.video_detect_recorder is None:
                        # define video recorder
                        self.startVideoDetectionRecorder(
                            path = self.video_path,
                            image_size = (frame.shape[1], frame.shape[0]))

                    # send the frame through the object detector
                    detect_frame = detector.inference(frame)

                    # update progress bar
                    progressBar.update(1)

                    # record detected frame
                    self.video_detect_recorder.write(detect_frame)
                elif not ret:
                    break
        except KeyboardInterrupt:
            pass

        # release the capture
        self.stream.release()
        self.video_detect_recorder.release()

        # end function
        return


import yaml

def read_config(file: str) -> dict:
    """
    Helper function to read the configuration file (yml format).
    :param file: config file name
    :return: configuration dict
    """
    global cfg
    with open(file, 'r') as ymlfile:
        cfg = yaml.load(ymlfile, Loader=yaml.CLoader)
    return cfg


import os
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime

import common

def model_file_path(model_id):
    date = datetime.now()
    ts = date.strftime("%d_%m_%Y-%H:%M:%S")
    model_fname = '-'.join((model_id, ts))
    return os.path.join(common.MODEL_PATH, model_fname)

def model_results_path(model_id):
    if not os.path.exists(common.OUT_DIR):
        os.mkdir(common.OUT_DIR)

    model_dir = os.path.join(common.OUT_DIR, model_id)
    if not os.path.exists(model_dir):
        os.mkdir(model_dir)

    date = datetime.now()
    ts = date.strftime("%d_%m_%Y-%H:%M:%S")
    base_dir_name = '-'.join((model_id, ts))
    base_dir = os.path.join(model_dir, base_dir_name)
    os.mkdir(base_dir)
    print("Created model directory:", base_dir)

    dir_paths = {}
    for dir_name, sub_dirs in common.DIR_STRUCTURE.items():
        result_dir = os.path.join(base_dir, dir_name)
        os.mkdir(result_dir)
        dir_paths[dir_name] = result_dir
        for sub_dir_name in sub_dirs:
            sub_dir = os.path.join(result_dir, sub_dir_name)
            os.mkdir(sub_dir)
            dir_paths[sub_dir_name] = sub_dir

    return base_dir, dir_paths

def train_results_path(base_dir, prefix, layer):
    results_fname = "{}-{}.npy".format(prefix, layer)
    return os.path.join(base_dir, common.METRICS_DIR, common.TRAINING_DIR, results_fname)

def prune_results_path(base_dir, prefix, layer):
    results_fname = "{}-{}.npy".format(prefix, layer)
    return os.path.join(base_dir, common.METRICS_DIR, common.PRUNING_DIR, results_fname)

"""
def prune_results_path(model_id, layer, pruning_method, pruning_ratio, metric):
    date = datetime.now()
    ts = date.strftime("%d_%m_%Y-%H:%M:%S")
    results_fname = '-'.join((model_id, layer, pruning_method, pruning_ratio, metric, ts))
    return os.path.join(common.PRUNE_METRICS_PATH, results_fname)
"""

def plot_test_acc(base_dir):
    acc_path = os.path.join(base_dir, common.METRICS_DIR, common.TRAINING_DIR, common.ACCURACY_FNAME)
    test_accuracies = np.load(acc_path)
    plt.plot(test_accuracies)
    plt.title('Testset accuracy')
    plt.xlabel('Epoch')
    plt.ylabel('Accuracy (%)')
    plt.show()

def plot_train_fps(fp_paths, layers):
    n_plots = len(layers)
    fig, axs = plt.subplots(n_plots, 1, figsize=(8, 20), sharex=True)
    for i, layer in enumerate(layers):
        layer_fp = np.load(fp_paths[layer])
        axs[i].plot(layer_fp)
        axs[i].set_title(f"Frame potential of {layer}")

    fig.suptitle("Frame potential (FP) during training", fontsize=16)
    fig.text(0.5, 0.04, 'Epoch', ha='center')
    fig.text(0.04, 0.5, 'FP', va='center', rotation='vertical')

def draw_acc_plot(layer, exp_acc_fname, pruning_acc_fname, *, figsize=(25, 12), fig_name=""):
    plt.figure(figsize=figsize)

    pruning_acc = np.load(pruning_acc_fname, allow_pickle=True).item()
    for pruning_method, acc in pruning_acc.items():
        n_obs = len(acc)
        plt.plot(acc, label=pruning_method)

    if exp_acc_fname:
        exp_acc = np.load(exp_acc_fname)
        random_accuracies = exp_acc.mean(axis=0)
        random_std_devs = exp_acc.std(axis=0)
        plt.errorbar(range(n_obs), random_accuracies, random_std_devs, linestyle='None',
                     marker='.', label="random pruning")

    plt.title("Accuracy after pruning " + layer)
    elem_type = "neurons" if layer[:2] == "fc" else "filters"
    plt.xlabel("Pruned " + elem_type)
    plt.ylabel("Accuracy (%)")
    plt.legend(loc="best")

    if fig_name:
        fig_path = os.path.join(common.FIGURE_PATH, fig_name)
        plt.savefig(fig_path, format="png")
    else:
        plt.show()

def draw_fps_plot(layer, exp_fps_fname, pruning_fps_fname, *, figsize=(25, 12), fig_name=""):
    plt.figure(figsize=figsize)

    pruning_fps = np.load(pruning_fps_fname, allow_pickle=True).item()
    for pruning_method, fps in pruning_fps.items():
        n_obs = len(fps)
        plt.plot(fps, label=pruning_method)

    if exp_fps_fname:
        exp_fps = np.load(exp_fps_fname)
        random_fps = exp_fps.mean(axis=0)
        random_std_devs = exp_fps.std(axis=0)
        plt.errorbar(range(n_obs), random_fps, random_std_devs, linestyle='None',
                     marker='.', label="random pruning")

    plt.title("Frame potential after pruning " + layer)
    elem_type = "neurons" if layer[:2] == "fc" else "filters"
    plt.xlabel("Pruned " + elem_type)
    plt.ylabel("FP")
    plt.legend(loc="best")

    if fig_name:
        fig_path = os.path.join(common.FIGURE_PATH, fig_name)
        plt.savefig(fig_path, format="png")
    else:
        plt.show()

def draw_sched_plot(layer, acc_fname, pruning_method, pruning_ratio, *, figsize=(14, 7), fig_name=""):
    plt.figure(figsize=figsize)

    accuracies = np.load(acc_fname, allow_pickle=True).item()
    for init_time, acc in accuracies.items():
        if init_time == -1:
            plt.plot(accuracies[init_time], label="No pruning")
        elif init_time == 0:
            plt.plot(accuracies[init_time], label="{}% random_pruning before training".format(int(pruning_ratio * 100)))
        else:
            plt.plot(accuracies[init_time],
                     label="{}% {} after iteration {}".format(int(pruning_ratio * 100), pruning_method, init_time))
    plt.title(f"Testset accuracy (pruning {layer})")
    plt.xlabel("Time")
    plt.ylabel("Accuracy (%)")
    plt.legend(loc="best")

    if fig_name:
        fig_path = os.path.join(common.FIGURE_PATH, fig_name)
        plt.savefig(fig_path, format="png")
    else:
        plt.show()


#
# @lc app=leetcode.cn id=105 lang=python
#
# [105] 从前序与中序遍历序列构造二叉树
#
# https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (62.44%)
# Likes:    288
# Dislikes: 0
# Total Accepted:    34K
# Total Submissions: 54K
# Testcase Example:  '[3,9,20,15,7]\n[9,3,15,20,7]'
#
# 根据一棵树的前序遍历与中序遍历构造二叉树。
#
# 注意:
# 你可以假设树中没有重复的元素。
#
# 例如，给出
#
# 前序遍历 preorder = [3,9,20,15,7]
# 中序遍历 inorder = [9,3,15,20,7]
#
# 返回如下的二叉树：
#
#    3
#   / \
#  9  20
#    /  \
#   15   7
#
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 203/203 cases passed (176 ms)
# Your runtime beats 47.52 % of python submissions
# Your memory usage beats 11.94 % of python submissions (86.4 MB)
class Solution(object):
    def buildTree(self, preorder, inorder):
        if not preorder:
            return None

        rootValue = preorder[0]

        index = inorder.index(rootValue)

        root = TreeNode(rootValue)

        root.left = self.buildTree(preorder[1:index+1],inorder[:index])
        root.right = self.buildTree(preorder[index+1:],inorder[index+1:])
        return root

# @lc code=end

105.从前序与中序遍历序列构造二叉树.py


from playsound import playsound
from termcolor import colored, cprint
import random

player_score = 0
dealer_score = 0
total_hands = 0

#Dealing Cards
def deal_card(turn):
    card = random.choice(deck)
    turn.append(card)
    deck.remove(card)

# Calculate the total of each hand
def total(turn):
    total = 0
    face = ['j', 'q', 'k']
    for card in turn:
        if card in range (1,11):
            total += card
        elif card in face:
            total += 10
        else:
            if total > 11:
                total += 1
            else:
                total += 11
    return total

# Check for winner
def show_dealer_hand():
    if len(dealer_hand) == 2:
        return dealer_hand[0]
    elif len(dealer_hand) > 2:
        return dealer_hand[0],dealer_hand[1]

#game loop

while True:
    print(colored("\n----------Black Jack ------------", "cyan"))
    game_start = input(colored("Do you want to Play: \n Yes or No", "cyan"))
    if game_start == "yes":
        print("lets get started")
    else:
        break

    player_active = True
    dealer_active = True

    #Deck of cards / player hands
    deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'j', 'q', 'k', 'a',
        2, 3, 4, 5, 6, 7, 8, 9, 10, 'j', 'q', 'k', 'a',
        2, 3, 4, 5, 6, 7, 8, 9, 10, 'j', 'q', 'k', 'a',
        2, 3, 4, 5, 6, 7, 8, 9, 10, 'j', 'q', 'k', 'a']
    player_hand = []
    dealer_hand = []
    for x in range(2):
        deal_card(dealer_hand)
        deal_card(player_hand)
    while player_active or dealer_active:
        playsound('Dealing.wav')
        print(colored("-----------------------------", 'green'))
        print("   Dealer has:",    show_dealer_hand(),"       ")
        print(colored("-----------------------------", 'green'))
        print(colored("-----------------------------", 'red'))
        print(f"You have {player_hand}. total of {total(player_hand)}")
        print(colored("-----------------------------", 'red'))

        if player_active:
            stay_hit = input(colored("1:Stay\n2:Hit\n  ", "blue"))
        if total (dealer_hand) > 16:
            dealer_active = False
        else:
            deal_card(dealer_hand)
        if stay_hit == "1":
            player_active = False
        else:
            deal_card(player_hand)
        if total(player_hand) >= 21:
            break
        elif total(dealer_hand) >= 21:
            break
    if total(player_hand) == 21:
        print(f"\nYou have {player_hand} for a total of {total(player_hand)}\n and the dealer has {dealer_hand} for a total of {total(dealer_hand)}")
        playsound('BlackJack.wav')
        print("BlackJack!")

    elif total(dealer_hand) == 21:
        print(f"\nYou have {player_hand} for a total of {total(player_hand)}\n and the dealer has {dealer_hand} for a total of {total(dealer_hand)}")
        playsound('Busted.mp3')
        print("BlackJack!")

    elif total(player_hand) > 21:
        print(colored("---------------------------", 'red'))
        print(f"You have {player_hand}. total of {total(player_hand)}")
        print(colored("---------------------------", 'red'))
        playsound('Busted.mp3')
        print("you busted :( Dealer wins")

    elif total(dealer_hand) > 21:
        print(colored("--------------------------", 'green'))
        print(f"Dealer has {dealer_hand}. total of {total(dealer_hand)}")
        print(colored("--------------------------", 'green'))
        print(colored("--------------------------", 'red'))
        print(f"You have {player_hand}. total of {total(player_hand)}")
        print(colored("--------------------------", 'red'))
        print("Dealer busted :( You win")

    elif 21 - total(dealer_hand) < 21 - total(player_hand):
        print(colored("--------------------------", 'green'))
        print(f"Dealer has {dealer_hand}. total of {total(dealer_hand)}")
        print(colored("--------------------------", 'green'))
        print(colored("--------------------------", 'red'))
        print(f"You have {player_hand}. total of {total(player_hand)}")
        print(colored("-------------------------", 'red'))
        print("dealer wins!")

    elif  21 - total(dealer_hand) > 21 - total(player_hand):
        print(colored("------------------------", 'green'))
        print("|    Dealer has:",    show_dealer_hand(),"       ")
        print(colored("--------------------------", 'green'))
        print(colored("--------------------------", 'red'))
        print(f"You have {player_hand}. total of {total(player_hand)}")
        print(colored("-------------------------", 'red'))
        print("You win")


"""
-*- coding: UTF-8 -*-
@Time : 2023/3/21  19:10
@Description :
@Author : Huizhi XU
"""

import configparser
import os.path

# Open a configuration file
config = configparser.ConfigParser()
file_path = os.path.dirname(os.path.abspath('.')) + 'config.ini' #返回上级目录再访问某文件（路径根据实际情况自定义）
config.read(file_path)
open_ai_key = str(config.get("open_ai", "OPENAI_API_KEY"))
serapi_key = str(config.get("serp_api", "SERPAPI_API_KEY"))


"""Lazy sequences.

>>> from lazysequence import lazysequence
>>>
>>> def load_records():
...     return range(10)  # let's pretend this is expensive
...
>>> records = lazysequence(load_records())
>>> if not records:
...     raise SystemExit("no records found")
...
>>> first, second = records[:2]
>>>
>>> print("The first record is", first)
The first record is 0
>>> print("The second record is", second)
The second record is 1
>>>
>>> for record in records.release():  # do not cache all records in memory
...     print("record", record)
...
record 0
record 1
record 2
record 3
record 4
record 5
record 6
record 7
record 8
record 9
"""
from __future__ import annotations

from dataclasses import dataclass
from itertools import chain
from itertools import count
from itertools import islice
from typing import Iterable
from typing import Iterator
from typing import MutableSequence
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Sized
from typing import Tuple
from typing import TypeVar
from typing import Union

_T_co = TypeVar("_T_co", covariant=True)

def _positive(index: int, size: int) -> int:
    """Convert a negative index to a non-negative integer.

    The index is interpreted relative to the position after the last item. If
    the index is smaller than ``-size``, IndexError is raised.
    """
    assert index < 0  # noqa: S101
    index += size

    if index < 0:
        raise IndexError("lazysequence index out of range")

    return index

def _positivestart(start: int, size: int) -> int:
    """Convert a negative start index to a non-negative integer.

    The index is interpreted relative to the position after the last item. If
    the index is smaller than ``-size``, zero is returned.
    """
    assert start < 0  # noqa: S101
    return max(0, start + size)

def _positivestop(stop: int, size: int, step: int) -> Optional[int]:
    """Convert a negative stop index to a non-negative integer.

    The index is interpreted relative to the position after the last item. If
    the index is smaller than ``-size``, the return value depends on ``step``.
    If ``step`` is positive, zero is returned. If ``step`` is negative, None is
    returned. Returning None for reverse slices ensures that an expression such
    as ``s[:-1000:-1]`` includes the first element of ``s``.
    """
    assert stop < 0  # noqa: S101

    stop += size
    if stop >= 0:
        return stop

    return 0 if step > 0 else None

@dataclass(frozen=True)
class _slice:  # noqa: N801
    """Slice representation.

    Attributes:
        start: The position of the first item, either None or a non-negative
            integer.
        stop: The position after the last item, either None or a non-negative
            integer.
        step: The distance between successive items, any integer except zero.
    """

    start: Optional[int]
    stop: Optional[int]
    step: int

    def __init__(
        self, start: Optional[int], stop: Optional[int], step: Optional[int]
    ) -> None:
        """Initialize."""
        if step == 0:
            raise ValueError("slice step cannot be zero")

        if step is None:
            step = 1

        object.__setattr__(self, "start", start)
        object.__setattr__(self, "stop", stop)
        object.__setattr__(self, "step", step)

    def astuple(self) -> Tuple[Optional[int], Optional[int], int]:
        """Return the attributes as a tuple."""
        return self.start, self.stop, self.step

    def apply(self, iterable: Iterable[_T_co], sized: Sized) -> Iterator[_T_co]:
        """Yield items from the iterable corresponding to this slice."""
        return islice(iterable, *self.astuple())

    def length(self, sized: Sized) -> int:
        """Return the number of items corresponding to this slice."""
        origin = self

        if origin.step < 0:
            origin = origin.reverse(sized)

        start, stop, step = origin.astuple()
        size = len(sized)

        if stop is not None:
            size = min(size, stop)

        if start is not None:
            size = max(0, size - start)

        if size > 0:
            # This is equivalent to `math.ceil(result / step)`, but avoids
            # floating-point operations and importing `math`.
            size = 1 + (size - 1) // abs(step)

        return size

    def reverse(self, sized: Sized) -> _slice:
        """Return the equivalent slice for a reversed sequence."""
        assert self.step < 0  # noqa: S101

        start, stop, step = self.astuple()
        size = len(sized)
        step = -step

        if start is None:
            start = size - 1

        start = (size - 1) - start
        start = max(0, start)

        if stop is None:
            stop = size
        else:
            stop = (size - 1) - stop

        stop = max(0, stop)

        return _slice(start, stop, step)

    def resolve(self, index: int, sized: Sized) -> int:
        """Return the equivalent index on the underlying sequence.

        In pseudo-code: ``s[slice][index] === s[slice.resolve(index)]``
        """
        if index < 0:
            index = _positive(index, self.length(sized))

        return self._resolve(index, sized, strict=True)

    def _resolve(self, index: int, sized: Sized, *, strict: bool = True) -> int:
        assert index >= 0  # noqa: S101
        return (
            self._resolveforward(index, sized, strict=strict)
            if self.step > 0
            else self._resolvebackward(index, sized, strict=strict)
        )

    def _resolveforward(self, index: int, sized: Sized, *, strict: bool = True) -> int:
        """Resolve index on a forward slice, where start <= stop and step > 0."""
        assert self.step > 0  # noqa: S101

        start, stop, step = self.astuple()

        if start is None:
            start = 0

        index = start + index * step

        if stop is not None and index >= stop:
            if strict:
                raise IndexError("lazysequence index out of range")

            # Default to the last valid slot.
            return max(0, stop - 1)

        return index

    def _resolvebackward(self, index: int, sized: Sized, *, strict: bool = True) -> int:
        """Resolve index on a backward slice, where start >= stop and step < 0."""
        assert self.step < 0  # noqa: S101

        size = len(sized)
        start, stop, step = self.astuple()

        if start is None:
            start = size - 1

        start = min(start, size - 1)
        index = start + index * step

        if index < 0 or stop is not None and index <= stop:
            if strict:
                raise IndexError("lazysequence index out of range")

            # Default to the first valid slot.
            return stop + 1 if stop is not None else 0

        return index

    def resolveslice(self, slice: _slice, sized: Sized) -> _slice:
        """Return the equivalent slice on the underlying sequence.

        In pseudo-code: ``s[slice0][slice1] === s[slice0.resolve(slice1)]``
        """
        start, stop, step = slice.astuple()

        start = self._resolvestart(start, step, sized)
        stop = self._resolvestop(stop, step, sized)
        step *= self.step

        return _slice(start, stop, step)

    def _resolvestart(
        self, start: Optional[int], step: int, sized: Sized
    ) -> Optional[int]:
        if start is not None and start < 0:
            start = _positivestart(start, self.length(sized))

        if start is not None:
            return self._resolve(start, sized, strict=False)

        if step > 0:
            return self.start

        if self.stop is None:
            return None

        return self.stop + 1 if self.step < 0 else self.stop - 1

    def _resolvestop(
        self, stop: Optional[int], step: int, sized: Sized
    ) -> Optional[int]:
        if stop is not None and stop < 0:
            stop = _positivestop(stop, self.length(sized), step)

        if stop is not None:
            return self._resolve(stop, sized, strict=False)

        if step > 0:
            return self.stop

        if self.start is None:
            return None

        return self.start + 1 if self.step < 0 else self.start - 1

_defaultslice = _slice(None, None, None)

class lazysequence(Sequence[_T_co]):  # noqa: N801
    """A lazy sequence provides sequence operations on an iterable.

    Args:
        iterable: The iterable being wrapped.
    """

    def __init__(
        self,
        iterable: Iterable[_T_co],
        *,
        _cache: Optional[MutableSequence[_T_co]] = None,
        _slice: _slice = _defaultslice,
    ) -> None:
        """Initialize."""
        parent = self

        class _Total(Sized):
            def __len__(self) -> int:
                parent._fill()
                return len(parent._cache)

        self._iter = iter(iterable)
        self._cache = [] if _cache is None else _cache
        self._slice = _slice
        self._total = _Total()

    def _consume(self) -> Iterator[_T_co]:
        """Yield from the iterator, adding each item to the cache."""
        for item in self._iter:
            self._cache.append(item)
            yield item

    def _fill(self) -> None:
        """Add all items from the iterator to the cache."""
        self._cache.extend(self._iter)

    def _iterate(self, iterator: Iterator[_T_co]) -> Iterator[_T_co]:
        """Iterate over the items in the sequence."""
        slice = self._slice

        if slice.step < 0:
            slice = slice.reverse(self._total)

            self._fill()
            iterator = reversed(self._cache)

        return slice.apply(iterator, self._total)

    def __iter__(self) -> Iterator[_T_co]:
        """Iterate over the items in the sequence."""

        def generate() -> Iterator[_T_co]:
            """Essentially the same as ``chain(self._cache, self._consume())``.

            Other instances may be consuming items from the iterator though, so
            after each ``next()`` on the iterator, try the cache again. Also,
            yield from the cache first, as it's much faster than the loop below.
            """
            yield from self._cache

            offset = len(self._cache) + 1
            consumer = self._consume()

            try:
                yield next(consumer)

                for index in count(offset):  # pragma: no branch
                    try:
                        yield self._cache[index]
                    except IndexError:
                        yield next(consumer)
            except StopIteration:
                pass

        return self._iterate(generate())

    def release(self) -> Iterator[_T_co]:
        """Iterate over the sequence without caching additional items.

        The sequence should no longer be used after calling this function. The
        same applies to slices of the sequence obtained by using ``s[i:j]``.

        Yields:
            The items in the sequence.
        """  # noqa: DAR201, DAR302
        iterator = chain(self._cache, self._iter)
        return self._iterate(iterator)

    def __bool__(self) -> bool:
        """Return True if there are any items in the sequence."""
        for _ in self:
            return True
        return False

    def __len__(self) -> int:
        """Return the number of items in the sequence."""
        return self._slice.length(self._total)

    def _getitem(self, index: int) -> _T_co:
        """Return the item at the given index."""
        index = self._slice.resolve(index, self._total)

        try:
            return self._cache[index]
        except IndexError:
            pass

        index -= len(self._cache)

        try:
            return next(islice(self._consume(), index, None))
        except StopIteration:
            raise IndexError("lazysequence index out of range") from None

    def _getslice(self, indices: slice) -> lazysequence[_T_co]:  # noqa: C901
        """Return a slice of the sequence."""
        slice = _slice(indices.start, indices.stop, indices.step)
        slice = self._slice.resolveslice(slice, self._total)

        return lazysequence(self._iter, _cache=self._cache, _slice=slice)

    @overload
    def __getitem__(self, index: int) -> _T_co:
        """Return the item at the given index."""  # noqa: D418

    @overload
    def __getitem__(self, indices: slice) -> lazysequence[_T_co]:
        """Return a slice of the sequence."""  # noqa: D418

    def __getitem__(
        self, index: Union[int, slice]
    ) -> Union[_T_co, lazysequence[_T_co]]:
        """Return the item at the given index, or a slice of the sequence."""
        return (
            self._getslice(index) if isinstance(index, slice) else self._getitem(index)
        )


import json
import boto3
import os
from boto3.dynamodb.conditions import Key, Attr

table_name = os.environ['CINEMA_TABLE']

dynamodb = boto3.resource('dynamodb')
cinema_table = dynamodb.Table(table_name)

def add_reservation(event, context):
    # show_id, person_id -> body
    body = json.loads(event["body"])
    cinema_table.update_item(
        Key={
            'pk': 'show_' + body["show_id"],
            'sk': 'person_' + body["person_id"]
        }
    )
    print(json.dumps(event))
    return {
        'statusCode': 200,
        'body': json.dumps({
            "success": True
        })
    }
def display_show(event, context):
    # /show/{show_id}
    path_parameters = event["pathParameters"]
    show_id = path_parameters["show_id"]
    response = cinema_table.query(
        KeyConditionExpression=Key('pk').eq('show_' + show_id)
    )
    items = response['Items']
    print(items)
    return {
        'statusCode': 200,
        'body': json.dumps({
            "success": True,
            "list": items
        })
    }

def display_movie(event, context):
    # /?movie_id={movie_id}
    query_params = event["queryStringParameters"]
    movie_id = query_params["movie_id"]
    response = cinema_table.query(
        KeyConditionExpression=Key('pk').eq('movie_' + movie_id)
    )
    items = response['Items']
    print(items)
    return {
        'statusCode': 200,
        'body': json.dumps({
            "success": True,
            "list": items
        })
    }


def solution(numbers):
    # 숫자를 문자열로 변환합니다.
    numbers = list(map(str, numbers))

    numbers.sort(key=lambda x: x*3, reverse=True)

    answer = ''.join(numbers)

    if answer[0] == '0':
        answer = '0'

    return answer

프로그래머스/lv2/42746. 가장 큰 수/가장 큰 수.py


import random
from GeoGo_players import *

class Game:
    def __init__(self, playerlist):
        self.players = playerlist
        self.deck = []
        self.table_stack = []

    def shuffle_deck(self):
        tempdeck = []
        for letter in "abcdefghijklmnopqr":
            for number in [0, 1, 2, 3, 4]:
                tempdeck.append(Card(letter, number))
        for i in range(0, 90):
            # print(i)
            tempcard = tempdeck.pop(random.randint(0, 89 - i))
            self.deck.append(tempcard)

    def show_deck(self):
        print("Size of deck is " + str(len(self.deck)) + " cards.")
        print(self.deck)

    def get_deck_card(self):
        if len(self.deck) > 0:
            return self.deck.pop(0)
        elif len(self.table_stack) > 0:
            return self.table_stack.pop()
        else:
            raise RuntimeError("get_deck_card() called on empty deck and stack.")

    def get_table_stack_card(self):
        if len(self.table_stack) > 0:
            return self.table_stack.pop()
        elif len(self.deck) > 0:
            return self.deck.pop(0)
        else:
            raise RuntimeError("get_table_stack_card() called on empty deck and stack.")

    def view_table_stack_top(self):
        if len(self.table_stack) > 0:
            return self.table_stack[-1]
        else:
            return Card("s", -1)

    def add_to_stack(self, card):
        self.table_stack.append(card)

    def play_game(self):
        playernum = 0
        self.deck = []
        self.shuffle_deck()
        self.table_stack = []
        for player in self.players:
            player.game = self
            player.hand = []
            player.table = []
            for _ in range(0, 10):
                player.hand.append(self.deck.pop(0))
        while len(self.deck) > 0 or len(self.table_stack) > 0:
            # print("\n\nCards in deck: " + str(len(self.deck)))
            # print("Cards in table-stack: " + str(len(self.table_stack)))
            print("\nPlayer " + str(playernum) + ":")
            # self.players[playernum].show_hand()
            self.players[playernum].move()
            playernum += 1
            playernum = playernum % len(self.players)
        print("Scores:")
        scoretable = []
        for i in range(len(self.players)):
            print("Player" + str(i) + ": " + str(self.players[i].calculate_score()) + " pts.")
            scoretable.append(self.players[i].calculate_score())
        return scoretable

class Card:
    def __init__(self, letter, number): # 18 letters [a-r], 5 numbers [0-4] -> a stack holds 90 cards
        if letter in "abcdefghijklmnopqrs":
            self.letter = letter
        else:
            raise ValueError("Cards may only be of letter [a-s].")
        if number in [-1, 0, 1, 2, 3, 4]:
            self.number = number
        else:
            raise ValueError("Cards may only be of number [-1,4].")

    def __repr__(self):
        return "|" + self.letter + str(self.number) + "|"

    def __str__(self):
        return "|" + self.letter + str(self.number) + "|"

if __name__ == "__main__":
    player0 = DoubleDownPlayer()
    player1 = DoubleDownPlayer()
    player2 = DoubleDownPlayer()
    mygame = Game([player0, player1, player2])
    # player1.show_hand()
    # player2.show_hand()
    # mygame.show_deck()
    score_table = [0, 0, 0]
    for i in range(10):
        temp_table = mygame.play_game()
        for i in range(len(temp_table)):
            score_table[i] += temp_table[i]

    print()
    print(score_table)


from flask import Flask, render_template, Response
import cv2
import numpy as np
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model

app = Flask(__name__)
model = load_model(r"C:\Users\ashis\OneDrive\Desktop\dataset2\Saved models\ResNet50_faceMask.h5")
cap = cv2.VideoCapture(0)  # use 0 for default camera, or specify a camera index if you have multiple cameras

# Define the class labels
class_labels = {'Mask': 0, 'No mask': 1}
labels = dict((v, k) for k, v in class_labels.items())
# your code for starting the process
def start_process():
    pass

# your code for stopping the process
def stop_process():
    # add your code here
    cap.release()
    pass

@app.route('/')
def index():
    return render_template('index.html')

# function to handle the video feed
def gen():
    # add your code to generate the video feed
    while True:
        success, frame = cap.read()
        if not success:
            break
        else:
            # Resize frame to match the input size of the model
            frame = cv2.resize(frame, (224, 224))

            # Preprocess the frame for inference
            x = image.img_to_array(frame)
            x = np.expand_dims(x, axis=0)
            x = preprocess_input(x)

            # Make predictions
            preds = model.predict(x)
            pred_classes = np.argmax(preds, axis=1)

            # Map predicted classes to their corresponding class labels
            pred_class_label = labels[pred_classes[0]]
            # Get the percentage of certainty (confidence score) for the prediction
            confidence = preds[0][pred_classes[0]] * 100

            # Change color to red if predicted class is "No Mask"
            if pred_class_label == "No mask":
                color = (0, 0, 255)  # Red color
            else:
                color = (0, 255, 0)  # Green color

            # Draw the predicted class label and confidence score on the frame
            text = f"{pred_class_label}: {confidence:.2f}%"
            cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)

            # Encode the frame as a jpeg image
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()

            # Yield the frame as a multipart response
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/start')
def start():
    start_process()
    return "Process started"

@app.route('/stop')
def stop():
    stop_process()
    return "Process stopped"

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


from orator.migrations import Migration

class CreateSchedulesTable(Migration):

    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create('schedules') as table:
            table.increments('id')
            table.string('service')
            table.string('month')
            table.string('day')
            table.string('time')
            table.string('daytime')

            table.integer('schedule_id').unsigned()
            table.foreign('schedule_id').references('id').on('users')
            table.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop('schedules')


from google.appengine.api import memcache
from google.appengine.ext import db
import database
import time
import logging

'''The method gets the cache of page with pagename. If not cached yet, it reads from data base'''
def cache_get(pagename):
    result = memcache.get(pagename)
    if result is None:  #no cookie
        page = db.GqlQuery("select * from Page WHERE pagename=:1" , pagename).get()
        if page == None:  #no data or cookie
            return (None, None)
        else:
            time_last = page.created
            memcache.set(pagename, (page, time_last))   #the cache is stored with additional information of last time cache was edited'
    else:
        page, time_last = result

    return (page, time_last)

'''The method edits the page object. It basically adds a new page object into database each time edited.
   It also update the cache of the page with pagename to the latest edit'''
def cache_edit(pagename, content):
    time_last = time.time()
    page = database.Page(pagename = pagename, content = content)
    page.put()
    memcache.set(pagename, (page, content))

    return (page, time_last)