#!/usr/bin/python2
import __future__

import rospy
from std_msgs.msg import Int8, Float32
from sensor_msgs.msg import Imu
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point, Quaternion, Twist, Vector3, TransformStamped
import tf
import tf2_ros

from ironbot_rmt_ctrl.srv import RstLocalOdom, RstLocalOdomResponse
from ironbot_rmt_ctrl.srv import GetScanPoint
from utility import theta_rot

import sys
import math

import numpy as np
from numpy.random import uniform, randn
from scipy.spatial.transform import Rotation as R
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

import cv2

from icp_func import *

plt.style.use('fivethirtyeight')

# Declare Global Variable
glbAX = 0.0
glbAY = 0.0
glbWZ = 0.0
glbRPS = 0.0
glbCmd = Twist()

glbBotLoc = []

def create_uniform_particles(x_range, y_range, hdg_range, N):
    particles = np.empty((N, 3))
    particles[:, 0] = uniform(x_range[0], x_range[1], size=N)
    particles[:, 1] = uniform(y_range[0], y_range[1], size=N)
    particles[:, 2] = uniform(hdg_range[0], hdg_range[1], size=N)
    particles[:, 2] %= 2 * np.pi
    return particles

def create_gaussian_particles(mean, std, N):
    particles = np.empty((N, 3))
    particles[:, 0] = mean[0] + (randn(N) * std[0])
    particles[:, 1] = mean[1] + (randn(N) * std[1])
    particles[:, 2] = mean[2] + (randn(N) * std[2])
    particles[:, 2] %= 2 * np.pi
    return particles

class robot_state():
  def __init__(self, start_time=0.0, tyre_r=0.0336, steer_max=2.84, steer_range=50.0, L=0.14, lr=0.02, N_particles=50, model="ACKM", use_scan=False):
    self.rstLocalOdom_service = rospy.Service('rst_local_odom', RstLocalOdom, self.resetLocalOdom)

    self.state = np.zeros(5, dtype=np.float)  #x, y, theta, vx, w
    self.local_state = np.zeros(5, dtype=np.float)
    self.last_time = start_time

    self.tyre_radius = tyre_r
    self.steer_max = steer_max
    self.steer_bound = np.pi*steer_range/180.0
    self.L = L
    self.lr = lr
    self.N_particles = N_particles
    self.model = model

    self.twoPiR = 2*np.pi*self.tyre_radius
    self.steerConv = self.steer_bound/self.steer_max

    self.record_size = 50
    self.record_pt = 0
    self.imu_record = np.zeros((self.record_size,4), dtype=np.float)
    self.imu_chop_lv = 0.03

    self.idx = 0

    self.theta_rot_vec = np.vectorize(theta_rot)
    if use_scan:
      rospy.wait_for_service("scan_points")
      self.service_get_scan_point = rospy.ServiceProxy("scan_points", GetScanPoint)
      self.scan = np.zeros(1)
      self.scan_prev = np.zeros(1)
      self.scan_stat = 0

    rospy.Subscriber("est_cmd", Int8, self.consoleCmd_callback)

  def consoleCmd_callback(self, msg):
    if msg.data==1: #reset odom state
      self.state = np.zeros(5, dtype=np.float)
      self.local_state = np.zeros(5, dtype=np.float)
      self.last_time = rospy.Time.now().to_sec()
      self.imu_record = np.zeros((self.record_size,4), dtype=np.float)

  def updateScanPoint(self):
    pt = self.service_get_scan_point(0)
    self.scan_prev = self.scan.copy()
    self.scan = np.column_stack([pt.points_x, pt.points_y])
    if self.scan_stat<2:
      self.scan_stat += 1

  def resetLocalOdom(self, rst):
    self.local_state = np.zeros(5, dtype=np.float)
    print("Reset Local Odometry")
    return RstLocalOdomResponse(0)

  def ackermann_model_pred(self, control, std, dt):
    dX = dY = dTheta = 0.0

    #lookup table for steer input to hardware steer angle
    #control[1] -> steer angle
    steer = self.steerConv*control[1] #inaccurate assumption

    steer += abs(np.sign(control[1]))*randn(1)[0]*std[0] #noise

    #lookup table for motor input to forward speed
    acc = control[0]
    acc += abs(np.sign(control[0]))*randn(1)[0]*std[1]
    fSpeed = self.state[3] + acc*dt

    slip = np.arctan(self.lr*np.tan(steer)/self.L)
    turn = (self.state[2] + slip) % (2*np.pi)

    dx = fSpeed*np.cos(turn)*dt
    dy = fSpeed*np.sin(turn)*dt

    pred_angular_v = fSpeed*np.cos(slip)*np.tan(steer)/self.L
    dTheta = (pred_angular_v*dt) % (2*np.pi)

    return dX, dY, dTheta

  def differential_model_pred(self, control, std, t):

    dX = dY = dTheta = 0.0

    return dX, dY, dTheta

  def predict_step(self, particles, control, std, t):
    dt = float(t - self.last_time)

    dX = dY = dTheta = 0.0
    if self.model=="ACKM":
      dX, dY, dTheta = self.ackermann_model_pred(control, std, dt)
    elif self.model=="DIFF":
      dX, dY, dTheta = self.differential_model_pred(control, std, dt)

    N = len(particles)

    particles[:,0] += dX
    particles[:,1] += dY
    particles[:,2] = self.theta_rot_vec(particles[:,2], dTheta)

  def update_step(self, particles):
    pass

  def direct_state_inc(self, dx, dy, dth):
    self.state[0] += dx
    self.state[1] += dy
    self.state[2] = theta_rot(self.state[2], dth)

  def state_pred_vanilla(self, wheel_rps, angular_v, acc_x, acc_y, control, t, dbg=False):
    dt = float(t - self.last_time)
    steer = self.steerConv*control[1]
    direction = np.sign(self.steerConv*control[0])
    if direction==0:
      direction = np.sign(acc_x)

    encoder_vel = direction*wheel_rps*self.twoPiR
    imu_vel = np.dot(self.imu_record[:,0], self.imu_record[:,1])
    if imu_vel<self.imu_chop_lv:
      imu_vel = 0.0

    #fSpeed = 0.5*encoder_vel + 0.5*imu_vel
    fSpeed = encoder_vel

    slip = np.arctan(self.lr*np.tan(steer)/self.L)
    turn = (self.state[2] + slip) % (2*np.pi)

    dx = fSpeed*np.cos(turn)*dt
    dy = fSpeed*np.sin(turn)*dt

    if dbg: print("[%d] dt:%f, dx:%f, EncVel:%f, Turn:%f, IMUVel:%f"% (self.idx, dt, dx, encoder_vel, turn, imu_vel))

    pred_angular_v = fSpeed*np.cos(slip)*np.tan(steer)/self.L
    mean_angular_v = 0.0
    if fSpeed!=0:
      mean_angular_v = 0.5*(angular_v+pred_angular_v)
    theta = theta_rot(self.state[2], mean_angular_v*dt)

    self.state[0] += dx
    self.state[1] += dy
    self.state[2] = theta
    self.state[3] = fSpeed
    self.state[4] = mean_angular_v

    self.local_state[0] += dx
    self.local_state[1] += dy
    self.local_state[2] = theta_rot(self.local_state[2], mean_angular_v*dt)
    self.local_state[3] = fSpeed
    self.local_state[4] = mean_angular_v

    self.last_time = t

    self.imu_record[self.record_pt] = np.array([dt, acc_x, acc_y, angular_v])
    self.record_pt = (self.record_pt+1)%self.record_size

    self.idx+=1
    """
    if self.record_pt>5:
      print self.imu_record[self.record_pt-5:self.record_pt]
      print imu_derived_v
      print
    print self.state[0], self.state[1]
    """

def plt_animate(i):
  global glbBotLoc

  plt.cla()
  plt.plot()

def imu_sub_callback(imuData):
  global glbAX
  global glbAY
  global glbWZ

  glbAX = imuData.linear_acceleration.x
  glbAY = imuData.linear_acceleration.y
  glbWZ = imuData.angular_velocity.z
  #print "AX:%f, AY:%f, WZ:%f" % (glbAX,glbAY,glbWZ)

def rps_sub_callback(rpsData):
  global glbRPS
  glbRPS = rpsData.data
  #print "New RPS: %f" % glbRPS

def cmd_sub_callback(cmdData):
  global glbCmd
  glbCmd = cmdData
  #print glbCmd.linear.x

def odometer():
  PUB_ODOM = True
  USE_SCAN = True

  if len(sys.argv)>1:
    if sys.argv[1]=="sim":
      PUB_ODOM = False

  # In ROS, nodes are uniquely named. If two nodes with the same
  # name are launched, the previous one is kicked off. The
  # anonymous=True flag means that rospy will choose a unique
  # name for our 'listener' node so that multiple listeners can
  # run simultaneously.
  rospy.init_node('odometer', anonymous=False)
  print("Setup Odometer Node")

  rospy.Subscriber("imu", Imu, imu_sub_callback)
  rospy.Subscriber("rps", Float32, rps_sub_callback)
  rospy.Subscriber("cmd_vel", Twist, cmd_sub_callback)

  odom_broc = tf.TransformBroadcaster()
  twist_pub = rospy.Publisher("speedometer", Twist, queue_size=1)
  localOdom_pub = rospy.Publisher("local_odom", Odometry, queue_size=1)

  msgLocalOdom = Odometry()
  localOdom_pub.publish(msgLocalOdom)

  vel_msg = Twist()

  rate = rospy.Rate(2)

  bot = robot_state(start_time=rospy.Time.now().to_sec(), use_scan=USE_SCAN)

  # Setup static transformint

  # spin() simply keeps python from exiting until this node is stopped
  tmpORT = 0.0
  tmpX = 0.0
  tmpY = 0.0

  while not rospy.is_shutdown():
    global glbAX
    global glbAY
    global glbWZ
    global glbRPS
    global glbCmd
    current_time = rospy.Time.now()

    """
    bot.state_pred_vanilla( wheel_rps=glbRPS,
                            angular_v=glbWZ,
                            acc_x=glbAX,
                            acc_y=glbAY,
                            control=(glbCmd.linear.x, glbCmd.angular.z),
                            t=current_time.to_sec(), dbg=True)
    """

    if USE_SCAN:
      bot.updateScanPoint()
      #print("Scan: ", bot.scan[0:3])
      print("Point N: ", bot.scan.shape[0])

      if bot.scan_stat >= 2:
        R_hist, X_hist, Y_hist, pts = icp(bot.scan_prev, bot.scan, distance_threshold=0.1, verbose=False)

        tmpORT = theta_rot(tmpORT, sum(R_hist))
        tmpX += sum(X_hist)
        tmpY += sum(Y_hist)

        print("Est Coord: (", tmpX, tmpY, ")")
        print("Est Orien: ", tmpORT)
        #print(tmpORT)
        print

        #a = raw_input()

    #print("WZ:", glbWZ, "RPS:", glbRPS, "CMD:", glbCmd)
    #print("X=", bot.state[0], "Y=", bot.state[1], "VX=", bot.state[3])

    if PUB_ODOM:

      odom_tran = (float(bot.state[0]), float(bot.state[1]), 0.0)
      odom_quat = tf.transformations.quaternion_from_euler(0.0,0.0,float(bot.state[2]))
      odom_broc.sendTransform(odom_tran, odom_quat, current_time, "base_link", "odom")

      msgLocalOdom.pose.pose.position.x = bot.local_state[0]
      msgLocalOdom.pose.pose.position.y = bot.local_state[1]
      local_ort = tf.transformations.quaternion_from_euler(0.0,0.0,bot.local_state[2])
      msgLocalOdom.pose.pose.orientation.x = local_ort[0]
      msgLocalOdom.pose.pose.orientation.y = local_ort[1]
      msgLocalOdom.pose.pose.orientation.z = local_ort[2]
      msgLocalOdom.pose.pose.orientation.w = local_ort[3]
      localOdom_pub.publish(msgLocalOdom)

    vel_msg.linear.x = bot.state[3]
    vel_msg.angular.z = bot.state[4]
    twist_pub.publish(vel_msg)

    rate.sleep()

if __name__=='__main__':
  odometer()


from fastapi import FastAPI, Header, Response, HTTPException
from environs import Env

env = Env()
app = FastAPI()

SERVER_API_KEY = env('SERVER_API_KEY')

@app.get('/')
async def root():
    return Response(
        content=f'Мы переезжаем на v2. Все изменения в /docs. Используйте временный ключ для доступа к api: {SERVER_API_KEY}',
        media_type='text/html',
        status_code=302,
        headers={
            'Location': '/',
        },
    )

@app.get('/api/v2/location')
async def location(
    api_key: str | None = Header(default=None),
):
    if api_key != SERVER_API_KEY:
        raise HTTPException(status_code=403, detail={'error': 'wrong key'})

    results = [
        {
            'device_id': device_id,
            'location': None,
            'status': 'destroyed',
        } for device_id in range(64)
    ]

    results[18].update({
        'location': ['68.946192', '94.506208'],
        'status': 'operational',
    })

    results[33].update({
        'location': ['9223372036854775807', '9223372036854775807'],
        'status': 'corrupted',
    })

    results[10].update({
        'location': ['68.388253', '175.169301'],
    })

    results[34].update({
        'location': ['59.817252', '153.020863'],
    })

    results[60].update({
        'location': ['62.356226', '113.887236'],
    })

    return results


import os
from colorfield.fields import ColorField
from django.db import models
from django import forms
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel

path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

from blog.models import Tags

# Create your models here.

class Sliders(models.Model):
    slider_types = [
        ('standart', 'Стандарт'),
        ('calendar', 'Календарь'),
    ]
    locales = [
        ('ru', 'ru'),
        ('en', 'en'),
    ]
    locale = models.CharField(max_length=250, verbose_name="Language", choices=locales, default='ru')
    order_num = models.IntegerField('Порядок', null=False, blank=True, default=999)
    ontop = models.BooleanField('в начало', null=True, blank=True, default=False)
    draft = models.BooleanField('черновик', null=True, blank=True, default=False)
    color = ColorField(default='#FFFFFF', verbose_name="цвет")
    title = models.CharField(max_length=128, null=True, blank=True, verbose_name="заголовок")
    subtitle = models.CharField(blank=True, max_length=250, verbose_name="подзаголовок")
    standart_link = models.CharField(blank=True, max_length=255, verbose_name="ссылка")
    image = models.ForeignKey('wagtailimages.Image', blank=True, null=True, on_delete=models.CASCADE, related_name='+',
                              verbose_name="Основное изображение",
                              )
    calendar_image = models.ForeignKey('wagtailimages.Image', blank=True, null=True, on_delete=models.CASCADE,
                                       related_name='+', verbose_name="Изображение в календарь",
                                       )
    slider_type = models.CharField(max_length=250, choices=slider_types, default='black', verbose_name="Тип слайда")
    title_one = models.CharField(max_length=250, blank=True, verbose_name="подзаголовок 1")
    tag_link_one = models.CharField(blank=True, max_length=255, verbose_name="ссылка 1")
    title_two = models.CharField(max_length=250, blank=True, verbose_name="подзаголовок 2")
    tag_link_two = models.CharField(blank=True, max_length=255, verbose_name="ссылка 2")
    title_three = models.CharField(max_length=250, blank=True, verbose_name="подзаголовок 3")
    tag_link_three = models.CharField(blank=True, max_length=255, verbose_name="ссылка 3")
    collect = models.CharField(blank=True, max_length=255, verbose_name="название подборки")
    collect_tag = models.ForeignKey(Tags, related_name='%(class)s_tag', on_delete=models.CASCADE, null=True, blank=True,
                                    verbose_name='Tag подборки')
    panels = [
        MultiFieldPanel([
            FieldPanel('order_num'),
            FieldPanel('ontop', widget=forms.CheckboxInput),
            FieldPanel('draft', widget=forms.CheckboxInput),
            FieldPanel('slider_type'),
            FieldPanel('title'),
            FieldPanel('subtitle'),
            FieldPanel('color'),
            FieldPanel('standart_link'),
        ], heading="Данные слайдера"),
        ImageChooserPanel('image'),
        MultiFieldPanel([
            ImageChooserPanel('calendar_image'),
            FieldPanel('title_one'),
            FieldPanel('tag_link_one'),
            FieldPanel('title_two'),
            FieldPanel('tag_link_two'),
            FieldPanel('title_three'),
            FieldPanel('tag_link_three'),
            FieldPanel('collect'),
            FieldPanel('collect_tag'),
        ], heading="Данные календаря"),
    ]

    class Meta:
        verbose_name = 'Изображение слайдера'
        verbose_name_plural = 'Изображения слайдера'
        ordering = ['-ontop', 'order_num', 'draft', '-id']

class SlidersEN(Sliders):
    locale = 'en'

    def save(self, *args, **kwargs):
        self.locale = 'en'
        return super().save(*args, **kwargs)


if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))

    max_data = max(arr)

    remove_data = {max_data}

    new_list = [i for i in arr if i not in remove_data]

    print(max(new_list))


from manim import *
from itertools import permutations
from typing import List
from numpy import arange
from math import factorial
from permutation_group_definition import write_group_defs

class SymmetricalGroup(Scene):
    def construct(self):
        bottom_rows = list(permutations("123"))
        bmatrices: List[str] = []
        for row in bottom_rows:
            matrix = r"\begin{bmatrix}"\
                r"1 & 2 & 3 \\" +\
                " & ".join(row) + r" \\"\
                r"\end{bmatrix}"
            bmatrices.append(matrix)

        write_group_defs(self, "Symmetrical Group", r"S_3", bmatrices, r"\circ", math_font_size=36, read_time=4.0)

class ShowAllBijections(Scene):
    def construct(self):

        N = 5
        if (N % 2 == 0):
            hrange = arange(-N / 2, N / 2, 1.0) + 0.5
        else:
            hrange = arange(-(N // 2), N // 2 + 1, 1.0)
        CELL_SIZE = 1.0
        HORIZ_DIST = 1
        l_row = VGroup(*[
            Square(CELL_SIZE).shift(HORIZ_DIST * LEFT,  i * CELL_SIZE * UP).set_stroke(width=1.0)
            for i in hrange
        ])
        r_row = VGroup(*[
            Square(CELL_SIZE).shift(HORIZ_DIST * RIGHT, i * CELL_SIZE * UP).set_stroke(width=1.0)
            for i in hrange
        ])
        assert len(l_row) == len(r_row) == N, (len(l_row), len(r_row), N, hrange)
        self.play(Create(l_row), Create(r_row))

        self.wait(0.5)

        for i, permutation in enumerate(permutations(range(N), N)):
            arrows = VGroup(*[
                Arrow(l_row[old_idx].get_center(), r_row[new_idx].get_center(), stroke_width=1.0, buff=0, tip_length=0.1)
                for old_idx, new_idx in enumerate(permutation)
            ])

            if i == 0:
                self.play(Create(arrows), run_time=0.50)
            else:
                self.add_foreground_mobject(arrows)
                self.wait(0.05)
            if i != factorial(N) - 1:
                self.remove(arrows)

        self.play(Uncreate(arrows))
        self.play(Uncreate(l_row), Uncreate(r_row))
        self.wait(0.5)


import math
from typing import (
    Generator,
    List,
    Dict,
    Optional,
    Sequence,
    TypeVar,
    Union,
    Tuple,
    cast,
    overload,
)

from anacreonlib.types.response_datatypes import World, Trait
from anacreonlib.types.scenario_info_datatypes import ScenarioInfoElement
from anacreonlib.types.type_hints import Location

T = TypeVar("T")
U = TypeVar("U")

def flat_list_to_tuples(lst: Sequence[T]) -> List[Tuple[T, T]]:
    """
    Convert a list of the form `[1, 2, 3, 4, ...]` into the list of tuples `[(1, 2), (3, 4)]`
    """
    return list(zip(lst[::2], lst[1::2]))

def flat_list_to_n_tuples(n: int, lst: List[T]) -> List[Tuple[T, ...]]:
    zip_args = [lst[i::n] for i in range(n)]
    return list(zip(*zip_args))

def dict_to_flat_list(dict: Dict[T, U]) -> List[Union[T, U]]:
    """
    Convert a dict to a flat list alternating between keys and values
    :param dict: A dict e.g `{1: 2, 3: 4, 5: 6}`
    :return: A list alternating between keys and values (e.g `[1, 2, 3, 4, 5, 6]`)
    """
    ret: List[Union[T, U]] = []
    for k, v in dict.items():
        ret.append(k)
        ret.append(v)
    return ret

def _diff_squared(a: float, b: float) -> float:
    return (a - b) * (a - b)

def dist(pointA: Location, pointB: Location) -> float:
    dist2 = sum(map(_diff_squared, pointA, pointB))
    return math.sqrt(dist2)

def world_has_trait(
    scninfo: List[ScenarioInfoElement],
    world: World,
    target_trait_id: int,
    include_world_characteristics: bool = True,
) -> bool:
    """
    Returns true if a world has the trait or a trait inheriting from it
    :param target_trait_id: The ID of the trait
    :param world: The dictionary representing the world
    :return: bool
    """
    trait_dict = world.squashed_trait_dict

    trait_id: int
    for trait_id in trait_dict.keys():
        if target_trait_id == trait_id:
            return True
        elif trait_inherits_from_trait(scninfo, trait_id, target_trait_id):
            return True

    if include_world_characteristics:
        characteristic_traits = (world.world_class, world.designation, world.culture)
        characteristic_inherits_from_target = any(
            trait_inherits_from_trait(scninfo, characteristic, target_trait_id)
            for characteristic in characteristic_traits
        )

        if (
            target_trait_id in characteristic_traits
            or characteristic_inherits_from_target
        ):
            return True

    return False

def trait_inherits_from_trait(
    scninfo: List[ScenarioInfoElement],
    child_trait: Union[Trait, int],
    parent_trait: Union[Trait, int],
) -> bool:
    """
    Checks if trait_a inherits from trait_b i.e
    trait_a extends trait_b
    trait_a inheritsFrom trait_b
    :param child_trait:
    :param parent_trait:
    :return:
    """
    try:
        # looks up up trait in scenario info based on id. information from Trait object is not used.
        childs_parent_list = next(
            trait.inherit_from
            for trait in scninfo
            if trait.id == child_trait
            or (isinstance(child_trait, Trait) and trait.id == child_trait.trait_id)
        )
        if childs_parent_list is None:
            return False

        return parent_trait in childs_parent_list or any(
            trait_inherits_from_trait(scninfo, trait, parent_trait)
            for trait in childs_parent_list
        )
    except StopIteration as e:
        raise ValueError("child trait was not found in scenario info") from e
    except KeyError:
        return False

def trait_under_construction(
    squashed_trait_dict: Dict[int, Union[int, Trait]], trait_id: int
) -> bool:
    """Returns true if a trait/structure on a world is in the process of being built"""
    if trait_id not in squashed_trait_dict.keys():
        return False  # world doesn't have it at all
    trait = squashed_trait_dict[trait_id]
    if isinstance(trait, int):
        return False  # its a simple structure, world has it, and its built
    if trait.build_complete is not None:
        return True

    return False

def world_has_fully_built_trait(
    scninfo: List[ScenarioInfoElement], world: World, target_trait_id: int
) -> bool:
    return world_has_trait(
        scninfo, world, target_trait_id, True
    ) and trait_under_construction(world.squashed_trait_dict, target_trait_id)

def type_supercedes_type(
    scninfo: List[ScenarioInfoElement],
    later_improvement_id: int,
    earlier_improvement_id: int,
) -> bool:
    """Returns True if trait_a needs trait_b to be built first at some point"""
    later_improvement = scninfo[later_improvement_id]
    if later_improvement.build_upgrade is not None:
        return earlier_improvement_id in later_improvement.build_upgrade or any(
            type_supercedes_type(scninfo, trait, earlier_improvement_id)
            for trait in later_improvement.build_upgrade
        )
    return False

def get_world_primary_industry_products(world: World) -> Optional[List[int]]:
    primary_industry = next(
        (
            trait
            for trait in world.traits
            if isinstance(trait, Trait) and trait.is_primary
        ),
        None,
    )

    if primary_industry is None or primary_industry.production_data is None:
        return None

    return [
        cast(int, res_id)
        for res_id, pct_alloc, cannot_build in flat_list_to_n_tuples(
            3, primary_industry.build_data
        )
    ]

_one_min_in_cycles = 1 / 1440

def calculate_attrition_equilibrium(
    initial_qty: int, half_life_in_cycles: float, production_per_watch: float = 0
) -> Generator[int, None, None]:
    current_qty = initial_qty
    while True:
        after_attrition = current_qty * 0.5 ** (_one_min_in_cycles / half_life_in_cycles)
        after_production = after_attrition + production_per_watch
        next_qty = int(after_production)
        yield next_qty
        current_qty = next_qty

class TermColors:
    HEADER = "\033[95m"
    OKBLUE = "\033[94m"
    OKCYAN = "\033[96m"
    OKGREEN = "\033[92m"
    WARNING = "\033[93m"
    FAIL = "\033[91m"
    ENDC = "\033[0m"
    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"


import os
import glob

global homogeneous
global path

#pathstring = str(os.path.dirname(os.path.realpath(__file__)) + "/input_files/comass[0-9][0-9].txt")
pathstring = str(os.path.dirname(os.path.realpath(__file__)) + "/input_files/comass16.txt")
path = glob.glob(pathstring)
degree = 0

def find_degree(pathstring, degree):
    file = open(pathstring, 'r')
    j = 0

    for i, line in enumerate(file):
        if i == 2:
            print(line)
            num = 15 #hardcoded 15 which is getting looped over untill it hits 0

            while j < num:
                string = "(n-" + str(num) + ")"
                #print("string =" + string)
                #print("FOUND = " + str(line.find(string)))
                if line.find(string) is not -1:
                    if num > degree:
                        degree = num
                        num = num-1
                    else:
                        num = num-1
                    print(string)
                    num = int(num)-1
                else:
                    num = num-1
            print("degree = " + str(degree))
            break
        else:
            continue
    print("found degree = " + str(the_degree))
    return degree

#the_degree = find_degree(pathstring=pathstring, degree=0)


#! /usr/bin/env python3
import os
import sys
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from itertools import product

sns.set(style="whitegrid")

datapoints = []

categories = ["bitos", "inorder"]
control = "http"
params = [(3, 3), (2, 4), (1, 5)]
param_desc = {(3, 3): "3 up 3 down", (2, 4): "2 up 4 down", (1, 5): "1 up 5 down"}

datapoints = []
for item, p in product(categories, params):
    folder_name = f"{item}_{p[0]}_{p[1]}"
    for d in os.scandir(f"{sys.argv[1]}/{folder_name}"):
        if d.name.startswith("run"):
            for peer in os.scandir(d):
                with open(peer) as f:
                    df = pd.read_csv(peer)
                    ttfb = df[df["index"] == 0]["time"].iloc[0]
                    datapoints.append((ttfb / 1000, d.name, param_desc[p], item))

for p in params:
    folder_name = f"{control}_{p[0]}_{p[1]}"
    for d in os.scandir(f"{sys.argv[1]}/{folder_name}"):
        if d.name.startswith("run"):
            for peer in os.scandir(d):
                with open(peer) as f:
                    datapoints.append(
                        (
                            float(f.readlines()[-2].split()[-1]),
                            d.name,
                            param_desc[p],
                            control,
                        )
                    )

bittorrent = pd.DataFrame(
    datapoints, columns=["Time Taken (s)", "run", "Swarm Configuration", "Strategy"]
)

g = sns.catplot(
    data=bittorrent,
    x="Strategy",
    y="Time Taken (s)",
    hue="Swarm Configuration",
    kind="bar",
)
g.set(yscale="log")

plt.title("Time to First Byte")
plt.show()


from pathlib import Path
import sys

BASE_DIR = Path(__file__).parent.parent.absolute()
CONFIG_DIR = Path(BASE_DIR, "config")
DATA_DIR = Path(BASE_DIR, "data")
ASSETS_DIR = Path(DATA_DIR, "assets")
STORE_DIR = Path(BASE_DIR, "store")
MODELS_DIR = Path(STORE_DIR, "models")
RESULTS_DIR = Path(BASE_DIR, "results")
IMGCROP_DIR = Path(RESULTS_DIR, "img_crop")
RAWDATA_DIR = Path(RESULTS_DIR, "raw_data")

# Add to path
sys.path.append(str(BASE_DIR))
sys.path.append(str(BASE_DIR / "strong_sort"))

# Create dirs
DATA_DIR.mkdir(parents=True, exist_ok=True)
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
IMGCROP_DIR.mkdir(parents=True, exist_ok=True)
RAWDATA_DIR.mkdir(parents=True, exist_ok=True)
(MODELS_DIR / "strong_sort").mkdir(parents=True, exist_ok=True)

MODELS = [
  "VGG-Face",
  "Facenet",
  "Facenet512",
  "OpenFace",
  "DeepFace",
  "DeepID",
  "ArcFace",
  "Dlib",
  "SFace",
]

BACKENDS = [
  'opencv',
  'ssd',
  'dlib',
  'mtcnn',
  'retinaface',
  'mediapipe'
]


from deepposekit.models.backend.backend import find_subpixel_maxima

from tensorflow.keras.layers import Layer, InputSpec
from tensorflow.python.keras.utils.conv_utils import normalize_data_format

class SubpixelMaxima2D(Layer):
    """Subpixel maxima layer for 2D inputs.
    Convolves a 2D Gaussian kernel to find
    the subpixel maxima and 2D indices
    for the channels in the input.
    The output is ordered as [row, col, maximum].
    # Arguments
        index: Integer,
            The index to slice the channels to.
            Default is None, which does not slice the channels.
        data_format: A string,
            one of `channels_last` (default) or `channels_first`.
            The ordering of the dimensions in the inputs.
            `channels_last` corresponds to inputs with shape
            `(batch, height, width, channels)` while `channels_first`
            corresponds to inputs with shape
            `(batch, channels, height, width)`.
            It defaults to the `image_data_format` value found in your
            Keras config file at `~/.keras/keras.json`.
            If you never set it, then it will be "channels_last".
    # Input shape
        4D tensor with shape:
        - If `data_format` is `"channels_last"`:
            `(batch, rows, cols, channels)`
        - If `data_format` is `"channels_first"`:
            `(batch, channels, rows, cols)`
    # Output shape
        3D tensor with shape:
        - If `data_format` is `"channels_last"`:
            `(batch, 3, index)`
        - If `data_format` is `"channels_first"`:
            `(batch, index, 3)`
    """

    def __init__(
        self,
        kernel_size,
        sigma,
        upsample_factor,
        index=None,
        coordinate_scale=1.0,
        confidence_scale=1.0,
        data_format=None,
        **kwargs
    ):
        super(SubpixelMaxima2D, self).__init__(**kwargs)
        self.data_format = normalize_data_format(data_format)
        self.input_spec = InputSpec(ndim=4)
        self.kernel_size = kernel_size
        self.sigma = sigma
        self.upsample_factor = upsample_factor
        self.index = index
        self.coordinate_scale = coordinate_scale
        self.confidence_scale = confidence_scale

    def compute_output_shape(self, input_shape):
        if self.data_format == "channels_first":
            n_channels = self.index if self.index is not None else input_shape[1]
        elif self.data_format == "channels_last":
            n_channels = self.index if self.index is not None else input_shape[3]
        return (input_shape[0], n_channels, 3)

    def call(self, inputs):
        if self.data_format == "channels_first":
            inputs = inputs[:, : self.index]
        elif self.data_format == "channels_last":
            inputs = inputs[..., : self.index]
        outputs = find_subpixel_maxima(
            inputs,
            self.kernel_size,
            self.sigma,
            self.upsample_factor,
            self.coordinate_scale,
            self.confidence_scale,
            self.data_format,
        )
        return outputs

    def get_config(self):
        config = {
            "data_format": self.data_format,
            "kernel_size": self.kernel_size,
            "sigma": self.sigma,
            "upsample_factor": self.upsample_factor,
            "index": self.index,
            "coordinate_scale": self.coordinate_scale,
            "confidence_scale": self.confidence_scale,
        }
        base_config = super(SubpixelMaxima2D, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))


#!/usr/bin/python
import pyrealsense2 as rs
import sys, getopt
import asyncore
import numpy as np
import pickle
import socket
import struct
from argparse import ArgumentParser

port = 1024
chunk_size = 4096
clipping_distance_in_meters = 2.0
camera_width = 640
camera_height = 480
camera_fps = 6

def getColorDepthTimestamp(pipeline, color_depth_filter, align, depth_sensor):
    frames = pipeline.wait_for_frames()
    # take owner ship of the frame for further processing
    #frames.keep()
    aligned_frames = align.process(frames)
    color = aligned_frames.get_color_frame()
    depth = aligned_frames.get_depth_frame()

    depth_scale = depth_sensor.get_depth_scale()
    clipping_distance = clipping_distance_in_meters / depth_scale

    if color and depth:
        # represent the frame as a numpy array
        colorData = color.get_data()
        depthData = depth.get_data()
        colorMat = np.asanyarray(colorData)
        depthMat = np.asanyarray(depthData)
        depthMat = np.where((depthMat > clipping_distance) | (depthMat <= 0), 0, depthMat)
        ts = frames.get_timestamp()

        return colorMat, depthMat, ts
    else:
        return None, None, None

def openPipeline():
    cfg = rs.config()
    cfg.enable_stream(rs.stream.depth, camera_width, camera_height, rs.format.z16, camera_fps)
    cfg.enable_stream(rs.stream.color, camera_width, camera_height, rs.format.bgr8, camera_fps)
    pipeline = rs.pipeline()
    pipeline_profile = pipeline.start(cfg)
    align = rs.align(rs.stream.color)
    sensor = pipeline_profile.get_device().first_depth_sensor()
    intr = pipeline_profile.get_stream(rs.stream.color).as_video_stream_profile().get_intrinsics()

    return pipeline, align, intr, sensor

class DevNullHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        print(self.recv(1024))

    def handle_close(self):
        self.close()

class EtherSenseServer(asyncore.dispatcher):
    def __init__(self, address):
        asyncore.dispatcher.__init__(self)
        print("Launching Realsense Camera Server")
        try:
            self.pipeline, self.align, intr, self.depth_sensor = openPipeline()
            self.intr = np.asanyarray([intr.width, intr.height, intr.fx, intr.fy, intr.ppx, intr.ppy])
        except:
            print("Unexpected error: ", sys.exc_info()[1])
            sys.exit(1)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        print('sending acknowledgement to', address)

        # reduce the resolution of the depth image using post processing
        self.decimate_filter = rs.decimation_filter()
        self.decimate_filter.set_option(rs.option.filter_magnitude, 2)
        self.frame_data = ''
        self.connect((address[0], 1024))
        self.packet_id = 0

    def handle_connect(self):
        print("connection received")

    def writable(self):
        return True

    def update_frame(self):
        color, depth, timestamp = getColorDepthTimestamp(self.pipeline, self.decimate_filter, self.align, self.depth_sensor)
        if (color is not None) and (depth is not None):
            # convert the depth image to a string for broadcast
            data = pickle.dumps([color, depth, self.intr])
            #print(color,depth)
            # capture the lenght of the data portion of the message
            length = struct.pack('<I', len(data))
            # include the current timestamp for the frame
            ts = struct.pack('<d', timestamp)
            # for the message for transmission
            self.frame_data = length + ts + data

    def handle_write(self):
        # first time the handle_write is called
        if not hasattr(self, 'frame_data'):
            self.update_frame()
        # the frame has been sent in it entirety so get the latest frame
        if len(self.frame_data) == 0:
            self.update_frame()
        else:
            # send the remainder of the frame_data until there is no data remaining for transmition
            remaining_size = self.send(self.frame_data)
            self.frame_data = self.frame_data[remaining_size:]

    def handle_close(self):
        self.close()

class MulticastServer(asyncore.dispatcher):
    def __init__(self, port=1024):
        asyncore.dispatcher.__init__(self)
        server_address = ('', port)
        self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.bind(server_address)

    def handle_read(self):
        data, addr = self.socket.recvfrom(42)
        print('Recived Multicast message %s bytes from %s' % (data, addr))
        # Once the server recives the multicast signal, open the frame server
        EtherSenseServer(addr)
        print(sys.stderr, data)

    def writable(self):
        return False # don't want write notifies

    def handle_close(self):
        self.close()

    def handle_accept(self):
        channel, addr = self.accept()
        print('received %s bytes from %s' % (data, addr))

def get_option():
    argparser = ArgumentParser()
    argparser.add_argument('--port', type=int, default=1024, help="input port number")
    argparser.add_argument('--chunk_size', type=int, default=4096, help="input chunk size")
    argparser.add_argument('--width', type=int, default=640, help="input camera width")
    argparser.add_argument('--height', type=int, default=480, help="input camera height")
    argparser.add_argument('--fps', type=int, default=6, help="input camera fps")
    argparser.add_argument('--distance', type=float, default=2.0, help="input clipping distance in meters")
    argparser.add_argument('--log', type=bool, default=False, help="show log")

    return argparser.parse_args()

def main():
    # initalise the multicast receiver
    server = MulticastServer(port)
    # hand over excicution flow to asyncore
    asyncore.loop()

if __name__ == '__main__':
    print("running server")
    args = get_option()
    port = args.port
    chunk_size = args.chunk_size
    camera_width = args.width
    camera_height = args.height
    camera_fps = args.fps
    clipping_distance_in_meters = args.distance
    if args.log:
        rs.log_to_console(rs.log_severity.debug)

    main()


from __future__ import print_function, absolute_import, unicode_literals
import sys

def print_enc(msg, out=None, linefeed_and_flush=True):
    if out is None:
        out = sys.stdout

    if hasattr(out, 'buffer'):
        bytes_out = out.buffer
    else:
        bytes_out = out

    if hasattr(out, 'encoding'):
        enc = out.encoding or 'UTF-8'
    else:
        enc = 'UTF-8'

    bytes_out.write(bytes(msg.encode(enc, 'ignore')))
    if linefeed_and_flush:
        bytes_out.write(b'\n')
        bytes_out.flush()

def sane_filename(name, excludechars):
    tr = dict((ord(c), ord('_')) for c in excludechars)
    x = name.strip(' .').translate(tr)
    return x or 'ylevideo'


import re
import os

def replace_prototypes(aadl_file, location=''):
    find_proto = re.compile(
        '(\w+):\s+thread\s+(?:(\w+)::)?(\w+)\.(\w+)\s+\(((?:\w+\s+=>\s+(?:data|subprogram)\s+(?:\w+::)?\w+(?:\s*?,\s*?)?)+)\);')
    get_proto = re.compile('(\w+)\s+=>\s+(data|subprogram)\s+(?:(\w+)::)?(\w+)')

    (filename, ext) = os.path.splitext(aadl_file)

    aadl_file_mod = os.path.join(location, filename + '_mod' + ext)

    out_file = open(aadl_file_mod, 'w')
    pkgs = {}
    tree = {}

    with open(os.path.join(location, aadl_file), 'r') as in_file:
        text = in_file.read()
        for match in find_proto.finditer(text):
            if match.group(2) not in pkgs:
                pkgs[match.group(2)] = []

            protos = match.group(5).split(',')
            proto_list = []
            type_list = []
            name_list = []
            for p in protos:
                m = re.search(get_proto, p)
                proto_list.append(m.group(1))
                type_list.append(m.group(3) + '::' + m.group(4))
                name_list.append(m.group(3) + '_' + m.group(4))
                if m.group(3) not in pkgs[match.group(2)]:
                    pkgs[match.group(2)].append(m.group(3))

            if match.group(2) not in tree:
                tree[match.group(2)] = {match.group(3): [match.group(4), [proto_list, type_list, name_list, []]]}
            else:
                if match.group(3) not in tree[match.group(2)]:
                    tree[match.group(2)][match.group(3)] = [match.group(4), [proto_list, type_list, name_list, []]]
                else:
                    if [proto_list, type_list, name_list, []] not in tree[match.group(2)][match.group(3)]:
                        tree[match.group(2)][match.group(3)].append([proto_list, type_list, name_list, []])

            text = re.sub(
                re.compile('(' + match.group(3) + ')\.(' + match.group(4) + ')\s+\(' + match.group(5) + '\);'),
                match.group(3) + '_' + '_'.join(name_list) + '.' + match.group(4) + ';', text)

        out_file.write(text)

    in_file.close()
    out_file.close()

    find_with = re.compile('with\s+((?:\w+(?:\s*,\s*?)?)+);')
    find_thread = re.compile('thread\s+(?P<type>\w+)\s+prototypes[\s\S]+end\s+(?P=type);')
    match_proto = re.compile('(\w+):\s+((?:in\s+event|out)\s+data\s+port|provides\s+subprogram\s+access)\s+(\w+)\s*;')

    for l0 in tree:

        in_pkg_file_path = os.path.join(location, l0 + '.aadl')
        out_pkg_file_path = os.path.join(location, l0 + '_mod.aadl')

        out_pkg_file = open(out_pkg_file_path, 'w')

        with open(in_pkg_file_path, 'r') as in_pkg_file:
            text = in_pkg_file.read()
            match = re.search(find_with, text)
            if match:
                ex_pkgs = match.group(1).split(',')
                for e in ex_pkgs:
                    if e not in pkgs[l0]:
                        pkgs[l0].append(e)
            with_line = 'with ' + ', '.join(pkgs[l0]) + ';\n\n'
            text = re.sub(re.compile('public(?:\s+with\s+((?:\w+(?:\s*,\s*?)?)+);)?'), 'public\n\t' + with_line, text)

            for thread_match in find_thread.finditer(text):
                for proto_match in match_proto.finditer(thread_match.group(0)):
                    if thread_match.group('type') in tree[l0]:
                        for l in tree[l0][thread_match.group('type')][1:]:
                            l[0] = [proto_match.group(1) if x == proto_match.group(3) else x for x in l[0]]
                            l[3].append(proto_match.group(2))
                thread_block = re.sub(re.compile('provides\s+subprogram\s+access\s+\w+\s*;'),
                                      'provides subprogram access;', thread_match.group(0))
                text = re.sub(thread_match.group(0), thread_block, text)

            text = re.sub(re.compile('end ' + l0 + ';'), '', text)

            out_pkg_file.write(text)

        out_pkg_file.write('\n\n')
        for t in tree[l0]:
            for e in tree[l0][t][1:]:
                new_name = t
                for n in e[2]:
                    new_name = new_name + '_' + n
                out_pkg_file.write('\tthread ' + new_name + ' extends ' + t + '\n')
                out_pkg_file.write('\t\tfeatures\n')
                for p, tp, po in zip(e[0], e[1], e[3]):
                    out_pkg_file.write('\t\t\t' + p + ': refined to ' + po + ' ' + tp + ';\n')
                out_pkg_file.write('\tend ' + new_name + ';\n\n')

                impl = '.' + tree[l0][t][0]
                out_pkg_file.write('\tthread implementation ' + new_name + impl + ' extends ' + t + impl + '\n')
                out_pkg_file.write('\tend ' + new_name + impl + ';\n\n')
        out_pkg_file.write('end ' + l0 + ';')

        in_pkg_file.close()
        out_pkg_file.close()


m,n = map(int, input().split(' '))
works=[]
for i in range(m):
    works.append(list(map(int, input().split(' '))))
people=list(map(int, input().split(' ')))
def printM(works,a):
    mmax=0
    for i in works:
        if i[0]<=a:
            mmax=max(mmax,i[1])
    print(mmax)
for j in people:
    printM(works,j)
# 3 3
# 1 100
# 10 1000
# 1000000000 1001
# 9 10 1000000000
import sys
def main():
    lines = sys.stdin.readlines()
    lines = [l.strip().split() for l in lines if l.strip()]
    n, m = int(lines[0][0]), int(lines[0][1])
    res = [0] * (n + m)
    abilities = list(map(int, lines[-1]))
    maps = dict()
    for index, l in enumerate(lines[1:-1]):
        d, s = int(l[0]), int(l[1])
        maps[d] = s
        res[index] = d
    for index, ability in enumerate(abilities):
        res[index + n] = ability
        if ability not in maps:
            maps[ability] = 0
    res.sort()
    maxSalary = 0
    for index in range(n + m):
        maxSalary = max(maxSalary, maps[res[index]])
        maps[res[index]] = maxSalary
    for index in range(m):
        print(maps[abilities[index]])
if __name__ == '__main__':
    main()

算法题/牛牛找工作.py


import matplotlib.pyplot as plt

tigers = [529, 190, 28, 88]
elephants = [6049, 5706, 1976, 194]
states = ['Karnataka', 'Kerala',
          'Odisha', 'West Bengal']

plt.bar(states, tigers, label='tigers')
plt.bar(states, elephants, label='elephants',
        bottom=tigers)

plt.xlabel('State')
plt.ylabel('Population')
plt.title('Wildlife Population in 2019')
plt.legend()

plt.savefig('out.png', dpi=300,
            bbox_inches='tight')


import os
import argparse
import gzip
import sys

def check_file(targetFile):
    if not os.path.isfile(targetFile):
        raise argparse.ArgumentTypeError(targetFile+' is not a file')
    if os.access(targetFile, os.R_OK):
        return targetFile
    else:
        raise argparse.ArgumentTypeError(targetFile+' is not readable')

def writeFastqRead(readFile,read):
    out="@%s\n%s\n+%s\n%s\n" %(read[0],read[1],read[0],read[2])
    #out=out.encode('utf-8')
    readFile.write(out)

def closeFiles(openFiles):
    for openFile in openFiles:
        openFile.close()

def openNormalOrGz(gzFile,mode='r'):
    if not any([True for ii in mode if ii=='t']):mode+="t"
    try:
        if gzFile[-2:]=='gz' or gzFile[-4]=='gzip':
            fastq=gzip.open(gzFile, mode)
        else:
            fastq=open(gzFile,mode)
    except IOError:
        sys.stderr.write("Problem opening file:"+gzFile+"\n")
        raise
    return fastq


import odoo

from odoo.addons.point_of_sale.tests.common import TestPointOfSaleCommon
from odoo import fields
from odoo.tests.common import Form

@odoo.tests.tagged('post_install', '-at_install')
class TestPosMrp(TestPointOfSaleCommon):
    def test_bom_kit_order_total_cost(self):
        #create a product category that use fifo
        category = self.env['product.category'].create({
            'name': 'Category for kit',
            'property_cost_method': 'fifo',
        })

        self.kit = self.env['product.product'].create({
            'name': 'Kit Product',
            'available_in_pos': True,
            'type': 'product',
            'lst_price': 10.0,
            'categ_id': category.id,
        })

        self.component_a = self.env['product.product'].create({
            'name': 'Comp A',
            'type': 'product',
            'available_in_pos': True,
            'lst_price': 10.0,
            'standard_price': 5.0,
        })

        self.component_b = self.env['product.product'].create({
            'name': 'Comp B',
            'type': 'product',
            'available_in_pos': True,
            'lst_price': 10.0,
            'standard_price': 10.0,
        })

        bom_product_form = Form(self.env['mrp.bom'])
        bom_product_form.product_id = self.kit
        bom_product_form.product_tmpl_id = self.kit.product_tmpl_id
        bom_product_form.product_qty = 1.0
        bom_product_form.type = 'phantom'
        with bom_product_form.bom_line_ids.new() as bom_line:
            bom_line.product_id = self.component_a
            bom_line.product_qty = 1.0
        with bom_product_form.bom_line_ids.new() as bom_line:
            bom_line.product_id = self.component_b
            bom_line.product_qty = 1.0
        self.bom_a = bom_product_form.save()

        self.pos_config.open_ui()
        order = self.env['pos.order'].create({
            'session_id': self.pos_config.current_session_id.id,
            'lines': [(0, 0, {
                'name': self.kit.name,
                'product_id': self.kit.id,
                'price_unit': self.kit.lst_price,
                'qty': 1,
                'tax_ids': [[6, False, []]],
                'price_subtotal': self.kit.lst_price,
                'price_subtotal_incl': self.kit.lst_price,
            })],
            'pricelist_id': self.pos_config.pricelist_id.id,
            'amount_paid': self.kit.lst_price,
            'amount_total': self.kit.lst_price,
            'amount_tax': 0.0,
            'amount_return': 0.0,
            'to_invoice': False,
            'last_order_preparation_change': '{}'
        })
        payment_context = {"active_ids": order.ids, "active_id": order.id}
        order_payment = self.PosMakePayment.with_context(**payment_context).create({
            'amount': order.amount_total,
            'payment_method_id': self.cash_payment_method.id
        })
        order_payment.with_context(**payment_context).check()

        self.pos_config.current_session_id.action_pos_session_closing_control()
        pos_order = self.env['pos.order'].search([], order='id desc', limit=1)
        self.assertEqual(pos_order.lines[0].total_cost, 15.0)

    def test_bom_kit_with_kit_invoice_valuation(self):
        # create a product category that use fifo
        category = self.env['product.category'].create({
            'name': 'Category for kit',
            'property_cost_method': 'fifo',
            'property_valuation': 'real_time',
        })

        self.kit = self.env['product.product'].create({
            'name': 'Final Kit',
            'available_in_pos': True,
            'categ_id': category.id,
            'taxes_id': False,
            'type': 'product',
        })

        self.subkit1 = self.env['product.product'].create({
            'name': 'Subkit 1',
            'available_in_pos': True,
            'categ_id': category.id,
            'taxes_id': False,
        })

        self.subkit2 = self.env['product.product'].create({
            'name': 'Subkit 2',
            'available_in_pos': True,
            'categ_id': category.id,
            'taxes_id': False,
        })

        self.component_a = self.env['product.product'].create({
            'name': 'Comp A',
            'available_in_pos': True,
            'standard_price': 5.0,
            'categ_id': category.id,
            'taxes_id': False,
        })

        self.component_b = self.env['product.product'].create({
            'name': 'Comp B',
            'available_in_pos': True,
            'standard_price': 10.0,
            'categ_id': category.id,
            'taxes_id': False,
        })

        bom_product_form = Form(self.env['mrp.bom'])
        bom_product_form.product_id = self.subkit1
        bom_product_form.product_tmpl_id = self.subkit1.product_tmpl_id
        bom_product_form.product_qty = 1.0
        bom_product_form.type = 'phantom'
        with bom_product_form.bom_line_ids.new() as bom_line:
            bom_line.product_id = self.component_a
            bom_line.product_qty = 1.0
        self.bom_a = bom_product_form.save()

        bom_product_form = Form(self.env['mrp.bom'])
        bom_product_form.product_id = self.subkit2
        bom_product_form.product_tmpl_id = self.subkit2.product_tmpl_id
        bom_product_form.product_qty = 1.0
        bom_product_form.type = 'phantom'
        with bom_product_form.bom_line_ids.new() as bom_line:
            bom_line.product_id = self.component_b
            bom_line.product_qty = 1.0
        self.bom_b = bom_product_form.save()

        bom_product_form = Form(self.env['mrp.bom'])
        bom_product_form.product_id = self.kit
        bom_product_form.product_tmpl_id = self.kit.product_tmpl_id
        bom_product_form.product_qty = 1.0
        bom_product_form.type = 'phantom'
        with bom_product_form.bom_line_ids.new() as bom_line:
            bom_line.product_id = self.subkit1
            bom_line.product_qty = 1.0
        with bom_product_form.bom_line_ids.new() as bom_line:
            bom_line.product_id = self.subkit2
            bom_line.product_qty = 1.0
        self.final_bom = bom_product_form.save()

        self.pos_config.open_ui()
        order_data = {'data':
        {'to_invoice': True,
        'amount_paid': 2.0,
        'amount_return': 0,
        'amount_tax': 0,
        'amount_total': 2.0,
        'creation_date': fields.Datetime.to_string(fields.Datetime.now()),
        'date_order': fields.Datetime.to_string(fields.Datetime.now()),
        'fiscal_position_id': False,
        'pricelist_id': self.pos_config.pricelist_id.id,
        'lines': [[0,
                    0,
                    {'discount': 0,
                    'pack_lot_ids': [],
                    'price_unit': 2,
                    'product_id': self.kit.id,
                    'price_subtotal': 2,
                    'price_subtotal_incl': 2,
                    'qty': 1,
                    'tax_ids': [(6, 0, self.kit.taxes_id.ids)]}]],
            'name': 'Order 00042-003-0014',
            'partner_id': self.partner1.id,
            'pos_session_id': self.pos_config.current_session_id.id,
            'sequence_number': 2,
            'statement_ids': [[0,
                                0,
                                {'amount': 2.0,
                                'name': fields.Datetime.now(),
                                'payment_method_id': self.cash_payment_method.id}]],
            'uid': '00042-003-0014',
            'user_id': self.env.uid},
        }
        order = self.env['pos.order'].create_from_ui([order_data])
        order = self.env['pos.order'].browse(order[0]['id'])
        accounts = self.kit.product_tmpl_id.get_product_accounts()
        debit_interim_account = accounts['stock_output']
        credit_expense_account = accounts['expense']
        invoice_accounts = order.account_move.line_ids.mapped('account_id.id')
        self.assertTrue(debit_interim_account.id in invoice_accounts)
        self.assertTrue(credit_expense_account.id in invoice_accounts)
        expense_line = order.account_move.line_ids.filtered(lambda l: l.account_id.id == credit_expense_account.id)
        self.assertEqual(expense_line.credit, 0.0)
        self.assertEqual(expense_line.debit, 15.0)
        interim_line = order.account_move.line_ids.filtered(lambda l: l.account_id.id == debit_interim_account.id)
        self.assertEqual(interim_line.credit, 15.0)
        self.assertEqual(interim_line.debit, 0.0)
        self.pos_config.current_session_id.action_pos_session_closing_control()


import pandas as pd
import numpy as np

def entropy(x):
    if len(x) == 0:  # Handle empty array
        return 0
    values, freq = np.unique(x, return_counts=True)
    prob = freq / len(x)
    return -np.sum(prob * np.log2(prob))

def calculate_bins(x):
    n = len(x)
    if n == 0:  # Handle empty array
        return 1
    iqr_x = np.subtract(*np.percentile(x, [75, 25]))
    iqr_x = 1 if iqr_x == 0 else iqr_x  # Ensure non-zero IQR
    fd_bin_width = 2 * iqr_x / (n**(1/3))  # Freedman-Diaconis rule
    sturges_bins = np.ceil(np.log2(n) + 1)    # Sturges' rule
    bins = np.ceil((x.max() - x.min()) / fd_bin_width) if ((x.max() - x.min()) / fd_bin_width) > 1 else sturges_bins
    return int(bins)

def fs_infogain(df, target):
    df = df.copy()  # Deep copy to avoid side effects

    if target not in df.columns:
        raise ValueError("The target variable is not found in the provided dataframe.")

    date_cols = df.select_dtypes(include=[np.datetime64]).columns
    for col in date_cols:
        df = df.assign(**{
            f"{col}_year": df[col].dt.year,
            f"{col}_month": df[col].dt.month,
            f"{col}_day": df[col].dt.day
        })
    df.drop(columns=date_cols, inplace=True)  # Drop original date columns

    info_gain = []
    column_names = df.columns
    entropy_target = entropy(df[target])
    total_rows = len(df)

    for col in column_names:
        if col != target:
            if np.issubdtype(df[col].dtype, np.number):
                n_bins = calculate_bins(df[col])
                df[col], _ = pd.cut(df[col], bins=n_bins, labels=False, retbins=True, include_lowest=True)

            entropy_attribute = sum(
                len(subset) / total_rows * entropy(subset[target])
                for _, subset in df.groupby(col)
            )
            gain = entropy_target - entropy_attribute
            info_gain.append(gain)

    result = pd.DataFrame({
        "Variable": [col for col in column_names if col != target],
        "InfoGain": info_gain
    })

    return result

def calculate_information_gain_multiple(dfs_list):
    results_list = []
    for i, df in enumerate(dfs_list, 1):
        result = fs_infogain(df, "target")
        result["Origin"] = f"Data_Frame_{i}"
        results_list.append(result)
    all_results = pd.concat(results_list, axis=0, ignore_index=True)
    return all_results


from colorlog import ColoredFormatter
import logging, logging.config

# Section 1: Logging configuration
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('Demo')

# Section 2: Add file handler to save logs to a file
file_handler = logging.FileHandler('output_log.txt')
logger.addHandler(file_handler)

# Section 3: Set custom log format
log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
formatter = logging.Formatter(log_format)
file_handler.setFormatter(formatter)

# Section 3: Logging examples
log_header = "Examples:"
message = "this could be your Ad;"

# Section 4: Logging functions
logger.debug(f"{log_header} {message}")
logger.info(f"{log_header} {message}")
logger.warning(f"{log_header} {message}")
logger.error(f"{log_header} {message}")
logger.critical(f"{log_header} {message}")


from lassonet import LassoNetRegressor, LassoNetClassifier

from sklearn.datasets import load_diabetes, load_digits

def test_regressor():
    X, y = load_diabetes(return_X_y=True)
    model = LassoNetRegressor()
    model.fit(X, y)
    model.score(X, y)

def test_classifier():
    X, y = load_digits(return_X_y=True)
    model = LassoNetClassifier()
    model.fit(X, y)
    model.score(X, y)


from project import Project
from criterias import *

x1 = Project("X1",[[5,10],[2,7],[8,6],[5,9]])
x2 = Project("X2",[[4,4],[5,7],[9,6],[4,4]])
x3 = Project("X3",[[4,8],[1,9],[7,3],[7,5]])
x4 = Project("X4",[[4,1],[6,4],[9,2],[7,2]])
x5 = Project("X5",[[1,3],[3,5],[4,2],[3,3]])
x6 = Project("X6",[[5,4],[2,6],[3,3],[2,4]])
x7 = Project("X7",[[11,5],[2,7],[4,5],[2,3]])
x8 = Project("X8",[[4,3],[3,7],[10,4],[3,8]])

projects = []
projects.extend([x1,x2,x3,x4,x5,x6,x7,x8])

if __name__ == '__main__':
    draw_projects_table(projects)

    print("Решения эффективные по принципу векторного максимина: ",end='')
    maxminOptimal = getVectorMaxminOptimal(projects)
    setOptimal("Векторный максимин",maxminOptimal)
    print(*map(lambda x: x.name, maxminOptimal), sep=",")

    print("Решения эффективные по принципу минимаксного сожаления: ",end='')
    minmaxOptimal = getVectorMinmaxOptimal(projects)
    setOptimal("Векторное минимаксное сожаление",minmaxOptimal)
    print(*map(lambda x: x.name, minmaxOptimal), sep=",")

    optimalByF1 = getOptimalByF("f1",projects)
    print("Лучшие решения по Вальду,Сэвиджу,Гурвицу и Лапласу по f1: ", end='')
    setOptimal("f1 по критериям Вальда,Сэвиджа,Гурвица и Лапласа",optimalByF1)
    print(*map(lambda x: x.name, optimalByF1), sep=",")

    optimalByF2 = getOptimalByF("f2",projects)
    print("Лучшие решения по Вальду,Сэвиджу,Гурвицу и Лапласу по f2: ", end='')
    setOptimal("f2 по критериям Вальда,Сэвиджа,Гурвица и Лапласа",optimalByF2)
    print(*map(lambda x: x.name, optimalByF2), sep=",")

    drawVotingTable(projects)

    print("Лучшие решения : ", end='')
    print(*map(lambda x: x.name, getBest(projects)), sep=",")

    plt.show()


from lclpy.localsearch.abstract_local_search import AbstractLocalSearch
from lclpy.termination.always_true_criterion import AlwaysTrueCriterion

from lclpy.aidfunc.is_improvement_func import bigger, smaller
from lclpy.aidfunc.pass_func import pass_func
from lclpy.aidfunc.add_to_data_func import add_to_data_func
from lclpy.aidfunc.convert_data import convert_data
from lclpy.aidfunc.logging import log_improvement

from collections import namedtuple

class SteepestDescent(AbstractLocalSearch):
    """Performs a steepest descent algorithm on the given problem.

    Parameters
    ----------
    problem : AbstractLocalSearchProblem
        Contains all the data needed for the specific problem.
    minimise : bool, optional
        If the goal is to minimise the evaluation function, this should be
        True. If the goal is to maximise the evaluation function, this should
        be False. The default is True.
    termination_criterion : AbstractTerminationCriterion, optional
        The termination criterion that is used.
    benchmarking : bool, optional
        Should be True if one wishes benchmarks to be kept, should be False if
        one wishes no benchmarks to be made. Default is False.
    logging: bool, optional
        Improvements will be logged to the command line if this variable is
        True. Default is True.

    Attributes
    ----------
    _problem : AbstractLocalSearchProblem
        Contains all the data needed for the specific problem.
    _termination_criterion : AbstractTerminationCriterion
        Ends the algorithm if no more improvements can be found.
    _function
        The function used to determine if a delta value is better than another
        delta value.
    _best_found_delta_base_value : float
        Initialisation value for the delta value of each iteration. It's
        infinite when minimising or minus infinite when maximising.
    data : list of tuple
        Data useable for benchmarking will be None if no benchmarks are made.
    _data_append
        Function to append new data-points to data. Will do nothing if no
        benchmarks are made.
    _log_improvement
        Function to write logs to the command line. Will do nothing if no logs
        are made.

    Examples
    --------
    An example of minimising:

    .. doctest::

        >>> import numpy
        >>> from lclpy.localsearch.steepestdescent.steepest_descent \\
        ...     import SteepestDescent
        >>> from lclpy.localsearch.move.tsp_array_swap import TspArraySwap
        >>> from lclpy.evaluation.tsp_evaluation_function \\
        ...     import TspEvaluationFunction
        >>> from lclpy.problem.array_problem import ArrayProblem
        ... # init problem
        >>> distance_matrix = numpy.array(
        ... [[0, 2, 5, 8],
        ...  [2, 0, 4, 1],
        ...  [5, 4, 0, 7],
        ...  [8, 1, 7, 0]])
        >>> size = distance_matrix.shape[0]
        >>> move = TspArraySwap(size)
        >>> evaluation = TspEvaluationFunction(distance_matrix, move)
        >>> problem = ArrayProblem(evaluation, move, size)
        ... # init SteepestDescent
        >>> steepest_descent = SteepestDescent(problem, logging=False)
        ... # run algorithm
        >>> steepest_descent.run()
        Results(best_order=array([0, 1, 3, 2]), best_value=15, data=None)

    An example of maximising, note that the distance matrix is different:

    .. doctest::

        >>> import numpy
        >>> from lclpy.localsearch.steepestdescent.steepest_descent \\
        ...     import SteepestDescent
        >>> from lclpy.localsearch.move.tsp_array_swap import TspArraySwap
        >>> from lclpy.evaluation.tsp_evaluation_function \\
        ...     import TspEvaluationFunction
        >>> from lclpy.problem.array_problem import ArrayProblem
        ... # init problem
        >>> distance_matrix = numpy.array(
        ... [[0, 8, 5, 2],
        ...  [8, 0, 4, 7],
        ...  [5, 4, 0, 1],
        ...  [2, 7, 1, 0]])
        >>> size = distance_matrix.shape[0]
        >>> move = TspArraySwap(size)
        >>> evaluation = TspEvaluationFunction(distance_matrix, move)
        >>> problem = ArrayProblem(evaluation, move, size)
        ... # init SteepestDescent
        >>> steepest_descent = SteepestDescent(problem, False, logging=False)
        ... # run algorithm
        >>> steepest_descent.run()
        Results(best_order=array([0, 1, 3, 2]), best_value=21, data=None)

    """

    def __init__(self, problem, minimise=True, termination_criterion=None,
                 benchmarking=False, logging=True):
        super().__init__()

        self._problem = problem

        if termination_criterion is None:
            self._termination_criterion = AlwaysTrueCriterion()
        else:
            self._termination_criterion = termination_criterion

        if minimise:
            self._function = smaller
            self._best_found_delta_base_value = float("inf")
        else:
            self._function = bigger
            self._best_found_delta_base_value = float("-inf")

        if benchmarking:
            self.data = []
            self._data_append = add_to_data_func
        else:
            self.data = None
            self._data_append = pass_func

        if logging:
            self._log_improvement = log_improvement
        else:
            self._log_improvement = pass_func

    def run(self):
        """Starts running the steepest descent.

        Returns
        -------
        best_order : numpy.ndarray
            The best found order.
        best_value : int or float
            The evaluation value of the best found order.
        data : None or collections.namedtuple
            Data useable for benchmarking. If no benchmarks were made, it will
            be None. The namedtuple contains the following data in
            numpy.ndarrays:
            time, iteration, value

        """

        # init problem
        base_value = self._problem.evaluate()
        self._problem.set_as_best(base_value)

        # init iteration (used to vount the amount of iterations)
        iteration = 0

        # add to data
        self._data_append(self.data, iteration, base_value)

        # init termination criterion
        self._termination_criterion.check_first_value(base_value)
        self._termination_criterion.start_timing()

        while self._termination_criterion.keep_running():

            # search the neighbourhood for the best move
            best_found_delta = self._best_found_delta_base_value
            best_found_move = None

            for move in self._problem.get_moves():

                # check quality move
                delta = self._problem.evaluate_move(move)

                # keep data best move
                if self._function(best_found_delta, delta):
                    best_found_delta = delta
                    best_found_move = move

            # check if the best_found_move improves the delta, if this is the
            # case perform the move and set a new best problem
            base_value = base_value + best_found_delta

            self._termination_criterion.check_new_value(base_value)

            if self._function(self._problem.best_order_value, base_value):
                # if the found value is better

                # perform move and set new state as best.
                self._problem.move(best_found_move)
                self._problem.set_as_best(base_value)

                # log if needed
                self._log_improvement(base_value)

                # add to data
                self._data_append(self.data, iteration, base_value)

            else:

                # if it's worse: stop iterating by breaking from the loop
                break

            iteration += 1
            self._termination_criterion.iteration_done()

        # last data point
        self._data_append(self.data, iteration, base_value)

        # if we have data:
        # convert data to something easier to plot
        if self.data is not None:

            # convert to tuple of list
            data = convert_data(self.data)

            # make namedtuple
            DataAsLists = namedtuple('Data', ['time', 'iteration', 'value'])

            data = DataAsLists(data[0], data[1], data[2])

        else:
            data = None

        # return results

        Results = namedtuple('Results', ['best_order', 'best_value', 'data'])

        return Results(self._problem.best_order,
                       self._problem.best_order_value,
                       data)

    def reset(self):
        """Resets the object back to it's state after init.

        Raises
        ------
        NotImplementedError
            If the problem or termination criterion have no reset method
            implemented.

        Examples
        --------
        An example of minimising, reset after run:

        .. doctest::

            >>> import numpy
            >>> from lclpy.localsearch.steepestdescent.steepest_descent \\
            ...     import SteepestDescent
            >>> from lclpy.localsearch.move.tsp_array_swap \\
            ...     import TspArraySwap
            >>> from lclpy.evaluation.tsp_evaluation_function \\
            ...     import TspEvaluationFunction
            >>> from lclpy.problem.array_problem import ArrayProblem
            ... # init problem
            >>> distance_matrix = numpy.array(
            ... [[0, 2, 5, 8],
            ...  [2, 0, 4, 1],
            ...  [5, 4, 0, 7],
            ...  [8, 1, 7, 0]])
            >>> size = distance_matrix.shape[0]
            >>> move = TspArraySwap(size)
            >>> evaluation = TspEvaluationFunction(distance_matrix, move)
            >>> problem = ArrayProblem(evaluation, move, size)
            ... # init SteepestDescent
            >>> steepest_descent = SteepestDescent(problem, logging=False)
            ... # state before running
            >>> steepest_descent._problem._order
            array([0, 1, 2, 3])
            >>> steepest_descent._termination_criterion.keep_running()
            True
            >>> # run algorithm
            >>> steepest_descent.run()
            Results(best_order=array([0, 1, 3, 2]), best_value=15, data=None)
            >>> # tests reset
            >>> # before reset
            >>> steepest_descent._problem._order
            array([0, 1, 3, 2])
            >>> steepest_descent._termination_criterion.keep_running()
            True
            >>> # reset
            >>> steepest_descent.reset()
            ... # after reset
            >>> steepest_descent._problem._order
            array([0, 1, 2, 3])
            >>> steepest_descent._termination_criterion.keep_running()
            True

        """

        self._problem.reset()
        self._termination_criterion.reset()

        if self.data is not None:
            self.data = []


import os,sys
import openai

sys.path.append("C:/Users/srini/git/Nxtcode/IT AUTOMATION/.vscode/OpenAIProject")

import constants
openai.api_key = constants.OPENAI_API_KEY

print("Program to convert movie name to emoji\n")
gpt_prompt = input('Enter tthe movie name :  ')

response = openai.Completion.create(
  model="text-davinci-003",
  prompt= gpt_prompt,
  temperature=0.8,
  max_tokens=60,
  top_p=1.0,
  frequency_penalty=0.0,
  presence_penalty=0.0,
  stop=["\\n"]
)
#print(response['choices'][0]['text'])
print(response)


from keras.applications.inception_v3 import InceptionV3, preprocess_input
from keras.layers import Dense, GlobalAveragePooling2D, Activation
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
import argparse

parser = argparse.ArgumentParser(description='parser to get the value of num_class')
parser.add_argument("--num_class", default = 100, help = 'can be either 50 or 100')
parser.add_argument("--epochs", default = 2, help = 'can be either 50 or 100')
args = parser.parse_args()

num_class = args.num_class
train_path = 'Datasets/train{}/'.format(num_class)
val_path = 'Datasets/val{}/'.format(num_class)

bs = 10
sz = 299

train_datagen = ImageDataGenerator(preprocessing_function = preprocess_input,
                                 rotation_range=10,
                                 width_shift_range=0.1,
                                 height_shift_range=0.1,
                                 shear_range=0.1,
                                 zoom_range=0.1,
                                 horizontal_flip=True)
train_gen = train_datagen.flow_from_directory(train_path,
                                              target_size=(sz,sz),
                                              class_mode='categorical',
                                              shuffle=True,
                                              batch_size=bs)

valid_datagen = ImageDataGenerator(preprocessing_function = preprocess_input)
valid_gen = valid_datagen.flow_from_directory(val_path,
                                              target_size=(sz,sz),
                                              class_mode='categorical',
                                              shuffle=False,
                                              batch_size=bs)

net = InceptionV3(weights = 'imagenet', include_top = False, input_shape = (sz,sz,3))
model = create_net(None, num_class)

model.compile(optimizer=Adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(train_gen,
	                 steps_per_epoch = train_gen.n//train_gen.batch_size,
	                 epochs=args.epochs,
	                 validation_data=valid_gen,
	                 validation_steps = valid_gen.n//valid_gen.batch_size)

model.save('model/reduced_weights{}.h5'.format(num_class))


# -*- coding: UTF-8 -*-
import os
import subprocess
import time
import pytest

def execute_command(cmd_string, cwd=None, shell=True):
    sub = subprocess.Popen(cmd_string, cwd=cwd, stdin=subprocess.PIPE,stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE, shell=shell, bufsize=4096)

    stdout_str = ''
    while sub.poll() is None:
        err= sub.stderr.read()
        stdout_str += str(sub.stdout.read(), encoding="UTF-8")
        if len(err)>0:
            raise Exception(err)
        time.sleep(0.1)

    return stdout_str

def exec_test_case(dir):
    print("=================> Project build start.")
    begin_time = time.time()
    script=os.path.join(dir,"sdk_test_case.py")
    report=os.path.join(dir,"report.html")
    pytest.main([script, '--html='+report, '--self-contained-html'])
    execute_command("rm -rf /rt-thread/eclipse/workspace")
    print("=================> Project build end, time consuming : {0}.".format(time.time() - begin_time))

def get_build_result(cmd_pre, project_name):

    project_path = os.path.join("/rt-thread/workspace", project_name)
    if not os.path.exists(project_path):
        print("Error : {0} not exit.".format(project_path))
        return False

    cmd = cmd_pre + " -cleanBuild all 1>build.log 2>/dev/null"
    execute_command(cmd)
    build_result = judge_build_result()

    project_path = os.path.join("/rt-thread/workspace", project_name)
    execute_command("rm -rf {0}".format(project_path))

    return build_result

def build_test(project_name):

    cmd_pre = r"/rt-thread/eclipse/eclipse -nosplash --launcher.suppressErrors "\
              r"-application org.eclipse.cdt.managedbuilder.core.headlessbuild " \
              r"-data '/rt-thread/eclipse/workspace'"
    return get_build_result(cmd_pre, project_name)

def judge_build_result():
    try:
        with open("build.log",'r') as f:
            log_info = f.readlines()
    except Exception as e:
        print("Error message : {0}".format(e))
        return False

    build_result = False
    for line in log_info:
        if (line.find('error') != -1) or (line.find("Error") != -1):
            print(line)
        if (line.find("region `ROM' overflowed") != -1) or (line.find("region `RAM' overflowed") != -1):
            print(line)
        if line.find("Finished building target: rtthread.elf") != -1:
            build_result = True
            break
    execute_command("rm -rf build.log")
    return build_result

# if __name__ == "__main__":
#     exec_test_case()


def score(nums):
    a = nums[0]
    b = nums[1]
    c = nums[2]
    return(a**2 + b**2 + c**2 + 7 * min(a,b,c))

n = int(input())

for i in range(n):
    a, b, c, d = list(map(int, input().split()))
    nums = [a,b,c]
    for i in range(d):

        nums = sorted(nums)
        hinums = nums[:]
        lonums = nums[:]

        lonums[0] += 1
        hinums[2] += 1

        if score(hinums) - score(nums) > score(lonums) - score(nums):
            nums[2] += d-i
            break
        else:
            nums[0] += 1

    print(score(nums))


import timeit

def normalConca():
    temp = ''
    for char in range(1000):
        temp += str(char)
    return temp

def joinConca():
    temp = ''
    for char in range(1000):
        temp.join(str(char))
    return temp

def joinConca2():

    temp = ''.join(map(str ,range(1000)))
    return temp

def listToString():

    l = []
    for i in range(1000):
        l.append(i)

    return ''.join(map(str,l))

def timefunct(name):
    SETUP_CODE = f'''from __main__ import {name}'''

    TEST_CODE = f'''{name}()'''

    # timeit.repeat statement
    times = timeit.repeat(setup = SETUP_CODE,
                          stmt = TEST_CODE,
                          repeat = 3,
                          number = 10000)
    return times

if __name__ == '__main__':
    #
    # times = timefunct('normalConca')
    # print(f'Normal Concatenation time:  {min(times)}')
    #
    # times = timefunct('joinConca')
    # print(f'joinConca Concatenation time:  {min(times)}')
    #
    # times = timefunct('joinConca2')
    # print(f'joinConca2 Concatenation time:  {min(times)}')

    times = timefunct('listToString')
    print(f'listToString Concatenation time:  {min(times)}')

    '''
    Normal Concatenation time:  3.4618344999999997
    joinConca Concatenation time:  4.332490100000001
    joinConca2 Concatenation time:  1.9204395999999981
    listToString Concatenation time:  2.5347735

    '''


from django.shortcuts import get_object_or_404
from course.models import CourseConfig
from Users.models import StudentInCourse, TeacherInCourse
from django.contrib.auth.models import User
from course.models import AssignedTest
from userAnswer.models import UserWhoСompletedTest
from tests.models import TestsConfig

def check_teacher(email):
    if len(TeacherInCourse.objects.filter(e_mail=email)) == 0:
        return False
    return True

def get_test_by_slug(slug):
    return get_object_or_404(TestsConfig, slug=slug)

def get_test_by_kwargs(**kwargs):
    return TestsConfig.objects.filter(**kwargs)

def get_students_by_course(course):
    return StudentInCourse.objects.filter(course=course)

def get_course_by_slug(course_slug):
    return get_object_or_404(CourseConfig, course_slug=course_slug)

def get_assign_test(course):
    return AssignedTest.objects.filter(course=course)

def get_user_by_email(email):
    return get_object_or_404(User, email=email)

def get_student_in_course(student_email, course):
    return StudentInCourse.objects.get(e_mail=student_email, course=course)

def percent_part(total_num, chosen_part):
    if total_num == 0:
        return ':('
    return (chosen_part * 100) / total_num

''' student statistic methods '''

def num_student_in_course(course_slug):
    STUDENT_NUM = 0
    try:
        this_course = get_course_by_slug(course_slug)
        students = get_students_by_course(this_course)
    except Exception:
        return ':('
    for i in students:
        STUDENT_NUM += 1

    return STUDENT_NUM

def get_student_average_in_course(course_slug, student_email):
    TOTAL_MARK = 0
    STUDENT_MARK_NUMBER = 0

    try:
        this_course = get_course_by_slug(course_slug)
        tests = get_assign_test(this_course)
        student = get_user_by_email(student_email)
    except Exception:
        return ':('

    assign_tests = []

    for assign_ob in tests:
        assign_tests.append(assign_ob.test)

    for test in assign_tests:
        try:
            testing_result_obj = UserWhoСompletedTest.objects.get(
                test=test, course=this_course, user=student)
        except Exception:
            continue
        TOTAL_MARK += testing_result_obj.user_point
        STUDENT_MARK_NUMBER += 1

    try:
        AVERAGE = round(TOTAL_MARK / STUDENT_MARK_NUMBER, 2)
    except ZeroDivisionError:
        return ':('

    return AVERAGE

def average_mark_in_course(course_slug):
    TOTAL_MARK = 0
    MARK_NUMBER = 0
    try:
        this_course = get_course_by_slug(course_slug)
        completed_tests = UserWhoСompletedTest.objects.filter(
            course=this_course)
    except Exception:
        return ':('

    for complete_test in completed_tests:
        if not check_teacher(complete_test.user.email):
            TOTAL_MARK += complete_test.user_point
            MARK_NUMBER += 1
        else:
            continue

    try:
        AVERAGE = round(TOTAL_MARK / MARK_NUMBER, 2)
    except ZeroDivisionError:
        return ':('

    return AVERAGE

def student_position_in_course(course_slug, student_email):
    try:
        this_course = get_course_by_slug(course_slug)
        student = get_user_by_email(student_email)
        student_in_course = get_student_in_course(student_email, this_course)
        all_students = get_students_by_course(this_course)
        student_num = num_student_in_course(course_slug)

    except Exception:
        return ':('

    students = {}

    for student in all_students:
        tmp_average = get_student_average_in_course(course_slug,
                                                    student.e_mail)
        students[student.e_mail] = tmp_average

    if students[student_email] == ':(':
        return students[student_email]

    left_limit = students[student_email] - 3
    right_limit = students[student_email] + 3

    Count_User_In_Limits = 0

    for e, ob in students.items():
        if ob == ':(':
            continue
        elif ob >= left_limit and ob <= right_limit and e != student_email:
            Count_User_In_Limits += 1

    this_user_percent = percent_part(student_num, Count_User_In_Limits)
    if this_user_percent == ':(' or this_user_percent == 0:
        return ':('
    return f'{int(round((this_user_percent),1))}% учнів мають аналогічні результати!'

'''teacher statistic '''

def get_average_mark_on_this_test_on_chossen_course(course_slug, test_slug):
    TOTAL_MARK = 0
    MARK_NUMBER = 0
    try:
        this_course = get_course_by_slug(course_slug)
        this_test = get_test_by_slug(slug=test_slug)
        this_test_results = UserWhoСompletedTest.objects.filter(
            course=this_course, test=this_test)

        for result in this_test_results:
            if not check_teacher(result.user.email):
                TOTAL_MARK += result.user_point
                MARK_NUMBER += 1

        return round(TOTAL_MARK / MARK_NUMBER, 2)

    except Exception:
        return ':('


#!/usr/bin/env python

import argparse
import os

import matplotlib.pyplot as pp
import pandas as pd

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--out", help="Path to output file")
    parser.add_argument("log_dir", help="Tensorflow log directory")
    args = parser.parse_args()

    out_path = args.out
    log_dir = args.log_dir

    train_metrics = pd.read_csv(os.path.join(log_dir, "train.csv"))
    val_metrics = pd.read_csv(os.path.join(log_dir, "val.csv"))

    train_metrics.index += 1
    val_metrics.index += 1

    min_val_loss = val_metrics["loss"].argmin()

    fig, ax = pp.subplots(figsize=(3, 3), dpi=200)

    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)

    ax.set_xlabel("Epoch")
    ax.set_ylabel("Loss")

    train_metrics["loss"].plot(ax=ax, label="Training", lw=1)
    val_metrics["loss"].plot(ax=ax, label="Validation", lw=1)

    ax.axvline(min_val_loss, alpha=0.5, lw=1, ls="--", label="Minimum", c="C1")

    ax.legend(loc="upper right", fontsize=6, framealpha=0.5)

    if out_path is None:
        pp.show()
    else:
        fig.savefig(out_path, bbox_inches="tight")

if __name__ == "__main__":
    main()


from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import List
from models.UserClimbDiary import UserClimbDiary, UserClimbDiaryModel
from database import get_db

router = APIRouter()

@router.post("/user_climb_diary/", response_model=UserClimbDiaryModel)
def create_user_climb_diary(diary_entry: UserClimbDiaryModel, db: Session = Depends(get_db)):
    db_diary_entry = UserClimbDiary(**diary_entry.dict())
    db.add(db_diary_entry)
    db.commit()
    db.refresh(db_diary_entry)
    return db_diary_entry

# 사용자 ID에 따른 다이어리 리스트를 반환하는 API
@router.get("/user_climb_diary/{user_id}", response_model=List[UserClimbDiaryModel])
def read_user_climb_diary(user_id: str, db: Session = Depends(get_db)):
    diary_entries = db.query(UserClimbDiary).filter(UserClimbDiary.user_id == user_id).all()
    if not diary_entries:
        raise HTTPException(status_code=404, detail="해당 사용자의 다이어리를 찾을 수 없습니다.")
    return diary_entries

@router.put("/user_climb_diary/{climbing_date}", response_model=UserClimbDiaryModel)
def update_user_climb_diary(climbing_date: str, diary_update: UserClimbDiaryModel, db: Session = Depends(get_db)):
    diary_entry = db.query(UserClimbDiary).filter_by(climbing_date=climbing_date).first()
    if diary_entry is None:
        raise HTTPException(status_code=404, detail="해당 날짜의 다이어리를 찾을 수 없습니다.")
    for key, value in diary_update.dict().items():
        setattr(diary_entry, key, value)
    db.commit()
    db.refresh(diary_entry)
    return diary_entry


# Creamos un diccionario vacío donde guardaremos los alumnos y sus notas
alumnos = {}

# Pedimos al usuario que introduzca el número de alumnos que va a registrar
num_alumnos = int(input("Introduce el número de alumnos: "))

# Iteramos por cada alumno
for i in range(num_alumnos):
    # Pedimos al usuario que introduzca el nombre del alumno
    nombre = input(f"Introduce el nombre del alumno {i+1}: ")

    # Creamos una lista vacía para las notas del alumno
    notas = []

    # Pedimos al usuario que introduzca las notas del alumno hasta que introduzca un número negativo
    nota = float(input("Introduce una nota (introduce un número negativo para salir): "))
    while nota >= 0:
        notas.append(nota)
        nota = float(input("Introduce otra nota (introduce un número negativo para salir): "))

    # Comprobamos si el nombre del alumno ya ha sido registrado
    if nombre in alumnos:
        print(f"Error: el alumno {nombre} ya existe")
    else:
        # Guardamos el nombre y las notas del alumno en el diccionario
        alumnos[nombre] = notas

# Mostramos por pantalla el listado de alumnos y sus notas, así como su media
print("\nListado de alumnos y sus notas:")
for nombre, notas in alumnos.items():
    media = sum(notas) / len(notas)
    print(f"{nombre}: {notas}, media = {media}")

Semana 3/Colección de Datos/E4_ColeccionDatos.py


"""empty message

Revision ID: 2a17e1eb4aa9
Revises: 431be9748976
Create Date: 2020-03-28 16:31:34.435850

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '2a17e1eb4aa9'
down_revision = '431be9748976'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('funcionario',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('nome', sa.String(length=50), nullable=False),
    sa.Column('idade', mysql.INTEGER(unsigned=True), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('funcionario')
    # ### end Alembic commands ###


import cv2
import math
import time
from random import *
import numpy as np
from PIL import Image
from array import *

def modulo(a, b, p):
    c = 1
    d = a
    while (b > 0):
        if (b % 2 != 0):
            c = (c*d) % p
        d = (d*d) % p
        if (d > (p/2)):
            d = d-p
        b //= 2
    if (c < 0):
        c = c+p
    return c % p

def revModulo(a, b, p):
    z = modulo(a, b, p)
    t1 = 0
    t2 = 1
    t = 0
    quotient = 0
    remainder = 0
    A = 0
    B = 0
    if (z > p):
        A = z
        B = p
    else:
        A = p
        B = z
    while (B != 0):
        quotient = A//B
        remainder = A % B
        t = t1-(quotient*t2)
        A = B
        B = remainder
        t1 = t2
        t2 = t
    return t1

def concatArr(arr, i, j, size):
    str_con = ""
    for row in range(i, i+size):
        for column in range(j, j+size):
            if int(arr[row][column]/100) !=0:
                num_str = str(arr[row][column])
            elif int(arr[row][column]/100) ==0 and int(arr[row][column]/10) !=0:
                num_str = "0"+str(arr[row][column])
            else:
                num_str = "00"+str(arr[row][column])
            str_con = str_con + num_str
    return int(str_con)

def digits(num):
    count=0
    while(num!=0):
        num //= 10
        count += 1
    return count

if __name__ == "__main__":
    n = cv2.imread("image3.png", 0)
    Row = len(n)
    Column = len(n[0])
    matrix = []
    print("The program starts ")
    print("The size of image is ", Row, "X", Column, " pixels")
    p = 999998999999
    g = 2585
    x = 47
    r = 65
    # defines the size of the block (size*size)
    size=2

    # Dummy
    np.save('dummy.npy', n)
    dummy_matrix = np.load('dummy.npy')
    dum = Image.fromarray(dummy_matrix, "L")
    dum.save('dummy.png')

    # original matrix
    print(n)

    # preparing the original array concatenation
    original_concat=[]
    for row in range(0,Row,size):
        for column in range(0,Column,size):
            original_con=concatArr(n,row,column,size)
            original_concat.append(original_con)
    print(original_concat)

    # Key generation
    t1 = time.time()
    mody = modulo(g, x, p)  # a=2585,b=47
    t2 = time.time()
    time_taken = t2 - t1
    print("The key generation task took", time_taken, "seconds to execute")
    # Public key (p,g,mody)

    # Encryption
    modc11 = []
    modc1 = modulo(g, r, p)
    enc_concat=[]
    enc = n
    t1 = time.time()

    # encrypting the block matrix
    for row in range(len(original_concat)):
        r = randint(1, p-2)
        modc2 = modulo(g, r, p)
        enc_con=modulo((original_concat[row]+1)*modulo(mody, r, p), 1, p)
        if digits(enc_con)==size*size*3:
            enc_concat.append(enc_con)
        else:
            enc_con_str=str(enc_con)
            while(digits(int(enc_con_str))!=size*size*3):
                enc_con_str=str(enc_con)+"0"
            enc_concat.append(int(enc_con_str))
        modc11.append(modc2)
    print(enc_concat)

    t2 = time.time()
    time_taken = t2 - t1
    print("The encryption tasks took", time_taken, "seconds to execute")

    # homomorphic multiplication
    # num = 3
    # Nmodc1 = modulo(g, r, p)
    # print("The value of c1 is :", Nmodc1, "mod", p)
    # Nmodc2 = modulo(num*modulo(mody, r, p), 1, p)
    # print("The value of c2 is :", Nmodc2, "mod", p)
    # # encrpyted value of num is stored in Nmodc2
    # for row in range(Row):
    #     for column in range(Column):
    #         modc11[row][column] = Nmodc1*modc11[row][column]
    #         enc1[row][column] = Nmodc2 * enc1[row][column]

    # matrix2=np.array(matrix)
    # encrypted matrix
    # print(matrix2)

    # np.save('image1_encrypted.npy', enc)
    # encrypted_matrix = np.load('image1_encrypted.npy')
    # encrypted_image = Image.fromarray(encrypted_matrix, "L")
    # encrypted_image.save('encrypted_image.png')

    # Decryption

    # decrypt=[]
    # Row=len(matrix2)
    # Column=len(matrix2[0])
    dec = n
    dec_concat=[]
    t1 = time.time()
    # block decryption
    for row in range(len(original_concat)):
        c3 = revModulo(modc11[row], x, p)
        dec_con=modulo(enc_concat[row] * c3, 1, p)-1
        dec_concat.append(dec_con)
    print(dec_concat)

    t2 = time.time()
    time_taken = t2 - t1
    print("The decryption tasks took", time_taken, "seconds to execute")
    # decrypt2=np.array(n)
    # decrypted matrix
    print(dec)
    np.save('image1_decrypted.npy', dec)
    decrypted_matrix = np.load('image1_decrypted.npy')
    decrypted_image = Image.fromarray(decrypted_matrix, "L")
    decrypted_image.save('decrypted_image.png')


# Test cloud photos

import pytest

import osxphotos

PHOTOS_DB_CLOUD = "./tests/Test-Cloud-10.14.6.photoslibrary/database/photos.db"
PHOTOS_DB_NOT_CLOUD = "./tests/Test-10.14.6.photoslibrary/database/photos.db"

UUID_DICT = {
    "incloud": "jNzHQgSxStK%Ll2aDOLakQ",
    "not_incloud": "h0m8G5PWTKqJwD4p9QGA5w",
    "cloudasset": "iOrNkBNSTxSELZtbSeBr1A",
    "not_cloudasset": "8SOE9s0XQVGsuq4ONohTng",
}

@pytest.fixture(scope="module")
def photosdb():
    return osxphotos.PhotosDB(dbfile=PHOTOS_DB_CLOUD)

def test_incloud(photosdb):
    photos = photosdb.photos(uuid=[UUID_DICT["incloud"]])

    assert photos[0].incloud

def test_not_incloud(photosdb):
    photos = photosdb.photos(uuid=[UUID_DICT["not_incloud"]])

    assert not photos[0].incloud

def test_cloudasset_1(photosdb):
    photos = photosdb.photos(uuid=[UUID_DICT["cloudasset"]])

    assert photos[0].iscloudasset

def test_cloudasset_2(photosdb):
    photos = photosdb.photos(uuid=[UUID_DICT["not_incloud"]])

    # not_incloud is still a cloud asset
    assert photos[0].iscloudasset

def test_cloudasset_3():
    import osxphotos

    photosdb = osxphotos.PhotosDB(PHOTOS_DB_NOT_CLOUD)
    photos = photosdb.photos(uuid=[UUID_DICT["not_cloudasset"]])

    assert not photos[0].iscloudasset


import os
# import cv2
import keras.callbacks
import numpy as np
import glob
import shutil
import matplotlib.pyplot as plt
import datetime
import tensorflow as tf
from sklearn.metrics import confusion_matrix,f1_score
from utils import plot_confusion_matrix, prepare_dataset
from sklearn.metrics import classification_report
import pathlib

# --------- LOAD DATASET ---------
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, cache_dir='.', untar=True)
data_dir = pathlib.Path(data_dir)
print(data_dir)
classes = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
IMG_SHAPE = 480

X_train, y_train, X_test, y_test = prepare_dataset(data_dir, IMG_SHAPE)
input_shape = X_train.shape[1:]
# --------- LOAD MODEL ---------
AUGMENTATION = True
if AUGMENTATION:

    model = tf.keras.applications.efficientnet_v2.EfficientNetV2L(include_top=True,
                                                                  weights='imagenet',
                                                                  classes=1000,
                                                                  classifier_activation='softmax',
                                                                  include_preprocessing=False
                                                                  )
    model.trainable = False
    base_output = model.layers[-2].output
    new_output = tf.keras.layers.Dense(5, activation="softmax")(base_output)
    model = tf.keras.models.Model(
    inputs=model.input, outputs=new_output)
    model.summary()
    # Augmentation Layers
    preprocessing_layer = tf.keras.Sequential([
        tf.keras.layers.Rescaling(scale=1. / 255)
        , tf.keras.layers.RandomFlip("horizontal")
        , tf.keras.layers.RandomZoom(0.2)
        # , tf.keras.layers.Normalization(
        #   mean=[0.485, 0.456, 0.406],
        #   variance=[0.229**2, 0.224**2, 0.225**2],
        #   axis=3)
        #  , tf.keras.layers.RandomTranslation(height_factor = 0.05, width_factor=0.05)
    ])
    inputs = keras.Input(shape=input_shape)
    x = preprocessing_layer(inputs)
    outputs = model(x)
    model = keras.Model(inputs, outputs)
else:
    model = tf.keras.applications.efficientnet_v2.EfficientNetV2L(include_top=True,
                                                                  weights='imagenet',
                                                                  classes=1000,
                                                                  classifier_activation='softmax',
                                                                  include_preprocessing=True
                                                                  )
    model.trainable = False
    base_output = model.layers[-2].output
    new_output = tf.keras.layers.Dense(5, activation="softmax")(base_output)
    model = tf.keras.models.Model(
        inputs=model.input, outputs=new_output)

model.load_weights('checkpoint/MODEL_AUGMENTATION/')  # load pretrained model
model.summary()
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'])
# --------- MODEL EVALUATION ---------
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)

predictions = model.predict(X_test)
print("Accuracy on test set is:{}".format(test_acc))
print("Loss on test set is:{}".format(test_loss))
rounded_predictions = np.argmax(predictions, axis=-1)
cm = confusion_matrix(y_true=y_test, y_pred=rounded_predictions)
plot_confusion_matrix(cm=cm, classes=classes, title='Confusion Matrix')
res = tf.math.confusion_matrix(y_test, rounded_predictions)
print("Confusion Matrix", res)

print("Classification report: \n", (classification_report(y_test, rounded_predictions)))