import numpy as np
import viscous_porepy as pp
import viscous_porepy.ad as ad
import time

from simulator import adaptivity
from utils import projection
from utils import viz
from utils import utils

def initiate_simulation(problem, disc):
    """
    Obtain discretization operators, projection operators, initial values,
    boundary conditions, etc.
    """
    # Get information from problem
    gb = problem.gb
    flow_kw = problem.flow_keyword
    tran_kw = problem.transport_keyword

    # define shorthand notation for discretizations
    # Flow
    flux = disc.mat[flow_kw]["flux"]
    bound_flux = disc.mat[flow_kw]["bound_flux"]
    trace_p_cell = disc.mat[flow_kw]["trace_cell"]
    trace_p_face = disc.mat[flow_kw]["trace_face"]
    bc_val_p = disc.mat[flow_kw]["bc_values"]
    i_x = disc.mat[flow_kw]["i_x"]  # moving frame velocity
    kn = disc.mat[flow_kw]["kn"]
    mu = problem.viscosity

    # Transport
    diff = disc.mat[tran_kw]["flux"]
    bound_diff = disc.mat[tran_kw]["bound_flux"]
    trace_c_cell = disc.mat[tran_kw]["trace_cell"]
    trace_c_face = disc.mat[tran_kw]["trace_face"]
    bc_val_c = disc.mat[tran_kw]["bc_values"]
    Dn = disc.mat[tran_kw]["dn"]

    # Define projections between grids
    (
        primary2mortar,
        secondary2mortar,
        mortar2primary,
        mortar2secondary,
    ) = projection.mixed_dim_projections(gb)
    # And between cells and faces
    avg = projection.cells2faces_avg(gb)
    div = projection.faces2cells(gb)

    # Assemble geometric values
    mass_weight = disc.mat[tran_kw]["mass_weight"]
    cell_volumes = gb.cell_volumes() * mass_weight
    mortar_volumes = gb.cell_volumes_mortar()
    # mortar_area = mortar_volumes * (primary2mortar * avg * specific_volume)
    return (
        gb,
        flux,
        bound_flux,
        trace_p_cell,
        trace_p_face,
        bc_val_p,
        i_x,
        kn,
        mu,
        diff,
        bound_diff,
        trace_c_cell,
        trace_c_face,
        bc_val_c,
        Dn,
        primary2mortar,
        secondary2mortar,
        mortar2primary,
        mortar2secondary,
        avg,
        div,
        mass_weight,
        cell_volumes,
        mortar_volumes,
    )

def initiate_variables(disc, c0):
    """
    Find the initial solution
    """
    gb = disc.problem.gb
    lam_c0 = np.zeros(gb.num_mortar_cells())
    # Initial guess for the pressure and mortar flux
    p0_init = np.zeros(gb.num_cells())
    lam0_init = np.zeros(gb.num_mortar_cells())
    # Define Ad variables
    p, lam = ad.initAdArrays([p0_init, lam0_init])
    # define dofs indices
    p_ix = slice(gb.num_cells())
    lam_ix = slice(gb.num_cells(), gb.num_cells() + gb.num_mortar_cells())
    c_ix = slice(
        gb.num_cells() + gb.num_mortar_cells(),
        2 * gb.num_cells() + gb.num_mortar_cells(),
    )
    lam_c_ix = slice(
        2 * gb.num_cells() + gb.num_mortar_cells(),
        2 * gb.num_cells() + 2 * gb.num_mortar_cells(),
    )
    # Solve with Newton (should converge in 1 or 2 iterations. Is non-linear due to
    # upstream weights)
    sol = np.hstack((p.val, lam.val))
    q = np.zeros(gb.num_faces())

    err = np.inf
    newton_it = 0
    newton_it = 0
    while err > 1e-9:
        newton_it += 1
        q = darcy(disc, p, c0, lam)
        eq_init = ad.concatenate(
            (
                mass_conservation(disc, lam, q),
                coupling_law_p(disc, p, lam, c0),
            )
        )
        err = np.max(np.abs(eq_init.val))
        sol = sol - disc.linear_solver(eq_init.jac, eq_init.val)
        p.val = sol[p_ix]
        lam.val = sol[lam_ix]

        if newton_it > 20:
            raise RuntimeError('Failed to converge Newton iteration in variable initiation')

    # Now that we have solved for initial condition, initalize full problem
    p, lam, c, lam_c = ad.initAdArrays([p.val, lam.val, c0, lam_c0])
    sol = np.hstack((p.val, lam.val, c.val, lam_c.val))

    q = darcy(disc, p, c, lam)
    return p, lam, q, c, lam_c, sol, p_ix, lam_ix, c_ix, lam_c_ix

def darcy(disc, p, c, lam):
    """
    Discretization of Darcy's law
    """
    kw = disc.problem.flow_keyword
    flux = disc.mat[kw]["flux"]
    bound_flux = disc.mat[kw]["bound_flux"]
    bc_val_p = disc.mat[kw]["bc_values"]
    i_x = disc.mat[kw]["i_x"]  # moving frame velocity
    mu = disc.viscosity()

    mortar2primary = disc.proj["mortar2primary"]
    v = flux * p
    return (
        (flux * p) * (mu(disc.upwind(c, v)) ** -1)
        + bound_flux * bc_val_p
        + bound_flux * mortar2primary * lam
        - i_x
    )

def trace(disc, kw, p, lam):
    "Discretization of the trace operator"
    trace_p_cell = disc.mat[kw]["trace_cell"]
    trace_p_face = disc.mat[kw]["trace_face"]
    bc_val_p = disc.mat[kw]["bc_values"]
    return trace_p_cell * p + trace_p_face * (lam + bc_val_p)

def mass_conservation(disc, lam, q):
    "Discretization of the mass conservation equation"
    div = disc.proj["div"]
    mortar2secondary = disc.proj["mortar2secondary"]
    return div * q - mortar2secondary * lam

def coupling_law_p(disc, p, lam, c):
    "Discretization of the coupling law for fluid flux"
    kw = disc.problem.flow_keyword

    kn = disc.mat[kw]["kn"]
    mu = disc.viscosity()
    mortar_volumes = disc.geo["mortar_volumes"]
    secondary2mortar = disc.proj["secondary2mortar"]
    primary2mortar = disc.proj["primary2mortar"]
    mortar2primary = disc.proj["mortar2primary"]
    avg = disc.proj["avg"]
    if isinstance(lam, ad.Ad_array):
        lam_flux = lam.val
    else:
        lam_flux = lam
    primary_flag = (lam_flux > 0).astype(np.int)
    secondary_flag = 1 - primary_flag
    c_upw = (secondary2mortar * c) * secondary_flag + (primary2mortar * avg * c) * primary_flag

    return lam / kn / mortar_volumes + (
        secondary2mortar * p - primary2mortar * trace(disc, kw, p, mortar2primary * lam)
    ) / mu(c_upw)

def upwind(disc, c, lam, q):
    "Discretization of the advective transport with upwind weighting"
    div = disc.proj["div"]
    avg = disc.proj["avg"]
    secondary2mortar = disc.proj["secondary2mortar"]
    primary2mortar = disc.proj["primary2mortar"]
    mortar2primary = disc.proj["mortar2primary"]
    mortar2secondary = disc.proj["mortar2secondary"]
    return (div * (disc.upwind(c, q) * q) + disc.mortar_upwind(
        c, lam, div, avg, primary2mortar, secondary2mortar, mortar2primary, mortar2secondary
    ))

def diffusive(disc, c, lam_c):
    "Discretizatio of the diffusive transport"
    kw = disc.problem.transport_keyword
    diff = disc.mat[kw]["flux"]
    bc_val_c = disc.mat[kw]["bc_values"]
    bound_diff = disc.mat[kw]["bound_flux"]
    mortar2primary = disc.proj["mortar2primary"]
    mortar2secondary = disc.proj["mortar2secondary"]
    div = disc.proj["div"]
    return (
        div * (diff * c + bound_diff * (mortar2primary * lam_c + bc_val_c))
        - mortar2secondary * lam_c
    )

def transport(disc, lam, lam0, c, c0, lam_c, lam_c0, q, q0, dt):
    "Discretization of the transport equation"
    kw = disc.problem.transport_keyword
    mass_weight = disc.mat[kw]["mass_weight"]
    theta = disc.mat[kw]["theta"]
    return (
        (c - c0) * (mass_weight / dt)
        + (upwind(disc, c, lam, q) + diffusive(disc, c, lam_c)) * theta
        + (upwind(disc, c0, lam0, q0) + diffusive(disc, c0, lam_c0)) * (1 - theta)
    )

def coupling_law_c(disc, c, lam_c):
    "Discretization of the transport between domains"
    kw = disc.problem.transport_keyword
    Dn = disc.mat[kw]["dn"]
    mortar_volumes = disc.geo["mortar_volumes"]
    secondary2mortar = disc.proj["secondary2mortar"]
    primary2mortar = disc.proj["primary2mortar"]
    mortar2primary = disc.proj["mortar2primary"]
    return (
        lam_c / Dn / mortar_volumes
        + (secondary2mortar * c
           - primary2mortar * trace(disc, kw, c, mortar2primary * lam_c))
    )

def viscous_flow(disc, problem, verbosity=1):
    """
    Solve the coupled problem of fluid flow and temperature transport, where the
    viscosity is depending on the viscosity.
    Darcy's law and mass conservation is solved for the fluid flow:
    u = -K/mu(c) grad p,   div u = 0,
    where mu(c) is a given concentration depending viscosity.
    The concentration is advective and diffusive:
    \partial phi c /\partial t + div (cu) -div (D grad c) = 0.

    A darcy type coupling is assumed between grids of different dimensions:
    lambda = -kn/mu(c) * (p^lower - p^higher),
    and similar for the diffusivity:
    lambda_c = -D * (c^lower - c^higher).

    Parameters:
    disc (discretization.ViscousFlow): A viscous flow discretization class
    problem (problem.ViscousProblem): a viscous flow problem class

    Returns:
    None

    The solution is exported to vtk and csv.
    """
    simulation_start = time.time()

    # Define ad variables
    if verbosity > 0:
        print("Apply initial grid adaptivity")
    # We solve for inital pressure and mortar flux by fixing the temperature
    # to the initial value.
    c0 = problem.initial_concentration()
    for i in range(problem.max_grid_level):
        adaptivity.adapt_domain(disc, c0)
        disc.update_problem(problem)
        c0 = problem.initial_concentration()
    gb = problem.gb
    if verbosity > 0:
        print("Initiate variables")
    p, lam, q, c, lam_c, sol, p_ix, lam_ix, c_ix, lam_c_ix = initiate_variables(
        disc, c0
    )
    if verbosity > 0:
        print("Prepare time stepping")
    dt = problem.time_step_param["initial_dt"]
    t = 0
    k = 0

    # Export initial condition
    exporter = pp.Exporter(
        gb,
        problem.time_step_param["file_name"],
        problem.time_step_param["vtk_folder_name"],
        fixed_grid=False,
    )
    updated_grid = False
    cmooth = (c.val + c0) / 2
    viz.split_variables(gb, [p.val, c.val, cmooth], ["pressure", "concentration", "smooth"])
    if problem.write_vtk_for_time(t, k):
        exporter.write_vtk(["pressure", "concentration"], time_dependent=True, grid=gb)
        times = [0]
    else:
        times = []

    # Store average concentration
    out_file_name = (
        problem.time_step_param["csv_folder_name"] + "/" + problem.time_step_param["file_name"] + ".csv"
    )
    out_file_smooth_name = (
        problem.time_step_param["csv_folder_name"] +
        "/" + problem.time_step_param["file_name"] +
        "_smooth.csv"
    )
    out_file = utils.initiate_csc_file(out_file_name)
    out_file_smooth = utils.initiate_csc_file(out_file_smooth_name)
    utils.store_time_data(problem, out_file, gb, 0.0)
    utils.store_time_data(problem, out_file_smooth, gb, 0.0, "smooth")

    time_disc_tot = 0
    time_output_tot = 0
    time_vtk_tot = 0
    time_nwtn_tot = 0
    time_adpt_tot = 0
    # Time iteration
    while t <= problem.time_step_param["end_time"] - dt + 1e-8:
        time_step_start = time.time()
        time_disc = 0
        time_nwtn = 0
        t += dt
        k += 1
        if verbosity > 0:
            print("Solving time step: ", k, " dt: ", dt, " Time: ", t)

        time_adaptive_start = time.time()
        if problem.adapt_domain(t, k):
            c0, adapted_domain = adaptivity.adapt_domain(disc, c.val)
            if adapted_domain:
                disc.update_problem(problem)
                gb = problem.gb
                p, lam, q, c, lam_c, sol, p_ix, lam_ix, c_ix, lam_c_ix = initiate_variables(
                    disc, c0
                )
                updated_grid = True

        time_adaptive = time.time() - time_adaptive_start
        time_adpt_tot += time_adaptive

        p0 = p.val
        lam0 = lam.val
        c0 = c.val
        lam_c0 = lam_c.val
        q0 = q.val

        err = np.inf
        newton_it = 0
        sol0 = sol.copy()
        # Newton iteration
        while err > 1e-9:
            newton_it += 1
            # Calculate flux
            q = darcy(disc, p, c, lam)
            tic = time.time()
            equation = ad.concatenate(
                (
                    mass_conservation(disc, lam, q),
                    coupling_law_p(disc, p, lam, c),
                    transport(disc, lam, lam0, c, c0, lam_c, lam_c0, q, q0, dt),
                    coupling_law_c(disc, c, lam_c),
                )
            )
            err = np.max(np.abs(equation.val))
            time_disc += time.time() - tic
            if err < 1e-9:
                break
            tic = time.time()
            if verbosity > 1:
                print("newton iteration number: ", newton_it - 1, ". Error: ", err)

            sol = sol - disc.linear_solver(equation.jac, equation.val)
            time_nwtn += time.time() - tic
            # Update variables
            p.val = sol[p_ix]
            lam.val = sol[lam_ix]

            c.val = sol[c_ix]
            lam_c.val = sol[lam_c_ix]

            if err != err or newton_it > 10 or err > 10e10:
                # Reset
                if verbosity > 0:
                    print("failed Netwon, reducing time step")
                t -= dt / 2
                dt = dt / 2
                p.val = p0
                lam.val = lam0

                c.val = c0
                lam_c.val = lam_c0

                sol = sol0
                err = np.inf
                newton_it = 0
            # print(err)
        # Newton solver finished
        # Update auxillary variables
        q.val = darcy(disc, p.val, c.val, lam.val)

        if verbosity > 0:
            print("Converged Newton in : ", newton_it - 1, " iterations. Error: ", err)
        if newton_it < 3:
            dt = dt * 1.2
        elif newton_it < 7:
            dt *= 1.1
        dt = problem.sugguest_time_step(t, dt)

        # Store solution
        time_output_start = time.time()
        cmooth = (c.val + c0) / 2
        viz.split_variables(gb, [p.val, c.val, cmooth], ["pressure", "concentration", "smooth"])
        utils.store_time_data(problem, out_file, gb, t)
        utils.store_time_data(problem, out_file_smooth, gb, t, "smooth")
        time_out = time.time() - time_output_start
        time_output_tot += time_out

        time_vtk_start = time.time()
        if problem.write_vtk_for_time(t, k):
            if updated_grid:
                exporter.write_vtk(
                    ["pressure", "concentration"], time_dependent=True, grid=gb
                )
            else:
                exporter.write_vtk(["pressure", "concentration"], time_dependent=True)
            times.append(t)
            exporter.write_pvd(timestep=np.array(times))

        # Calculate the solution times
        time_vtk = time.time() - time_vtk_start
        time_vtk_tot += time.time() - time_vtk_start

        time_step_time = time.time() - time_step_start
        time_left = time_step_time * (problem.time_step_param["end_time"] - t) / dt

        time_disc_tot += time_disc
        time_nwtn_tot += time_nwtn
        if verbosity > 0:
            print("Time step took: {0:.3f} s".format(time_step_time))
            print("Adaptivity took: {0:.3f} s".format(time_adaptive))
            print("Discretization took: {0:.3f} s".format(time_disc))
            print("Solving linear system took: {0:.3f} s".format(time_nwtn))
            print("Writing output files took: {0:.3f} s".format(time_out + time_vtk))
            print(
                "Estimated time left: {0:.3f} s ({1:.3f} h)".format(
                    time_left, time_left / 3600
                )
            )
            print("-------------------------------------------------------------------------------\n")
    # Time stepping finished
    time_vtk_start = time.time()
    exporter.write_pvd(timestep=np.array(times))
    out_file.close()
    time_vtk_tot += time.time() - time_output_start

    if verbosity > 0:

        print(
            "\n Finished simulation. It took: {0:.3f} s ({1:.3f} h)".format(
                time.time() - simulation_start, (time.time() - simulation_start) / 3600
            )
        )
        print(
            "Adaptivity took: {0:.3f} s  ({1:.3f} h)".format(
                time_adpt_tot, time_adpt_tot / 3600
            )
        )
        print(
            "Discretization took: {0:.3f} s  ({1:.3f} h)".format(
                time_disc_tot, time_disc_tot / 3600
            )
        )
        print(
            "Solving linear system took: {0:.3f} s ({1:.3f} h)".format(
                time_nwtn_tot, time_nwtn_tot / 3600
            )
        )
        print(
            "Writing output files took: {0:.3f} s ({1:.3f} h)".format(
                time_output_tot, time_output_tot / 3600
            )
        )
        print(
            "Writing VTK files took: {0:.3f} s ({1:.3f} h)".format(
                time_vtk_tot, time_vtk_tot / 3600
            )
        )


#!/usr/bin/env python
# From: https://adafruit-beaglebone-io-python.readthedocs.io/en/latest/Encoder.html
from Adafruit_BBIO.Encoder import RotaryEncoder, eQEP2b, eQEP1

import Adafruit_BBIO.GPIO as GPIO
import time
import smbus

myEncoder1 = RotaryEncoder(eQEP1)
myEncoder1.setAbsolute()
myEncoder1.enable()

myEncoder2 = RotaryEncoder(eQEP2b)
myEncoder2.setAbsolute()
myEncoder2.enable()

encoder1_position = myEncoder1.position
encoder2_position = myEncoder2.position
new_position1 = encoder1_position
new_position2 = encoder2_position

# Setting up buttons
btn1 = "P8_16" #up
btn4 = "P8_17" #
btn2 = "P8_18" #
btn3 = "P8_15" # up

reset = "P8_8" #

#Bus 2 at address 0x70
bus = smbus.SMBus(2)
matrix = 0x70

# Setting up LED matrix
bus.write_byte_data(matrix, 0x21, 0)
bus.write_byte_data(matrix, 0x81, 0)
bus.write_byte_data(matrix, 0xe7, 0)

# Setting up inputs and outputs
GPIO.setup(btn1, GPIO.IN)
GPIO.setup("P8_11", GPIO.IN)
GPIO.setup("P8_12", GPIO.IN)
GPIO.setup(btn2, GPIO.IN)
GPIO.setup(btn3, GPIO.IN)
GPIO.setup(btn4, GPIO.IN)
GPIO.setup(reset, GPIO.IN)

# # Setting up internal pulldown
# GPIO.setup(btn1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# GPIO.setup(btn2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# GPIO.setup(btn3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# GPIO.setup(btn4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# GPIO.setup(reset, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Grid setup
width = 7
height = 7

x = 4
y = 4

path  = [0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF]

# Empty Array for matrix manipulation
empty = [0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF,
        0x00, 0xFF]

turn_off = [0x00,0x00,
            0x00,0x00,
            0x00,0x00,
            0x00,0x00,
            0x00,0x00,
            0x00,0x00,
            0x00,0x00,
            0x00,0x00]
# Inital Write to LED Matrix
bus.write_i2c_block_data(matrix, 0, path)

while(1):
    new_position1 = myEncoder1.position
    new_position2 = myEncoder2.position
    print(new_position1, ":", new_position2)
    if new_position1<encoder1_position:
        if x >= (width):
            x = x - 1
        x = x + 1
        time.sleep(0.08)

    if new_position1>encoder1_position:
        if x <= 0:
            x = x + 1
        x = x - 1
        time.sleep(0.08)

    if new_position2<encoder2_position:
        if y <= 0:
            y = y + 1
        y = y - 1
        time.sleep(0.08)
    #button 3
    if new_position2>encoder2_position:
        if y >= height:
            y = y - 1
        y = y + 1
        time.sleep(0.08)

    #reset button which clears terminal and sets the cursor back to position (0,0)
    # if GPIO.input(reset):
    #     x=4
    #     y=4
    #     for i in range(0, 15):
    #         leds[i] = 0x00

    encoder1_position=new_position1
    encoder2_position=new_position2

    path[2*x] = path[2*x]|(0x80>>y)
    bus.write_i2c_block_data(matrix, 0, path)

    time.sleep(0.08)
# # The first byte is GREEN, the second is RED.
# smile = [0x00, 0x3c, 0x00, 0x42, 0x28, 0x89, 0x04, 0x85, 0x04, 0x85, 0x28, 0x89, 0x00, 0x42, 0x00, 0x3c]
# frown = [0x3c, 0x00, 0x42, 0x00, 0x85, 0x20, 0x89, 0x00, 0x89, 0x00, 0x85, 0x20, 0x42, 0x00, 0x3c, 0x00]
# neutral = [0x3c, 0x3c, 0x42, 0x42, 0xa9, 0xa9, 0x89, 0x89, 0x89, 0x89, 0xa9, 0xa9, 0x42, 0x42, 0x3c, 0x3c]
# # Start oscillator (p10)
# bus.write_byte_data(matrix, 0x21, 0)
# # Dispon, blink off (p11)
# bus.write_byte_data(matrix, 0x81, 0)
# # Full brightness (page 15)
# bus.write_byte_data(matrix, 0xe7, 0)
# bus.write_i2c_block_data(matrix, 0, frown)
# time.sleep(1)


from __future__ import division
import numpy as np
import cv2
import csv
import data
import random

def poly_to_int(poly):
	return [[int(p[0]), int(p[1])] for p in poly]

def draw_polygons(polygons=[], image_path=('polygons' + str(random.randint(1, 1000)) + '.jpg')):
	img = np.zeros((data.IMAGE_RESOLUTION[1], data.IMAGE_RESOLUTION[0], 3), dtype="uint8")
	for poly in polygons:
		cv2.polylines(img, [np.array(poly_to_int(poly))], True, (0, 255, 0), thickness=1)
	cv2.imwrite(image_path, img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()

def detect_shapes(img_path, output_csv_path='piecesVertices.csv', thresh_range=(80, 255), approx_epsilon=0.017):
	img = cv2.imread(img_path)
	img = cv2.GaussianBlur(img, (1, 1), 0)
	img = cv2.resize(img, data.IMAGE_RESOLUTION)

	img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

	# lower mask (0-10)
	lower_red = np.array([0, 40, 40])
	upper_red = np.array([20, 255, 255])
	mask0 = cv2.inRange(img_hsv, lower_red, upper_red)

	# upper mask (170-180)
	lower_red = np.array([160, 40, 40])
	upper_red = np.array([180, 255, 255])
	mask1 = cv2.inRange(img_hsv, lower_red, upper_red)

	# join my masks
	mask = mask0 + mask1

	output_img = img.copy()
	output_img[np.where(mask == 0)] = 0

	output_img = cv2.cvtColor(output_img, cv2.COLOR_HSV2BGR)
	output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY)

	_, output_img = cv2.threshold(output_img, thresh_range[0], thresh_range[1], cv2.THRESH_BINARY_INV)

	# open the file in the write mode
	with open(output_csv_path, 'w') as f:
		# create the csv writer
		writer = csv.writer(f)

		writer.writerow(['piece', 'x', 'y'])

		# inverting the image
		output_img = 255 - output_img
		cv2.imshow("img", output_img)
		cv2.waitKey(0)
		cv2.destroyAllWindows()

		contours = cv2.findContours(output_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2]
		piece_num = 0
		for contour in contours:
			approx = cv2.approxPolyDP(contour, approx_epsilon * cv2.arcLength(contour, closed=True), closed=True)
			approx_int = [[int(point[0][0]), int(point[0][1])] for point in approx]
			approx_area = cv2.contourArea(np.array(approx_int))
			if approx_area < 700:
				continue

			print(len(approx))
			cv2.drawContours(img, [approx], 0, (0, 255, 255), 3)

			for point in approx:
				x = point[0][0]
				y = point[0][1]
				writer.writerow([piece_num, x / data.IMAGE_SCALING_FACTOR, y / data.IMAGE_SCALING_FACTOR])

			piece_num += 1

	cv2.imwrite('camera_capture.jpg', img)
	cv2.imshow('result', img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()

if __name__ == '__main__':
	detect_shapes('/home/kuka/.ros/snapshot.jpg')


import nni
import numpy as np

from UCTB.dataset import NodeTrafficLoader_CPT, NodeTrafficLoader
from UCTB.model import XGBoost
from UCTB.evaluation import metric

params = {
    'Dataset': 'Bike',
    'City': 'NYC',
    'CT': 6,
    'PT': 0,
    'TT': 0,
    'max_depth': 10,
    'num_boost_round': 150
}

# params.update(nni.get_next_parameter())

data_loader = NodeTrafficLoader_CPT(dataset=params['Dataset'], city=params['City'],
                                    with_lm=False, test_ratio=0.1, normalize=False,
                                    C_T=int(params['CT']), P_T=int(params['PT']), T_T=int(params['TT']))

test_prediction = []
val_prediction = []

for i in range(data_loader.station_number):

    print('*************************************************************')
    print('Station', i)

    model = XGBoost(max_depth=int(params['max_depth']))

    train = []
    test_x = []

    if int(params['CT']) > 0:
        train.append(data_loader.train_closeness[:, 0, i, :])
        test_x.append(data_loader.test_closeness[:, 0, i, :])
    if int(params['PT']) > 0:
        train.append(data_loader.train_period[:, :, i, -1])
        test_x.append(data_loader.test_period[:, :, i, -1])
    if int(params['TT']) > 0:
        train.append(data_loader.train_trend[:, :, i, -1])
        test_x.append(data_loader.test_trend[:, :, i, -1])

    train = np.concatenate(train, axis=-1)

    test_x = np.concatenate(test_x, axis=-1)

    # val has the same length as test
    train_x, val_x = train[:-len(test_x)], train[-len(test_x):]

    train_y, val_y = data_loader.train_y[:-len(test_x), i], data_loader.train_y[-len(test_x):, i]

    model.fit(train_x, train_y, num_boost_round=int(params['num_boost_round']))

    test_p = model.predict(test_x).reshape([-1, 1, 1])
    val_p = model.predict(val_x).reshape([-1, 1, 1])

    test_prediction.append(test_p)
    val_prediction.append(val_p)

test_prediction = np.concatenate(test_prediction, axis=-2)
val_prediction = np.concatenate(val_prediction, axis=-2)

val_rmse = metric.rmse(val_prediction, data_loader.train_y[-len(data_loader.test_y):], threshold=0)
test_rmse = metric.rmse(test_prediction, data_loader.test_y, threshold=0)

# nni.report_final_result({
#     'default': val_rmse,
#     'test-rmse': test_rmse,
# })


#!/usr/bin/env python3
import argparse
import os
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")  # Report only TF errors by default

import keras_cv
import numpy as np
import tensorflow as tf
tf.get_logger().addFilter(lambda m: "Analyzer.lamba_check" not in m.getMessage())  # Avoid pesky warning

parser = argparse.ArgumentParser()
parser.add_argument("prompt", type=str, help="Prompt for the model to generate.")
parser.add_argument("--images", default=3, type=int, help="Number of images to generate.")
parser.add_argument("--output", default="image", type=str, help="Filename to save the images to.")
parser.add_argument("--version", default=2, type=int, choices=[1, 2], help="Stable Diffusion version.")
args = parser.parse_args()

if args.version == 1:
    model = keras_cv.models.StableDiffusion
elif args.version == 2:
    model = keras_cv.models.StableDiffusionV2
model = model(img_height=512, img_width=512)

images = model.text_to_image(args.prompt, batch_size=args.images)

for i, image in enumerate(images):
    with open("{}-{}.jpg".format(args.output, i + 1), "wb") as jpg_file:
        jpg_file.write(tf.image.encode_jpeg(image).numpy())


import logging
import os
from tqdm import tqdm
import numpy as np
from PIL import Image
from glyphs import ALPHABETS

def save_image_grid(path, np_array, n_cols=None):
    n_imgs, h, w = np_array.shape
    n_cols = n_cols or int(np.ceil(np.sqrt(n_imgs)))
    n_rows = int(np.ceil(n_imgs / n_cols))
    np_array = np.concatenate([np_array, np.zeros((n_cols * n_rows - n_imgs, h, w))])
    rows = [np.concatenate(row, axis=1) for row in np.split(np_array, n_cols)]
    grid = np.concatenate(rows)
    Image.fromarray(grid).convert("RGB").save(path)

def save_message(path, np_array, n_cols=None):
    n_imgs, h, w = np_array.shape
    message = [
        ['F_', 'u', 'n',],
        ['W_', 'i', 't', 'h',],
        ['G_', 'A_', 'N_', 's'],
    ]
    max_len = max([len(word) for word in message])

    message_img = []
    for word in message:
        word_img = []
        for t in word:
            word_img.append(np_array[ALPHABETS.index(t)])
        while len(word_img) < max_len:
            word_img.append(np.zeros((h, w)))
        word_img = np.concatenate(word_img, axis=1)
        message_img.append(word_img)
    message_img = np.concatenate(message_img)
    Image.fromarray(message_img).convert("RGB").save(path)

def get_logger(log_dir, name):
    """Get a `logging.Logger` instance that prints to the console
    and an auxiliary file.

    Args:
        log_dir (str): Directory in which to create the log file.
        name (str): Name to identify the logs.

    Returns:
        logger (logging.Logger): Logger instance for logging events.
    """
    class StreamHandlerWithTQDM(logging.Handler):
        """Let `logging` print without breaking `tqdm` progress bars.

        See Also:
            > https://stackoverflow.com/questions/38543506
        """
        def emit(self, record):
            try:
                msg = self.format(record)
                tqdm.write(msg)
                self.flush()
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                self.handleError(record)

    # Create logger
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # Log everything (i.e., DEBUG level and above) to a file
    log_path = os.path.join(log_dir, f'{name}.txt')
    file_handler = logging.FileHandler(log_path)
    file_handler.setLevel(logging.DEBUG)

    # Log everything except DEBUG level (i.e., INFO level and above) to console
    console_handler = StreamHandlerWithTQDM()
    console_handler.setLevel(logging.INFO)

    # Create format for the logs
    file_formatter = logging.Formatter('[%(asctime)s] %(message)s',
                                       datefmt='%m.%d.%y %H:%M:%S')
    file_handler.setFormatter(file_formatter)
    console_formatter = logging.Formatter('[%(asctime)s] %(message)s',
                                          datefmt='%m.%d.%y %H:%M:%S')
    console_handler.setFormatter(console_formatter)

    # add the handlers to the logger
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger


from bpy.types import Operator
from bpy.props import BoolProperty, EnumProperty
import bpy, bmesh

class VNT_OT_vertactions(Operator):
    bl_idname = "custom.vert_action"
    bl_label = ""
    bl_description = "Add/Remove Vertices or Move Vertices Up/Down"
    bl_options = {'REGISTER'}

    action: EnumProperty(items=(('REMOVE', "Remove", ""),
                                ('ADD', "Add", "")))

    def execute(self, context):
        scn = context.scene

        idx = scn.vcustom_index

        try:
            item = scn.vcustom[idx]
        except IndexError:
            pass

        else:
            if self.action == 'REMOVE':

                selverts = []
                for i in range(0, len(scn.vcustom)):
                    if scn.vcustom[i].enabled == True:
                        selverts.append(scn.vcustom[i].vertindex)

                for i in selverts:
                    l = len(scn.vcustom)

                    for j in range(0, l):
                        if scn.vcustom[j].vertindex == i:

                            scn.vcustom_index = j
                            scn.vcustom.remove(j)
                            break
                    scn.vcustom_index = 0

                info = "Vertices with Indices:" + str(selverts) + "removed from Vertex List"
                self.report({'INFO'}, info)

        if self.action == 'ADD':

            obj = bpy.context.object

            if obj:
                mat = obj.matrix_world
                vert_list = []

                if obj.mode == 'EDIT':

                    bm=bmesh.from_edit_mesh(obj.data)
                    manual_vcoi = [[list(mat @ v.co), str(v.index)] for v in bm.select_history if isinstance(v, bmesh.types.BMVert)]

                    print(manual_vcoi)
                    for i in manual_vcoiself.report():
                        item = scn.vcustom.add()
                        item.name = str(tuple(list(np.around(np.array(i[0]), 2))))
                        item.vertindex = i[1]
                        scn.vcustom_index = len(scn.vcustom)-1
                        info = '"%s" added to list' % (item.name)
                        self.report({'INFO'}, info)

                else:
                    self.report({'INFO'}, "Enter Edit Mode")

            else:
                self.report({'INFO'}, "Select Block/Geometry")

        return {"FINISHED"}

class VNT_OT_add_update_verts(Operator):
    """Print all items and their properties to the console"""
    bl_idname = "custom.add_update_verts"
    bl_label = "Get Vertices"
    bl_description = "Add/Update vertices of selected Geometry"
    #bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        scn = context.scene

        obj = bpy.context.object

        if obj:
            mat = obj.matrix_world
            vert_list = []
            bpy.ops.object.mode_set(mode='EDIT')
            bm=bmesh.from_edit_mesh(obj.data)

            if obj.mode == 'EDIT':

                if len(scn.vcustom) > 0:

                    context.scene.vcustom.clear()
                    for v in bm.verts:
                        r = []
                        g = list(mat @ v.co)

                        for i in g:
                            r.append(str(round(i, 3)))

                        m = "(" + r[0] + ", " + r[1] + ", " + r[2] + ")"
                        n = str(v.index)
                        vert_list.append([m, n])

                    for i in vert_list:
                        item = scn.vcustom.add()
                        item.name = i[0]
                        item.vertindex = i[1]
                        scn.vcustom_index = len(scn.vcustom)-1
                        info = '"%s" added to list' % (item.name)
                        self.report({'INFO'}, info)

                    bpy.ops.object.mode_set(mode='OBJECT')

                else:

                    for v in bm.verts:
                        r = []
                        g = list(mat @ v.co)

                        for i in g:
                            r.append(str(round(i, 2)))

                        m = "(" + r[0] + ", " + r[1] + ", " + r[2] + ")"
                        n = str(v.index)
                        vert_list.append([m, n])

                    for i in vert_list:
                        item = scn.vcustom.add()
                        item.name = i[0]
                        item.vertindex = i[1]
                        scn.vcustom_index = len(scn.vcustom)-1
                        info = '"%s" added to list' % (item.name)
                        self.report({'INFO'}, info)

                    bpy.ops.object.mode_set(mode='OBJECT')

            else:
                self.report({'INFO'}, "Enter Edit Mode")
        else:
            self.report({'INFO'}, "Select Block/Geometry")

        return{'FINISHED'}

class VNT_OT_select_unselect_allverts(Operator):
    """Select Items in the Viewport"""
    bl_idname = "custom.select_unselect_allverts"
    bl_label = ""
    bl_description = "Show Selected Vertices in Viewport"
    bl_options = {'REGISTER', 'UNDO'}

    select_all: BoolProperty(
        default=False,
        name="Select all Items of List",
        options={'SKIP_SAVE'})

    @classmethod
    def poll(cls, context):
        return bool(context.scene.vcustom)

    def execute(self, context):
        scn = context.scene

        if self.select_all:

            for i in range(0, len(scn.vcustom)):
                scn.vcustom[i].enabled = True

        else:
            for i in range(0, len(scn.vcustom)):
                scn.vcustom[i].enabled = False

        return{'FINISHED'}

class VNT_OT_clearverts(Operator):
    bl_idname = "custom.clear_verts"
    bl_label = "Remove all vertex data"
    bl_description = "Clear all Vertices of the List"
    bl_options = {'INTERNAL'}

    @classmethod
    def poll(cls, context):
        return bool(context.scene.vcustom)

    def invoke(self, context, event):
        return context.window_manager.invoke_confirm(self, event)

    def execute(self, context):
        if bool(context.scene.vcustom):
            context.scene.vcustom.clear()
            self.report({'INFO'}, "All items removed")
        else:
            self.report({'INFO'}, "Nothing to remove")
        return{'FINISHED'}


"""Slightly crude, but ugrid-check-specific logging."""
import logging
from typing import List, Union

class UgridLogHandler(logging.Handler):
    """A logging handler which simply accumulates logged messages in a list."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.reset()

    def emit(self, record):
        self.logs.append(record)

    def reset(self):
        self.logs = []

class CheckLoggingInterface:
    """
    Purpose-specific interface for logging ugrid conformance check messages.

    Contains a regular :class:`~logging.Handler` and a
    :class:`UgridLogHandler` which is connected to it.

    """

    def __init__(self, logger=None, handler=None):
        if logger is None:
            logger = logging.Logger("ugrid_conformance")
        self._logger = logger
        if handler is None:
            handler = UgridLogHandler(level=logging.INFO)
        self._handler = handler
        #: Control printing of messages as they are logged (debug).
        self._ENABLE_PRINT = False
        self._print_func = print
        #: Total number of warning =ADVISE statements logged (since reset).
        self.N_WARNINGS = 0
        #: Total number of error =REQUIRE statements logged (since reset).
        self.N_FAILURES = 0
        self._logger.addHandler(self._handler)
        self.reset()

    def reset(self):
        self._handler.reset()
        self.N_WARNINGS = 0
        self.N_FAILURES = 0
        self._ENABLE_PRINT = False

    def enable_reports_printout(self, print_statements=False, print_func=None):
        """Enable/disable printing of logged messages."""
        if print_func:
            self._print_func = print_func
        self._ENABLE_PRINT = print_statements

    def set_filter_level(self, level: int):
        self._handler.setLevel(level)

    def report_statement_logrecords(self) -> List[logging.LogRecord]:
        """Return the report log as a list of :class:`~logging.LogRecords`."""
        # Note: return a list copy, as a snapshot
        return self._handler.logs[:]

    def report(self, msg, level=logging.INFO, *args):
        """
        Output a free-form message with a given level.

        A low-level routine.  Use state/printonly in preference.

        """
        if self._ENABLE_PRINT:
            self._print_func(msg)
        self._logger.log(level, msg, *args)

    @staticmethod
    def _statement(vartype: str, varname: str, msg: str):
        if vartype:
            result = vartype + f' variable "{varname}" '
        elif varname:
            result = f'Variable "{varname}" '
        else:
            result = ""
        result += f"{msg}"
        return result

    def state(
        self,
        statement: str,
        vartype: Union[str, None],
        varname: Union[str, None],
        msg: str,
    ):
        """
        Log a message relating to a given statement code.

        This constructs a semi-automated message, referencing the statement
        code and a primary dataset variable 'var', of type 'vartype'
        (i.e. its role in the dataset, e.g 'mesh' or 'connectivity').

        Associates a statment code with the logged message.
        The statement code also determines the message level :
        * 'R' ("require") codes log with logging.ERROR.
        * 'A' ("advise") codes log with logging.WARN.
        * '?' (informational) codes log with logging.INFO.

        Parameters
        ----------
        statement : str
            the code for the specific problem (a short string like "A103")
        vartype : str or None
            the 'role' of a variable which is the focus of the problem (if any)
        varname : str or None
            the name of a variable which is the focus of the problem (if any)
        msg : str
            a description of the problem

        """
        assert len(statement) >= 1
        statement_type = statement[0]
        assert statement_type in ("R", "A", "?")
        try:
            statement_num = int(statement[1:])
        except ValueError:
            statement_num = 0
        if statement_type == "R":
            # For messages with a 'REQUIRE' type code.
            self.N_FAILURES += 1
            msg = f"*** FAIL R{statement_num:03d} : " + self._statement(
                vartype, varname, msg
            )
            self.report(msg, logging.ERROR, statement_num)
        elif statement_type == "A":
            # For messages with an 'ADVISE' type code.
            self.N_WARNINGS += 1
            msg = f"... WARN A{statement_num:03d} : " + self._statement(
                vartype, varname, msg
            )
            self.report(msg, logging.WARN, statement_num)
        elif statement_type == "?":
            # For messages which don't have a code assigned.
            self.report(self._statement(vartype, varname, msg))

    def printonly(self, msg, *args):
        """
        Log a debug-level message.

        A low-level alternative to 'state'.
        By default, these messages will be printed but *not* logged.
        ( to log them, change the filter level of the logger).

        """
        self.report(msg, logging.DEBUG, *args)


incoms = {}

with open("wagelist.txt", encoding="UTF-8") as file:
	for line in file:
		key, value = line.split()
		incoms[key] = int(value)

person = len(incoms)		# число работающих
print(f"Количество работников получивших зарплату: {person} человек")
#print(incoms)
total_income = sum(incoms.values())
avg_incom = total_income / person
#print(total_income)
print(f"Средний доход, полученный на одного работника: {round(avg_incom, 2)}")
low_incom = {x:y for x,y in incoms.items() if y <= 20000}
#print(low_incom)
print("Сотрудники получившие доход менее 20000: \n")
for key in low_incom:
	print(key, " -- > ",  low_incom[key])


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import requests
import sys
import os

class CrawlerPipeline(object):
    def process_item(self, item, spider):
        return item

    def close_spider(self, spider):
        spider.f.close()  # close the file

        if os.path.getsize(spider.filePath) > 0:
            # call to indexer
            filePath = spider.file_name
            try :
                r = requests.post("http://localhost:1021/search", data={"field":"0", "docName":filePath})
                if (r.status_code == 200):
                	print("{ \"success\" : true, "
                		+ "\"reason\": \"Succesfully crawled " + spider.url + "\"}")
                else:
                	print("{ \"success\" : false,"
                	 		+ "\"reason\" : \"Response from indexer not OK\"}", file=sys.stderr)

            except :
                print("{ \"success\" : false,"
                	 		+ "\"reason\" : \"Connection to indexer failed\"}", file=sys.stderr)
        else:
            print("{ \"success\" : false,"
                	 		+ "\"reason\" : \"Couldn't extract information from the given URL,"
                			+ " please ensure the url " + spider.url + " is correct\"}", file=sys.stderr)


"""
    Module for processing videos
"""

# pylint: disable=expression-not-assigned, too-many-locals, too-many-arguments

from datetime import datetime
from time import time
import sys

import cv2 as cv
#import face_recognition as fr
from security_webcam.video_buffer import VideoBuffer, TemporaryBuffer
from security_webcam.motion_detector import MotionDetector

class CameraControl:
    """ Camera control class """

    def __init__(self, fps=30, webcam_code=0, temp_buffer_len=5, vid_buffer_len=60,
                 max_len=5, show_time=False, show_cam=False):
        self._md = MotionDetector(0.1)
        self._cap = None
        self._fps = fps
        self._webcam = webcam_code
        self._temp_buffer_len = temp_buffer_len
        self._vid_buffer_len = vid_buffer_len
        self._max_len = max_len
        self._show_time = show_time
        self._show_cam = show_cam

    def start_cam(self):
        """ Start webcam """
        self._cap = cv.VideoCapture(self._webcam)
        self._cap.set(cv.CAP_PROP_FPS, self._fps)

    def start_recording(self, verbose=False):
        """ Start recording """
        _, frame = self._cap.read()   # read the first frame to get dimension of the frame

        # initialize buffer list
        temp_buffer = TemporaryBuffer(fps=self._fps, length=self._temp_buffer_len)
        buffers = [None] * (self._max_len + 1)
        buffers[0] = temp_buffer
        for i in range(1, len(buffers)):
            buffers[i] = VideoBuffer(fps=self._fps, length=self._vid_buffer_len)
        curr_i = 1

        # initialize some variables
        curr_time = prev_time = detected_time = time()
        motion_detected = False

        # start recording
        while True:
            _, frame = self._cap.read()

            detected_frame = self._md.detect(frame)

            # TODO use face recognition somewhere else?
            #small_frame = cv.resize(frame, (0, 0), fx=0.25, fy=0.25)
            #face_locations = fr.face_locations(small_frame)

            # switch mode once a face is detected
            if detected_frame:
                if not motion_detected:
                    if verbose: print('>>> MOTION DETECTED!!!')
                    detected_time = time()

                motion_detected = True
                prev_time = time()

            frame = self._add_time(frame) if self._show_time else None
            self._stream_vid(frame) if self._show_cam else None

            # decide which buffer to put in
            buffers[curr_i].load(frame) if motion_detected else temp_buffer.load(frame)

            curr_time = time()

            # use the next buffer once the current one is full
            if buffers[curr_i].is_full():
                curr_i += 1
                if curr_i == len(buffers):
                    curr_i -= 1
                    break
                else:
                    detected_time = time()

            # if wait time is reached, exit
            if motion_detected and (curr_time - prev_time) > self._temp_buffer_len:
                break

        real_fps = buffers[curr_i].num_frames / (curr_time - detected_time)
        return buffers, (frame.shape[1], frame.shape[0]), real_fps

    @staticmethod
    def _add_time(frame):
        """ Add time stamp to the frame """
        now = datetime.today().strftime("%m-%d-%Y %H:%M:%S")
        return cv.putText(frame, now, (25, 50), cv.FONT_HERSHEY_SIMPLEX,
                          1, (0, 0, 255), 2)

    @staticmethod
    def _stream_vid(frame):
        """ Display the video feed """
        cv.imshow('Security Webcam', frame)
        key = cv.waitKey(1) & 0xFF
        if key == 27:
            sys.exit(0)

    def close_cam(self):
        """ Properly close webcam """
        self._cap.release()
        cv.destroyAllWindows()


from django.views.generic import TemplateView, FormView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.utils import timezone
from django.shortcuts import get_object_or_404, redirect
from django.contrib import messages
from django.urls import reverse_lazy

from . import models
from . import forms

class EvaluationList(LoginRequiredMixin, TemplateView):
    """Evaluation landing page"""

    template_name = "evaluations/index.html"

    def get_context_data(self, **kwargs) -> dict:
        context = super().get_context_data(**kwargs)

        return {
            **self._evaluation_list(),
            **context,
        }

    def _evaluation_list(self) -> dict:
        student: Optional[models.Student] = self.request.student  # type: ignore

        if student:
            evaluations = models.Evaluation.objects.filter(student=student)
            complete_evaluations = evaluations.filter(completed_at__isnull=False)
            incomplete_evaluations = evaluations.filter(completed_at__isnull=True)

            q_starting_at_null = Q(available_starting_at__isnull=True)
            q_starting_at_before_now = Q(available_starting_at__lte=timezone.now())
            q_starting_at = q_starting_at_null | q_starting_at_before_now

            q_available_until_null = Q(available_until__isnull=True)
            q_available_until_after_now = Q(available_until__gt=timezone.now())
            q_available_until = q_available_until_null | q_available_until_after_now

            q_available = q_starting_at & q_available_until

            available_evaluations = incomplete_evaluations.filter(q_available)
            missed_evaluations = incomplete_evaluations.exclude(q_available)

            return {
                "completed_evaluations": complete_evaluations,
                "incomplete_evaluations": incomplete_evaluations,
                "available_evaluations": available_evaluations,
                "missed_evaluations": missed_evaluations,
            }

        return {
            "completed_evaluations": [],
            "incomplete_evaluations": [],
            "available_evaluations": [],
            "missed_evaluations": [],
        }

class CompleteEvaluation(LoginRequiredMixin, FormView):
    form_class = forms.EvaluationForm
    template_name = "evaluations/evaluation.html"
    success_url = reverse_lazy("evaluations:index")

    def dispatch(self, request, *args, **kwargs):
        to_prefetch = (
            "question_set",
            "question_set__multiple_choice_questions",
            "question_set__multiple_choice_questions__answers",
            "question_set__freeform_questions",
        )

        self.evaluation = get_object_or_404(
            models.Evaluation.objects.prefetch_related(*to_prefetch),
            pk=self.kwargs["pk"],
            student=request.student,
        )

        return super().dispatch(request, *args, **kwargs)

    def get(self, *args, **kwargs):
        if not self.form_completable:
            return redirect(self.success_url)

        return super().get(*args, **kwargs)

    def post(self, *args, **kwargs):
        if not self.form_completable:
            messages.error(self.request, "Your survey was not able to be completed")
            return redirect(self.success_url)

        return super().post(*args, **kwargs)

    def get_form_kwargs(self) -> dict:
        kwargs = super().get_form_kwargs()
        kwargs["evaluation"] = self.evaluation
        return kwargs

    def get_context_data(self, **kwargs) -> dict:
        context = super().get_context_data(**kwargs)
        context["evaluation"] = self.evaluation
        return context

    def form_valid(self, form: forms.EvaluationForm):
        form.save_responses()
        messages.success(self.request, "Thank you for completing your evaluation")
        return super().form_valid(form)

    @property
    def form_completable(self) -> bool:
        if self.evaluation.completed_at:
            return False

        if not self.evaluation.is_available:
            return False

        return True


#!/usr/bin/python3
"""
script starts Flask web app
    listen on 0.0.0.0, port 5000
    routes: /: display "Hello HBNB!"
"""

from flask import Flask
app = Flask(__name__)

@app.route('/airbnb-onepage/')
def airbnb_onepage():
    """display text"""
    return "Hello HBNB!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)


import numpy as np

class AngularDistribution(object):
    """
    angular distribution class
    accepts uniform in the angle
    and uniform in the cosine of the angle
    """
    def __init__(self, angular_law, n_slices):

        if n_slices % 2 == 1:
            print('Error: n_slices must be an even number!')
            exit(-1)
        if angular_law=="uniform":
            self.angular_distribution = self.uniform_ang
        elif angular_law=="cos_uniform":
            self.angular_distribution = self.cos_uniform_ang
        else:
            print("Unknown angular distribution")
            exit(0)

    def __call__(self,n,omega_frac):
        return self.angular_distribution(n,omega_frac)

    def uniform_ang(self,n,omega_fraction):
        delta = np.pi/2./float(n)
        a = np.array([ [delta*i,delta*(i+1)] for i in range(int(n))])
        o = np.array([ 2.*np.pi*(np.cos(x[0]) - np.cos(x[1])) for x in a])
        return a,o*omega_fraction

    def cos_uniform_ang(self,n,omega_fraction):
        delta = 1./float(n)
        a = np.array([ [np.arccos(delta*float(i)),np.arccos(delta*float(i-1))] for i in range(int(n),0,-1)])
        o = np.array([ 2.*np.pi*(np.cos(x[0]) - np.cos(x[1])) for x in a])
        return a,o*omega_fraction

if __name__=="__main__":
    N = 12
    M = AngularDistribution("uniform", 12)
    a,o = M(10)
    M = AngularDistribution("cos_uniform", 12)
    a,o = M(10)


import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
from step_ga import genetic_algorithm, step_func, step_func_score
import time
plt.style.use('C:/Users/BRoehrich/Desktop/git/echem/scientific.mplstyle')

## Adapted from Nature 442, 709–712 (2006). https://doi.org/10.1038/nature04928 ##

# file = 'C:/Users/BRoehrich/Desktop/New folder/data.asc'
file = 'C:/Users/BRoehrich/Desktop/Sofia data/3 CVA 2 mM FeMeOH half mM KCl -400 mV 20 min 50 Hz CUME26 flow rate 20uLhr to 020uLhr_C02.txt'
time, curr = np.loadtxt(file, unpack=True, skiprows=1, delimiter='\t')
y = curr[5000:]
from scipy.signal import savgol_filter
filt = savgol_filter(y, 101, 1)
filt2 = np.average(filt.reshape((-1, 5)), axis=1)
plt.plot(filt2)
y = filt2
# ind, time, curr, t2, v = np.loadtxt(file, unpack=True, skiprows=50, delimiter=',')

# y = curr[2000:]
#%%

# arr = np.ones(1000)
# for i in range(len(arr)):
#     arr[i] = np.ceil(i/100)
# arr += np.random.normal(loc=0, scale=0.6, size=1000)

# y = arr

def initial_fit(y, n_steps):
    c, best_eval = genetic_algorithm(y, n_steps, n_pop=100,
                                        n_iter=100)
    fit = step_func(c)

    return c, fit

def main_fit(y, c, n_steps):
    # c: n-1 steps best candidate

    co = []

    for i, (loc, val) in enumerate(c):
        if i == 0:
            continue

        ydata = y[c[i-1][0] : c[i][0]]

        if len(ydata) < 5:
            continue

        best_fit, _, _ = genetic_algorithm(ydata, n_steps=1, n_pop=100,
                                       n_iter=25)

        step_loc = best_fit[1][0]
        step_val = best_fit[2][1]

        s_loc = c[i-1][0] + step_loc

        this_cand = c.copy()
        this_cand.append((s_loc, step_val))
        this_cand.sort()

        co.append(this_cand)

    # Reevaluate median values
    for c in co:
        for i in range(1, len(c)):
            med = np.median(y[ c[i-1][0]:c[i][0] ])
            c[i] = (c[i][0], med)
        c[0] = (c[0][0], c[1][1])

    # See which new step gives the best score
    best, best_eval = co[0], step_func_score(y, co[0])
    scores = [step_func_score(y, c) for c in co]

    for i in range(len(co)):
        if scores[i] < best_eval:
            best, best_eval = co[i], scores[i]

    return best, best_eval

def counter_fit(y, c):

    cf = []
    cf.append(c[0])

    for i, (loc, val) in enumerate(c):
        if i == 0:
            continue

        ydata = y[c[i-1][0] : c[i][0]]

        if len(ydata) < 5:
            continue

        best_counter_fit, _, _ = genetic_algorithm(ydata,
                                                   n_steps=1, n_pop=100,
                                                   n_iter=25)

        # if best_counter_fit == 0:
        #     print(c)
        #     print(i, val, loc)
            # print(ydata)

        counter_step_loc = best_counter_fit[1][0]
        counter_step_val = best_counter_fit[2][1]

        cs_loc = c[i-1][0] + counter_step_loc

        cf.append((cs_loc, counter_step_val))

    cf.append(c[-1])
    # for i in range(1, len(c)):
    #     cf.pop(i)
    cf.sort()

    # Pick counter fit candidate with the best n steps
    best      = None
    best_eval = 1e20
    # print('')
    # print('c: ',  [loc for (loc, val) in c])
    # print('cf: ', [loc for (loc, val) in cf])
    for i in range(1, len(cf)-1):
        cf_cand = cf.copy()

        cf_cand.pop(i)

        for i in range(1, len(cf_cand)):
            med = np.median(y[ cf_cand[i-1][0]:cf_cand[i][0] ])
            cf_cand[i] = (cf_cand[i][0], med)

        cf_cand[0] = (cf_cand[0][0], cf_cand[1][1])
        score = step_func_score(y, cf_cand)

        # print(score, [loc for (loc, val) in cf_cand])

        if score < best_eval:
            best      = cf_cand
            best_eval = score

    return best, best_eval

def S(fit_score, cf_score):
    return cf_score/fit_score

def refine_locs(y, c, width):

    # Look within +- width/2 points for the largest step

    locs = [loc for i, (loc, val) in enumerate(c)]
    tol = int(width/10)

    for i in range(1, len(c)):
        loc = c[i][0]
        if any([x in locs for x in range(loc-tol, loc+tol+1) if x != loc]):
            print(f'Removing point at {loc}')
            c.pop[i]

    for i, (loc, val) in enumerate(c):

        if i == 0 or i == len(c)-1:
            continue

        ydata = y[int(loc-width/2) : int(loc+width/2)]

        best_fit, _, _ = genetic_algorithm(ydata, n_steps=1, n_pop=100,
                                           n_iter=25)

        new_loc = int(loc-width/2) + best_fit[1][0]

        print(loc, new_loc)

        c[i] = (new_loc, val)

    # Recalculate median values

    for i in range(1, len(c)):
         if i > 0:
             med = med = np.median(y[ c[i-1][0]:c[i][0] ])
             c[i] = (c[i][0], med)

    c[0] = (c[0][0], c[1][1])

    return c

fits = {}
counter_fits = {}
Ss    = []
steps = []
max_steps = 20

for n_steps in range(1,20):
    if n_steps == 1:
        c, c_score, bests = genetic_algorithm(y, n_steps=n_steps, n_pop=100,
                                            n_iter=25)
    else:
        c, c_score = main_fit(y, c, n_steps)

    cf, cf_score = counter_fit(y, c)

    fig, ax = plt.subplots()
    ax.plot(y)
    ax.plot(step_func(c), label='fit')
    ax.plot(step_func(cf), label='counter fit')
    ax.set_title(f'{n_steps} steps')

    fits[n_steps] = (c, c_score)
    counter_fits[n_steps] = (cf, cf_score)

    locs = [loc for (val, loc) in c if loc != 0 and loc != len(y)]

    Ss.append(S(c_score, cf_score))
    steps.append(n_steps)

    print(f'{n_steps} steps: S = {S(c_score, cf_score)}')

fig, ax = plt.subplots()
ax.plot(steps, Ss)
ax.set_xlabel('# of steps')
ax.set_ylabel('Score')

print('')
print(f'I think there are {steps[np.where(Ss == max(Ss))[0][0]]} steps')

idx = np.where(Ss == max(Ss[1:]))[0][0]+1
refined_c = refine_locs(y, fits[idx][0], len(y)/10)

fig, ax = plt.subplots()
ax.plot(y)
ax.plot(step_func(fits[idx][0]))
ax.plot(step_func(refined_c))


class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        numRows = rowIndex+1
        # initialize dp with first two rows of Pascal's Triangle
        if rowIndex == 0:
            return [1]
        if rowIndex == 1:
            return [1,1]
        prev = [1,1]

        # iterate from row 2 to numRows-1
        for i in range(2,numRows):
            # create a new row with the first element as 1
            cur = [1]
            # iterate over previous row and compute sum of adjacent elements
            for j in range(1,len(prev)):
                cur.append(prev[j]+prev[j-1])
            # append 1 to the end of row and append row to dp
            cur.append(1)
            prev = cur.copy()

        # return dp representing Pascal's Triangle
        return cur


#Python 3.6.1
#Author: Bill Bonney
#This is the GUI code for The Tech Academy Python Item 65 drill

from tkinter import *
import file_transfer_func
import file_transfer

def load_gui(self):
    self.lbl_wfiles = Label(self.master,text="Working Files", bg="dodger blue", fg="snow", font="-weight bold")
    self.lbl_wfiles.grid(row=0,column=0,columnspan=2,padx=(5,0),sticky=S+W)
    self.lbl_tfiles = Label(self.master,text="Destination", bg="dodger blue", fg="snow", font="-weight bold")
    self.lbl_tfiles.grid(row=2,column=0,columnspan=2,padx=(5,0),sticky=S+W)

    self.txt_wfiles = Entry(self.master,text="")
    self.txt_wfiles.grid(row=1,column=0,columnspan=2,padx=(5,0),sticky=E+N)
    self.txt_tfiles = Entry(self.master,text="")
    self.txt_tfiles.grid(row=3,column=0,columnspan=2,padx=(5,0),sticky=E+N)

#Defining and resizing the search button images.
    magImage = PhotoImage(file=".\\mag_glass.gif")
    buttonImage = magImage.subsample(13,13)
    Button.img = buttonImage

    self.wfilesearch = Button(self.master)
    self.wfilesearch.config(image = buttonImage,compound = 'center',command=lambda: file_transfer_func.getWorking(self))
    self.wfilesearch.grid(row=1,column=2,pady=(1,0),sticky=W+N)
    self.wfilesearch = Button(self.master)
    self.wfilesearch.config(image = buttonImage,compound = 'center',command=lambda: file_transfer_func.getDest(self))
    self.wfilesearch.grid(row=3,column=2,pady=(1,0),sticky=W+N)

    self.scrollbar1 = Scrollbar(self.master,orient=VERTICAL)
    self.display = Text(self.master, height=15, width=42,yscrollcommand=self.scrollbar1.set,wrap=WORD)
    self.scrollbar1.config(command=self.display.yview)
    self.scrollbar1.grid(row=0,column=5,rowspan=5,pady=(10,0),sticky=N+E+S)
    self.display.grid(row=0,column=3,rowspan=5,columnspan=2,padx=(5,0),pady=(10,0))

    self.btn_run = Button(self.master,width=12,height=2,text='Run',command=lambda: file_transfer_func.copyFiles(self))
    self.btn_run.grid(row=4,column=0,sticky=S)
    self.btn_checkfiles = Button(self.master,width=12,height=2,text='Check Files',command=lambda: file_transfer_func.checkFiles(self))
    self.btn_checkfiles.grid(row=4,column=2,padx=(0,10),sticky=S)

if __name__ == "__main__":
    pass


from prometheus_client import Gauge, Info, make_asgi_app

from air_sensor.api_models import SensorData
from air_sensor.utils import convert_to_datetime

temperature_summary = Gauge("temperature", "Temperature in degrees Celsius")
co2_summary = Gauge("co2", "CO2 level")
humidity_summary = Gauge("humidity", "Humidity level")
time_info = Info("time", "Observation time from sensor")

prometheus_asgi_app = make_asgi_app()

def observe_data(data: SensorData):
    temperature_summary.set(data.temp)
    co2_summary.set(data.co2)
    humidity_summary.set(data.humi)
    time_info.info({"time": str(convert_to_datetime(data.date))})


from django.test import TestCase
from catalog.models import Category, Product

class SimpleTest(TestCase):
    def test_basic_addition(self):
        """
        Tests that 1 + 1 always equals 2.
        """
        self.assertEqual(1 + 1, 2)

    def test_Models(self):
        category = Category();
        self.assertTrue(category)
        product = Product();
        self.assertTrue(product)

'''
from catalog.admin import ProductAdmin
from django.contrib import admin
class ModelAdminTest(TestCase):

    def test_ok_to_register(self):
        admin.site.register(Product, ProductAdmin)
'''


from collections import deque

food_portions = deque([int(x) for x in input().split(", ")])
stamina_potions = deque([int(x) for x in input().split(", ")])
peaks = {'Vihren': 80, 'Kutelo': 90, 'Banski Suhodol': 100, 'Polezhan': 60, 'Kamenitza': 70}
climbed_peaks = []
days = 0

while food_portions and stamina_potions:
    if len(climbed_peaks) == 5:
        break
    if not food_portions or not stamina_potions:
        break

    food = food_portions.pop()
    stamina = stamina_potions.popleft()
    days += 1
    for current_peak in peaks:
        if food + stamina >= peaks[current_peak]:
            climbed_peaks.append(current_peak)

        else:
            while food_portions and stamina_potions:
                food = food_portions.pop()
                stamina = stamina_potions.popleft()
                days += 1

                if stamina + food >= peaks[current_peak]:
                    climbed_peaks.append(current_peak)
                    break
                else:
                    continue

if len(climbed_peaks) == 5 and days <= 7:
    print(f'Alex did it! He climbed all top five Pirin peaks in one week -> @FIVEinAWEEK')
else:
    print("Alex failed! He has to organize his journey better next time -> @PIRINWINS")

if climbed_peaks:
    print('Conquered peaks:')
    print(*climbed_peaks, sep="\n")


import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def import_coords(folder):
    annotations = [os.path.join(folder, x) for x in os.listdir(folder) if x[-3:] == "txt"]
    coords = []
    multiple_coords = []
    for annotation in annotations:
        ann = open(annotation)
        line_count = len(ann.readlines())       # counts number of lines in single annotation file
        print('lines : ' + str(line_count))

        ann = open(annotation)
        read = ann.readlines()      # reads each line in annotation file

        for line in read:
            box = [item.strip() for item in line.split(' ')]
            cell_id = box[0]
            c_x = box[1]
            c_y = box[2]
            width = box[3]
            height = box[4]
            info = np.array([float(cell_id), float(c_x), float(c_y), float(width), float(height)])
            if line_count == 1:
                coords.append(info)
            elif line_count > 1:
                multiple_coords.append(info)
                # print(y_multiple)
                coords[:] = multiple_coords[-1]
            #coords.append(info)
    print(coords)
    return print(np.array(coords).shape)

folder = 'data\\sample'
import_coords(folder)

'''
def draw_bboxes(bbox, **kwargs):
    # optional arguments
    colormap = kwargs.get('colormap', None)  # dict keys: class labels, values: valid colors
    bbox_format = kwargs.get('bbox_format', 'xywh')
    image_shape = kwargs.get('image_shape', None)
    xticks = kwargs.get('xticks', None)
    yticks = kwargs.get('yticks', None)

    fig, ax = plt.subplots()

    # check size
    if type(bbox[0]) != list:  # only a single bbox provided
        bbox = [bbox]  # put bbox into a list

    xmax = 0.0
    ymax = 0.0
    for bb in bbox:

        # color for current class label
        try:
            color = colormap[bb[0]]
        except:
            color = 'red'

        if bbox_format == 'xyxy':
            # convert into [x, y, w, h] for plotting
            bb[2] = bb[2] - bb[0]
            bb[3] = bb[3] - bb[1]

        # place bounding box
        rect = patches.Rectangle((bb[1], bb[2]), bb[3], bb[4], linewidth=3, edgecolor=color, facecolor='none',
                                 alpha=0.8)
        ax.add_patch(rect)

        # plot center of bounding box as +
        plt.plot(bb[0] + bb[2] / 2, bb[1] + bb[3] / 2, color=color, marker='+')

        # add the label w/o probability
        if (len(bb) == 5) and type(bb[4] == str):
            plt.text(bb[0] + bb[2], bb[1] + bb[3], bb[4],
                     fontsize=10,
                     color='white',
                     horizontalalignment='right',
                     verticalalignment='bottom',
                     bbox=dict(facecolor=color, edgecolor=color, alpha=0.8))
        # add the label w/ probability
        elif (len(bb) == 6) and type(bb[4] == str) and type(bb[5] == float):
            plt.text(bb[0] + bb[2], bb[1] + bb[3], bb[4] + ' (' + str(bb[5]) + ')',
                     fontsize=10,
                     color='white',
                     horizontalalignment='right',
                     verticalalignment='bottom',
                     bbox=dict(facecolor=color, edgecolor=color, alpha=0.8))

        # update max axis extents
        if image_shape is None:
            xmax = np.max([xmax, bb[0] + bb[2]])
            ymax = np.max([ymax, bb[1] + bb[3]])

    if image_shape is None:
        plt.xlim([0, xmax * 1.5])
        plt.ylim([0, ymax * 1.5])
    else:
        plt.xlim([0, image_shape[0]])
        plt.ylim([0, image_shape[1]])

    if xticks is not None:
        plt.xticks(xticks)
    if yticks is not None:
        plt.yticks(yticks)
    plt.grid()
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()

    return fig, ax'''


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

from odoo.fields import Command
from odoo.exceptions import ValidationError
from odoo.tests import tagged

from odoo.addons.project.tests.test_project_base import TestProjectCommon

from datetime import date

@tagged('-at_install', 'post_install')
class TestTaskDependencies(TestProjectCommon):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        cls.project_pigs.write({
            'allow_task_dependencies': True,
        })
        cls.task_3 = cls.env['project.task'].with_context({'mail_create_nolog': True}).create({
            'name': 'Pigs UserTask 2',
            'user_ids': cls.user_projectuser,
            'project_id': cls.project_pigs.id,
        })

    def flush_tracking(self):
        """ Force the creation of tracking values. """
        self.env.flush_all()
        self.cr.precommit.run()

    def test_task_dependencies(self):
        """ Test the task dependencies feature

            Test Case:
            =========
            1) Add task2 as dependency in task1
            2) Checks if the task1 has the task in depend_on_ids field.
        """
        self.assertEqual(len(self.task_1.depend_on_ids), 0, "The task 1 should not have any dependency.")
        self.task_1.write({
            'depend_on_ids': [Command.link(self.task_2.id)],
        })
        self.assertEqual(len(self.task_1.depend_on_ids), 1, "The task 1 should have a dependency.")
        self.task_1.write({
            'depend_on_ids': [Command.link(self.task_3.id)],
        })
        self.assertEqual(len(self.task_1.depend_on_ids), 2, "The task 1 should have two dependencies.")

    def test_cyclic_dependencies(self):
        """ Test the cyclic dependencies

            Test Case:
            =========
            1) Check initial setting on three tasks
            2) Add task2 as dependency in task1
            3) Add task3 as dependency in task2
            4) Add task1 as dependency in task3 and check a validation error is raised
            5) Add task1 as dependency in task2 and check a validation error is raised
        """
        # 1) Check initial setting on three tasks
        self.assertTrue(
            len(self.task_1.depend_on_ids) == len(self.task_2.depend_on_ids) == len(self.task_3.depend_on_ids) == 0,
            "The three tasks should depend on no tasks.")
        self.assertTrue(self.task_1.allow_task_dependencies, 'The task dependencies feature should be enable.')
        self.assertTrue(self.task_2.allow_task_dependencies, 'The task dependencies feature should be enable.')
        self.assertTrue(self.task_3.allow_task_dependencies, 'The task dependencies feature should be enable.')

        # 2) Add task2 as dependency in task1
        self.task_1.write({
            'depend_on_ids': [Command.link(self.task_2.id)],
        })
        self.assertEqual(len(self.task_1.depend_on_ids), 1, 'The task 1 should have one dependency.')

        # 3) Add task3 as dependency in task2
        self.task_2.write({
            'depend_on_ids': [Command.link(self.task_3.id)],
        })
        self.assertEqual(len(self.task_2.depend_on_ids), 1, "The task 2 should have one dependency.")

        # 4) Add task1 as dependency in task3 and check a validation error is raised
        with self.assertRaises(ValidationError), self.cr.savepoint():
            self.task_3.write({
                'depend_on_ids': [Command.link(self.task_1.id)],
            })
        self.assertEqual(len(self.task_3.depend_on_ids), 0, "The dependency should not be added in the task 3 because of a cyclic dependency.")

        # 5) Add task1 as dependency in task2 and check a validation error is raised
        with self.assertRaises(ValidationError), self.cr.savepoint():
            self.task_2.write({
                'depend_on_ids': [Command.link(self.task_1.id)],
            })
        self.assertEqual(len(self.task_2.depend_on_ids), 1, "The number of dependencies should no change in the task 2 because of a cyclic dependency.")

    def test_task_dependencies_settings_change(self):

        def set_task_dependencies_setting(enabled):
            features_config = self.env["res.config.settings"].create({'group_project_task_dependencies': enabled})
            features_config.execute()

        self.project_pigs.write({
            'allow_task_dependencies': False,
        })

        # As the Project General Setting group_project_task_dependencies needs to be toggled in order
        # to be applied on the existing projects we need to force it so that it does not depends on anything
        # (like demo data for instance)
        set_task_dependencies_setting(False)
        set_task_dependencies_setting(True)
        self.assertTrue(self.project_pigs.allow_task_dependencies, "Projects allow_task_dependencies should follow group_project_task_dependencies setting changes")

        self.project_chickens = self.env['project.project'].create({
            'name': 'My Chicken Project'
        })
        self.assertTrue(self.project_chickens.allow_task_dependencies, "New Projects allow_task_dependencies should default to group_project_task_dependencies")

        set_task_dependencies_setting(False)
        self.assertFalse(self.project_pigs.allow_task_dependencies, "Projects allow_task_dependencies should follow group_project_task_dependencies setting changes")

        self.project_ducks = self.env['project.project'].create({
            'name': 'My Ducks Project'
        })
        self.assertFalse(self.project_ducks.allow_task_dependencies, "New Projects allow_task_dependencies should default to group_project_task_dependencies")

    def test_duplicate_project_with_task_dependencies(self):
        self.project_pigs.allow_task_dependencies = True
        self.task_1.depend_on_ids = self.task_2
        pigs_copy = self.project_pigs.copy()

        task1_copy = pigs_copy.task_ids.filtered(lambda t: t.name == 'Pigs UserTask')
        task2_copy = pigs_copy.task_ids.filtered(lambda t: t.name == 'Pigs ManagerTask')

        self.assertEqual(len(task1_copy), 1, "Should only contain 1 copy of UserTask")
        self.assertEqual(len(task2_copy), 1, "Should only contain 1 copy of ManagerTask")

        self.assertEqual(task1_copy.depend_on_ids.ids, [task2_copy.id],
                         "Copy should only create a relation between both copy if they are both part of the project")

        task1_copy.depend_on_ids = self.task_1

        pigs_copy_copy = pigs_copy.copy()
        task1_copy_copy = pigs_copy_copy.task_ids.filtered(lambda t: t.name == 'Pigs UserTask')

        self.assertEqual(task1_copy_copy.depend_on_ids.ids, [self.task_1.id],
                         "Copy should not alter the relation if the other task is in a different project")

    def test_duplicate_project_with_subtask_dependencies(self):
        self.project_goats.allow_task_dependencies = True
        parent_task = self.env['project.task'].with_context({'mail_create_nolog': True}).create({
            'name': 'Parent Task',
            'project_id': self.project_goats.id,
            'child_ids': [
                Command.create({'name': 'Node 1', 'project_id': self.project_goats.id}),
                Command.create({'name': 'SuperNode 2', 'project_id': self.project_goats.id, 'child_ids': [Command.create({'name': 'Node 2', 'project_id': self.project_goats.id})]}),
                Command.create({'name': 'Node 3', 'project_id': self.project_goats.id}),
            ],
        })

        node1 = parent_task.child_ids[0]
        node2 = parent_task.child_ids[1].child_ids
        node3 = parent_task.child_ids[2]

        node1.dependent_ids = node2
        node2.dependent_ids = node3

        # Test copying the whole Node tree
        parent_task_copy = parent_task.copy()
        parent_copy_node1 = parent_task_copy.child_ids[0]
        parent_copy_node2 = parent_task_copy.child_ids[1].child_ids
        parent_copy_node3 = parent_task_copy.child_ids[2]

        # Relation should only be copied between the newly created node
        self.assertEqual(len(parent_copy_node1.dependent_ids), 1)
        self.assertEqual(parent_copy_node1.dependent_ids.ids, parent_copy_node2.ids, 'Node1copy - Node2copy relation should be present')
        self.assertEqual(len(parent_copy_node2.dependent_ids), 1)
        self.assertEqual(parent_copy_node2.dependent_ids.ids, parent_copy_node3.ids, 'Node2copy - Node3copy relation should be present')

        # Original Node should not have new relation
        self.assertEqual(len(node1.dependent_ids), 1)
        self.assertEqual(node1.dependent_ids.ids, node2.ids, 'Only Node1 - Node2 relation should be present')
        self.assertEqual(len(node2.dependent_ids), 1)
        self.assertEqual(node2.dependent_ids.ids, node3.ids, 'Only Node2 - Node3 relation should be present')

        # Test copying Node inside the chain
        single_copy_node2 = node2.copy()

        # Relation should be present between the other original node and the newly copied node
        self.assertEqual(len(single_copy_node2.depend_on_ids), 1)
        self.assertEqual(single_copy_node2.depend_on_ids.ids, node1.ids, 'Node1 - Node2copy relation should be present')
        self.assertEqual(len(single_copy_node2.dependent_ids), 1)
        self.assertEqual(single_copy_node2.dependent_ids.ids, node3.ids, 'Node2copy - Node3 relation should be present')

        # Original Node should have new relations
        self.assertEqual(len(node1.dependent_ids), 2)
        self.assertEqual(len(node3.depend_on_ids), 2)


# -*- coding: utf-8 -*-
"""
Created on Tue May 11 01:36:20 2021

@author: danish
"""
# Movie recommender by user rating
import pandas as pd
from sklearn.decomposition import TruncatedSVD
import numpy as np
column = ['user_id','item_id','rating','timestamp']
data = pd.read_csv('C:/Users/danish/Documents/ml-100k/u.data', sep = "\t", names = column)
column2 = ['item_id','movie name','release_date', 'video release date','imdb URL', 'unknown', 'action','adventure','animation', 'children', 'comedy', 'crime', 'documentary', 'drama', 'fantasy', 'film noir', 'horror', 'musical', 'mystery', 'romance', 'scifi', 'thriller', 'war', 'western']
movie = pd.read_csv('C:/Users/danish/Documents/ml-100k/u.item', sep = "|", encoding='latin-1', names = column2)
data_2 = pd.merge(data,movie, on = 'item_id')
crosstab = data_2.pivot_table(values = 'rating', columns = 'movie name', index = 'user_id', fill_value = 0)
X = crosstab.T.values
SVD = TruncatedSVD(n_components = 12, random_state = 17)
result_m = SVD.fit_transform(X)
corrcof = np.corrcoef(result_m)
m = crosstab.columns
m = list(m)

recommender = pd.DataFrame(corrcof,columns = m,index = m)
def recommend(name):
    X = pd.Series(recommender[name].nlargest(5).index)
    X.drop(0,inplace = True)
    return X
def namer():
    while True:
        name = input('Enter an Integer to respond to your movie:')
        if name.isdigit():
            name = int(name)
            if name < 1665:
                print('Your movie name is ',m[name],".....\n")
                name = m[name]
            else:
                print('Please enter integer less than 1664')
                continue
            break
        else:
            print('Please enter a valid digit')
    print('The movies that correlate most with your movies are\n')
    return recommend(name)
print(namer())

Recommender system/Recommender data 4.py


menu = """

[d] Depositar
[s] Sacar
[e] Extrato
[q] Sair

=> """

saldo = 0
limite = 500
extrato = ""
numero_saques = 0
LIMITE_SAQUES = 3

while True:

    opcao = input(menu)

    if opcao == "d":
        print("Depósito")

        valor = float(input("Digite o valor que você quer depositar: R$"))

        if valor > 0:
            saldo += valor
            extrato += f"Depósito de R${valor:.2f}\n"
            print(f"Depósito de R${valor:.2f} realizado com sucesso.")
        else:
            print("Operação inválida! O valor informado não é aceito.")

    elif opcao == "s":
        print("Saque")

        if numero_saques < LIMITE_SAQUES:
            valor = float(input("Digite o valor que deseja sacar: R$"))

            if valor <= saldo:

                if valor <= limite:
                    print(f"Saque de R${valor:.2f} realizado com sucesso")
                    numero_saques += 1
                    saldo -= valor
                    extrato += f"Saque de R${valor:.2f}\n"
                else:
                    print(f"O valor do saque excede o limite de R${limite:.2f}")
            else:
                print("Saldo insuficiente para realizar o saque.")

        else:
            print("Você atingiu o limite de saques diários.")

    elif opcao == "e":
        print("\n============ EXTRATO ============\n")
        print(extrato)
        print(f"\nSaldo: R${saldo:.2f}")
        print("==================================")

    elif opcao == "q":
        break

    else:
        print("Operação inválida, por favor selecione novamente a operação desejada")


'''
This notebook provides a quick example showing how to train a TF model.

As part of our framework, we'll also load and deploy this trained
model object as part of a containerized service that runs on Google GKE.
'''

import numpy as np
import pandas as pd
import pathlib
import random
import os

# Developed with TF 2.8.3
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

GCS_MODEL_PATH = os.environ['GCS_MODEL_PATH']

# Generate Dataset used for Demo
simulations  = 10000
player_count = int(simulations * 0.05)

data = []
for i in range(simulations):
    event_payload = {
        "playerid": f'player_{random.randint(100000,100000+player_count)}',
        "xcoord": random.random() * random.choice([-1,1]),
        "ycoord": random.random() * random.choice([-1,1]),
        "zcoord": random.random() * random.choice([-1,1]),
        "dow": random.randint(0,6),
        "hour": random.randint(0,23),
        "score": random.randint(1,100),
        "minutesPlayed": random.randint(0,60),
        "timeInStore": random.randint(0,30),
        "purchaseAmount": random.triangular(0,100,0) if random.random() >= 0.65 else 0,
    }
    data.append(event_payload)

dataset = pd.DataFrame.from_records(data)

dataset = dataset.dropna()

dataset.isna().sum()

# Remove playerid from training data
dataset.pop("playerid")

# Test and Train Dataset Split
train_dataset = dataset.sample(frac=0.8,random_state=0)
test_dataset  = dataset.drop(train_dataset.index)

# Set target as the "purchaseAmount"

train_target = train_dataset.pop('purchaseAmount')
test_target  = test_dataset.pop('purchaseAmount')

train_stats = train_dataset.describe()
train_stats = train_stats.transpose()
train_stats

# Normalize the input variables
def norm(x):
  return (x - train_stats['mean']) / train_stats['std']

normed_train_data = norm(train_dataset)
normed_test_data  = norm(test_dataset)

# Build our demo Model

def build_model():
  model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=[len(train_dataset.keys())]),
    layers.Dense(64, activation='relu'),
    layers.Dense(1)
  ])

  optimizer = tf.keras.optimizers.RMSprop(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae', 'mse'])
  return model

model = build_model()

model.summary()

# The patience parameter is the amount of epochs to check for improvement
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=15)

early_history = model.fit(normed_train_data, train_target,
                    epochs=1000, validation_split=0.2,
                    callbacks=[early_stop])

# Save Training Model to GCS
print(f'Saving ML Model to GCS: {GCS_MODEL_PATH}')
model.save(GCS_MODEL_PATH)


from itertools import combinations

N, M = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(N)]
stores = []
house = []
for i in range(N):
    for j in range(N):
        if matrix[i][j] == 2:
            stores.append([i, j])
        if matrix[i][j] == 1:
            house.append([i, j])

min_rlt = 987654321
distance = 0
for store in combinations(stores, M):
    chicken_street = []
    for home in house:
        min_d = []
        for kfc in store:
            distance = abs(home[0]-kfc[0]) + abs(home[1]-kfc[1])
            min_d.append(distance)

        chicken_street.append(min(min_d))
    min_rlt = min(min_rlt, sum(chicken_street))

print(min_rlt)


import elementpath
import xml.etree.ElementTree as et

tree = et.parse("*.xml")
root = tree.getroot()

list = root.findall('tag')
root.findall("path")

rank = list.find('contents').text
#contents
list.get('name')
list.attrib['name']
#child
elem = et.SubElement(root, 'contents')
elem = et.SubElement(root, 'contents', attrib={'name':'Liechtenstein'})

#edit
for content in root.find('contents'):
    rank = int(content.find('rank'))
    if rank > 50:
        root.remove(content)

#output
tree = et.ElementTree(root)
tree.write('filename', encoding="utf-8", xml_declaration=True)


"""Helpers for the custom CLEF eHealth Task 2 file formats

"""

import os
import os.path
from collections import defaultdict

def load_topic_numbers(topic_path):
    """Read the list of topic files and then load all the topic numbers

    This is tailored to the CLEF eHealth Task 2 formats

    example:
    $head -30 ../Training\ Data/topics_train/1
    Topic: CD010438

    Title: Thromboelastography (TEG) and rotational thromboelastometry (ROTEM)
    for trauma-induced coagulopathy in adult trauma patients with bleeding

    Query:
    (Thrombelastogra$ or Thromboelastogra$ or (thromb$ adj2 elastogra$) or TEG or haemoscope or haemonetics).mp
    Thrombelastography/
    (thromboelasto$ or thrombelasto$ or (thromb$ adj2 elastom$) or (rotational adj2 thrombelast) or ROTEM or "tem international").mp.
    1 or 2 or 3
    exp animals/ not humans.sh.
    4 not 5
    limit 6 to yr="1970 -Current"

    Pids:
        23446185
        23425732
        23410777
        23407150
        23385320
        23354242
        23354228
        23354227
        23351534
        23321555
        23316863
        23313481
        23302970
        23302040
        23301972
        23301969
    """
    if not os.path.exists(topic_path):
        raise ValueError("Not a valid topic directory")

    topics_to_numbers = {}
    for topic_number in os.listdir(topic_path):
        topic_file = os.path.join(topic_path, topic_number)
        if not os.path.isfile(topic_file):
            continue

        topic = None
        with open(topic_file, 'r') as tf:
            for line in tf:
                if 'Topic:' in line:
                    topic = line.strip().split(" ")[1]
                    break
        topics_to_numbers[topic] = int(topic_number)

    return topics_to_numbers

def load_all_qrels(qrel_path):
    """Read a qrels file and load the topics->docids->judgements

    This is tailored to the CLEF eHealth Task 2 formats

    example:
    $head ../Training\ Data/qrel_abs_train
    CD010438     0  4461416      0
    CD010438     0  19762299     0
    CD010438     0  16607076     0
    CD010438     0  20042049     0
    CD010438     0  7223223      0
    CD010438     0  21330915     0
    CD010438     0  4576350      0
    CD010438     0  20813396     0
    CD010438     0  12675727     0
    CD010438     0  22782135     0
    """
    if not os.path.exists(qrel_path):
        raise ValueError("Not a valid qrel file path")

    topic_qrels = defaultdict(lambda: defaultdict(set))
    with open(qrel_path, 'r') as qrfile:
        for line in qrfile:
            # parts = line.strip().split()
            topic, unk, pubmedid, pos = line.strip().split()
            pos = int(pos)
            topic_qrels[topic]['all'].add(pubmedid)
            if pos:
                topic_qrels[topic]['pos'].add(pubmedid)
            else:
                topic_qrels[topic]['neg'].add(pubmedid)
    return topic_qrels

if __name__ == "__main__":

    # Ad hoc testing if called directly

    # 4.7M    ../Training Data/qrel_abs_train
    # 4.7M    ../Training Data/qrel_content_train
    # 1.9M    ../Training Data/topics_train

    path = "../downloads/Training Data/topics_train/"
    topics_to_numbers = load_topic_numbers(path)
    print("")
    print("topics to numbers:")
    print(topics_to_numbers)
    print("topic count: {}".format(len(topics_to_numbers)))
    print("")

    # path = "../downloads/Training Data/qrel_content_train"
    path = "../downloads/Training Data/qrel_abs_train"
    topic_qrels = load_all_qrels(path)
    print("")
    print("topics to pubmed qrels:")
    count = 0
    for topic, qrels in topic_qrels.iteritems():
        count += 1
        print("")
        for qtype in ('all', 'neg', 'pos'):
            qr_docids = qrels[qtype]
            print("{} - {} - {} ({}...)".format(topic, qtype, len(qr_docids), list(qr_docids)[:5]))
    print("")
    print("topic count: {}".format(count))
    print("")