import allure
import pytest
from allure_commons.types import AttachmentType
from selenium.common.exceptions import NoSuchElementException

from Utilties import XLUtils
from Utilties.customLogger import LogGen
from pageObjects.billing_shipping_page import Billing
from testCases.base_test import BaseTest

class Test_billing_shipping(BaseTest):
    logger = LogGen.loggen()
    path = "TestData/guest.xlsx"

    @pytest.mark.sanity
    @allure.severity(allure.severity_level.NORMAL)
    def test_addtocart(self):
        self.logger.info("*******  veriying billing form   **********")
        self.billing = Billing(self.driver)
        self.billing.shop_product()

        self.driver.save_screenshot(".\\Screenshots\\" + " test form .png")

    @pytest.mark.sanity
    @pytest.mark.regression
    @allure.severity(allure.severity_level.NORMAL)
    def test_billing_from(self):

        self.billing = Billing(self.driver)

        self.logger.info("********* Test Billing form *********")
        self.billing.cart_btn_click()
        self.billing.checkout_btn_click()
        self.logger.info("********* Reading Data from Excel *********")
        self.guest = XLUtils.getRowCount(self.path, 'Sheet1')
        print("number of rows g excel : ", self.guest)
        try:
            self.billing.check_billing_form()
            for g in range(2, self.guest + 1):
                self.name = XLUtils.readData(self.path, 'Sheet1', g, 1)
                self.lname = XLUtils.readData(self.path, 'Sheet1', g, 2)
                self.email = XLUtils.readData(self.path, 'Sheet1', g, 3)
                self.zcode = XLUtils.readData(self.path, 'Sheet1', g, 4)
                self.city = XLUtils.readData(self.path, 'Sheet1', g, 5)
                self.address = XLUtils.readData(self.path, 'Sheet1', g, 6)
                self.Phone = XLUtils.readData(self.path, 'Sheet1', g, 7)

                self.billing.fill_billing_form1(self.name, self.lname, self.email)

                self.billing.fill_billing_form2(self.zcode, self.city, self.address, self.Phone)

                self.logger.info("************* DDT form data entered ************")
        except NoSuchElementException:
            self.driver.save_screenshot(".\\Screenshots\\" + " test Billing form .png")
            self.logger.info("******* Test Billing form coudn't find  **********")
            self.logger.error("***** error occur *******")

        self.billing.checkbox_click()
        self.billing.c_checkout()
        self.logger.info("********* checkout continue  *********")
        self.billing.shipping_op_radio()
        self.billing.checkout_button_click()
        self.billing.place_order_click()
        try:
            self.billing.order_msg_no()
            self.driver.save_screenshot(".\\Screenshots\\" + " test Billing order placed .png")
            self.logger.info("***** Order placed successfully *******")

        except NoSuchElementException:
            self.logger.error("***** order havn't placed  *******")
            self.logger.error("***** error occur *******")
            self.driver.save_screenshot(".\\Screenshots\\" + " test Billing_form order error .png")
            allure.attach(self.driver.get_screenshot_as_png(), name=" Test Billing form order error",
                          attachment_type=AttachmentType.PNG)

        self.driver.close()


#!/usr/bin/python3
"""print_square module"""

def print_square(size):
    """This module prints a square using the # character"""

    char = "#"
    if type(size) not in [int, float]:
        raise TypeError("size must be an integer")
    if type(size) is float and size < 0:
        raise TypeError("size must be an integer")
    if size < 0:
        raise ValueError("size must be >= 0")
    for x in range(int(size)):
        for i in range(int(size)):
            print("{}".format(char), end="")
        if x < size:
            print()


from rclpy.node import Node
from sensor_msgs.msg import Range
from std_msgs.msg import Float32

from rcl_interfaces.msg import SetParametersResult

# from brping import Ping1D
import importlib
module_name = "ping_sonar_ros.ping-python.brping.ping1d"
module = importlib.import_module(module_name)

class Ping1dComponent(Node):
  def __init__(self):
    super().__init__("ping1d_node")
    self.publisher_ = self.create_publisher(Range, "/ping1d/range", 10)
    self.dist_pub_ = self.create_publisher(Float32, "/ping1d/data", 10)
    self.speed_pub_ = self.create_publisher(Float32, "/ping1d/param/speed", 10)
    self.interval_pub_ = self.create_publisher(Float32, "/ping1d/param/interval", 10)
    self.gain_pub_ = self.create_publisher(Float32, "/ping1d/param/gain", 10)
    self.mode_pub_ = self.create_publisher(Float32, "/ping1d/param/mode", 10)
    self.timer_ = self.create_timer(0.1, self.range_callback)

    ### Declare ROS 2 Parameter
    self.declare_parameter('speed', 1450000)  # 1550000 mm/s 1550 m/s
    self.speed_:float = self.get_parameter('speed').value
    self.declare_parameter('interval_num', 100)
    self.interval_num_:float = self.get_parameter('interval_num').value
    self.declare_parameter('gain_num', 1) # int 0 - 6
    self.gain_num_:int = self.get_parameter('gain_num').value
    self.declare_parameter('scan_start', 100) # default 100 [mm] range(30 to 200)
    self.scan_start_:float = self.get_parameter('scan_start').value
    self.declare_parameter('scan_lenght', 3000) # default 2000 [mm] range(2000 to 10000)
    self.scan_lenght_:float = self.get_parameter('scan_lenght').value
    self.declare_parameter('mode_auto', 0) # default 0: manual mode, 1: auto mode
    self.mode_auto_:int = self.get_parameter('mode_auto').value

    self.param_handler_ptr_ = self.add_on_set_parameters_callback(self.set_param_callback)

    ### Make a new Ping
    self.port = "/dev/ttyUSB0"
    self.baudrate = 115200
    self.ping = module.Ping1D()
    self.ping.connect_serial(self.port, self.baudrate)

    if self.ping.initialize() is False:
      print("Failed to initialize Ping!")
      exit(1)

    ### Set Initial parameter
    # self.id = self.ping.get_device_id()
    self.ping.set_speed_of_sound(self.speed_)
    self.ping.set_ping_interval(self.interval_num_)
    self.ping.set_gain_setting(self.gain_num_)
    self.ping.set_range(self.scan_start_, self.scan_lenght_)
    self.ping.set_mode_auto(self.mode_auto_)

  def range_callback(self):
    # distance: Units: mm; The current return distance determined for the most recent acoustic measurement.\n
    # confidence: Units: %; Confidence in the most recent range measurement.\n
    # transmit_duration: Units: us; The acoustic pulse length during acoustic transmission/activation.\n
    # ping_number: The pulse/measurement count since boot.\n
    # scan_start: Units: mm; The beginning of the scan region in mm from the transducer.\n
    # scan_length: Units: mm; The length of the scan region.\n
    # gain_setting: The current gain setting. 0: 0.6, 1: 1.8, 2: 5.5, 3: 12.9, 4: 30.2, 5: 66.1, 6: 144\n
    ### Comment or Uncomment below
    # data = self.ping.get_distance()
    # print("data:%d\n", data)

    # distance: Units: mm; Distance to the target.\n
    # confidence: Units: %; Confidence in the distance measurement.\n
    simple_data = self.ping.get_distance_simple()
    # print("simple data:%d\n", simple_data)

    # scan_start: Units: mm; The beginning of the scan range in mm from the transducer.\n
    # scan_length: Units: mm; The length of the scan range.\n
    range_data = self.ping.get_range()
    # print("scan_start: %s\tscan_length: %s " % (range_data["scan_start"], range_data["scan_length"]))

    # gain_setting: The current gain setting. 0: 0.6, 1: 1.8, 2: 5.5, 3: 12.9, 4: 30.2, 5: 66.1, 6: 144\n
    gain = self.ping.get_gain_setting()
    # print("gain:%d\n", gain)

    # speed_of_sound: Units: mm/s; The speed of sound in the measurement medium. ~1,500,000 mm/s for water.\n
    speed_sound = self.ping.get_speed_of_sound()
    # print("speed_of_sound: %s\n" % (speed_sound["speed_of_sound"]))

    # firmware_version_major: Firmware major version.\n
    # firmware_version_minor: Firmware minor version.\n
    # voltage_5: Units: mV; Device supply voltage.\n
    # ping_interval: Units: ms; The interval between acoustic measurements.\n
    # gain_setting: The current gain setting. 0: 0.6, 1: 1.8, 2: 5.5, 3: 12.9, 4: 30.2, 5: 66.1, 6: 144\n
    # mode_auto: The current operating mode of the device. 0: manual mode, 1: auto mode\n
    ### Comment or Uncomment below
    # general = self.ping.get_general_info()
    # print("general:%d\n", general)

    # ping_interval: Units: ms; The minimum interval between acoustic measurements. The actual interval may be longer.\n
    interval = self.ping.get_ping_interval()
    # print("interval:%d\n", interval)

    mode_auto = self.ping.get_mode_auto()
    # print("mode_auto:%d\n", mode_auto)

    ### ROS 2 data publisher
    range_msg = Range()
    range_msg.header.stamp = self.get_clock().now().to_msg()
    range_msg.header.frame_id = "range_link"
    range_msg.radiation_type = Range.ULTRASOUND
    range_msg.field_of_view = 0.1 # [rad]
    range_msg.min_range = float(range_data["scan_start"]/1000) # [m]
    range_msg.max_range = float(range_data["scan_length"]/1000) # [m]
    range_msg.range = float(simple_data["distance"]/1000) # [m]
    self.publisher_.publish(range_msg)
    self.get_logger().info("Publishing range: {}".format(range_msg.range))

    dist_msg = Float32()
    speed_msg = Float32()
    interval_msg = Float32()
    gain_msg = Float32()
    mode_msg = Float32()
    dist_msg.data = float(simple_data["distance"]/1000)
    speed_msg.data = float(speed_sound["speed_of_sound"]/1000)
    interval_msg.data = float(interval["ping_interval"])
    gain_msg.data = float(gain["gain_setting"])
    mode_msg.data = float(mode_auto["mode_auto"])
    self.dist_pub_.publish(dist_msg)
    self.speed_pub_.publish(speed_msg)
    self.interval_pub_.publish(interval_msg)
    self.gain_pub_.publish(gain_msg)
    self.mode_pub_.publish(mode_msg)

  def set_param_callback(self, params):
        result = SetParametersResult(successful=True)
        for param in params:
            if param.name == 'speed':
                self.speed_ = param.value
                self.get_logger().info('Updated speed value: %f' % self.speed_)
                self.ping.set_speed_of_sound(self.speed_)
            if param.name == 'interval_num':
                self.interval_num_ = param.value
                self.get_logger().info('Updated interval_num value: %f' % self.interval_num_)
                self.ping.set_ping_interval(self.interval_num_)
            if param.name == 'gain_num':
                self.gain_num_ = param.value
                self.get_logger().info('Updated gain_num value: %f' % self.gain_num_)
                self.ping.set_gain_setting(self.gain_num_)
            if param.name == 'scan_start':
                self.scan_start_ = param.value
                self.get_logger().info('Updated scan_start value: %f' % self.scan_start_)
                self.ping.set_range(self.scan_start_, self.scan_lenght_)
            if param.name == 'scan_lenght':
                self.scan_lenght_ = param.value
                self.get_logger().info('Updated scan_lenght value: %f' % self.scan_lenght_)
                self.ping.set_range(self.scan_start_, self.scan_lenght_)
            if param.name == 'mode_auto':
                self.mode_auto_ = param.value
                self.get_logger().info('Updated mode_auto value: %f' % self.mode_auto_)
                self.ping.set_mode_auto(self.mode_auto_)
        return result


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

"""
DisplayCAL setup.py script

Can be used with setuptools or pure distutils (the latter can be forced
with the --use-distutils option, otherwise it will try to use setuptools
by default).

Also supported in addition to standard distutils/setuptools commands,
are the bdist_bbfreeze, py2app and py2exe commands (if the appropriate
packages are installed), which makes this file your all-around building/
bundling powerhouse for DisplayCAL. In the case of py2exe, special care
is taken of Python 2.6+ and the Microsoft.VC90.CRT assembly dependency,
so if building an executable on Windows with Python 2.6+ you should
preferably use py2exe. Please note that bdist_bbfreeze and py2app
*require* setuptools.

IMPORTANT NOTE:
If called from within the installed package, should only be used to
uninstall (setup.py uninstall --record=INSTALLED_FILES), otherwise use
the wrapper script in the root directory of the source tar.gz/zip

"""

from configparser import ConfigParser
from distutils.command.install import install
from distutils.util import change_root, get_platform
from fnmatch import fnmatch
import codecs
import ctypes.util
import distutils.core
import os
import platform
import re
import shutil
import subprocess as sp
import sys
from time import strftime
from types import StringType

# Borrowed from setuptools
def findall(dir=os.curdir):
	"""Find all files under 'dir' and return the list of full filenames
	(relative to 'dir').
	"""
	all_files = []
	for base, dirs, files in os.walk(dir, followlinks=True):
		if base == os.curdir or base.startswith(os.curdir + os.sep):
			base = base[2:]
		if base:
			files = [os.path.join(base, f) for f in files]
		all_files.extend(list(filter(os.path.isfile, files)))
	return all_files

import distutils.filelist
distutils.filelist.findall = findall    # Fix findall bug in distutils

from defaultpaths import autostart, autostart_home
from meta import (author, author_ascii, description, longdesc, domain, name,
				  py_maxversion, py_minversion, version, version_tuple,
				  wx_minversion, author_email, script2pywname, appstream_id)
from util_list import intlist
from util_os import getenvu, relpath, safe_glob
from util_str import safe_str
appname = name

bits = platform.architecture()[0][:2]
pypath = os.path.abspath(__file__)
pydir = os.path.dirname(pypath)
basedir = os.path.dirname(pydir)

if sys.platform in ("darwin", "win32"):
	# Adjust PATH so ctypes.util.find_library can find SDL2 DLLs (if present)
	pth = getenvu("PATH")
	libpth = os.path.join(pydir, "lib")
	if not pth.startswith(libpth + os.pathsep):
		pth = libpth + os.pathsep + pth
		os.environ["PATH"] = safe_str(pth)

config = {"data": ["tests/*.icc"],
		  "doc": ["CHANGES.html",
				  "LICENSE.txt",
				  "README.html",
				  "README-fr.html",
				  "screenshots/*.png",
				  "theme/*.png",
				  "theme/*.css",
				  "theme/*.js",
				  "theme/*.svg",
				  "theme/icons/favicon.ico",
				  "theme/slimbox2/*.css",
				  "theme/slimbox2/*.js"],
		  # Excludes for .app/.exe builds
		  # numpy.lib.utils imports pydoc, which imports Tkinter, but
		  # numpy.lib.utils is not even used by DisplayCAL, so omit all
		  # Tk stuff
		  # Use pyglet with OpenAL as audio backend. We only need
		  # pyglet, pyglet.app and pyglet.media
		  "excludes": {"all": ["Tkconstants", "Tkinter", "pygame",
							   "pyglet.canvas", "pyglet.extlibs", "pyglet.font",
							   "pyglet.gl", "pyglet.graphics", "pyglet.image",
							   "pyglet.input", "pyglet.text",
							   "pyglet.window", "pyo", "setuptools", "tcl",
							   "test", "yaml"],
					   "darwin": ["gdbm"],
					   "win32": ["gi", "win32com.client.genpy"]},
		  "package_data": {name: ["beep.wav",
								  "camera_shutter.wav",
								  "ColorLookupTable.fx",
								  "lang/*.yaml",
								  "linear.cal",
								  "pnp.ids",
								  "presets/*.icc",
								  "quirk.json",
								  "ref/*.cie",
								  "ref/*.gam",
								  "ref/*.icm",
								  "ref/*.ti1",
								  "report/*.css",
								  "report/*.html",
								  "report/*.js",
								  "test.cal",
								  "theme/*.png",
								  "theme/*.wav",
								  "theme/icons/10x10/*.png",
								  "theme/icons/16x16/*.png",
								  "theme/icons/32x32/*.png",
								  "theme/icons/48x48/*.png",
								  "theme/icons/72x72/*.png",
								  "theme/icons/128x128/*.png",
								  "theme/icons/256x256/*.png",
								  "theme/icons/512x512/*.png",
								  "theme/jet_anim/*.png",
								  "theme/patch_anim/*.png",
								  "theme/splash_anim/*.png",
								  "theme/shutter_anim/*.png",
								  "ti1/*.ti1",
								  "x3d-viewer/*.css",
								  "x3d-viewer/*.html",
								  "x3d-viewer/*.js",
								  "xrc/*.xrc"]},
		  "xtra_package_data": {name: {"win32": ["theme/icons/%s-uninstall.ico"
												 % name]}}}

def add_lib_excludes(key, excludebits):
	for exclude in excludebits:
		config["excludes"][key].extend([name + ".lib" + exclude,
										"lib" + exclude])
	for exclude in ("32", "64"):
		for pycompat in ("26", "27"):
			if (key == "win32" and
				(pycompat == sys.version[0] + sys.version[2] or
				 exclude == excludebits[0])):
				continue
			config["excludes"][key].extend([name + ".lib%s.python%s" %
											(exclude, pycompat),
											name + ".lib%s.python%s.RealDisplaySizeMM" %
											(exclude, pycompat)])

add_lib_excludes("darwin", ["64" if bits == "32" else "32"])
add_lib_excludes("win32", ["64" if bits == "32" else "32"])

msiversion = ".".join((str(version_tuple[0]),
					   str(version_tuple[1]),
					   str(version_tuple[2]) +
					   str(version_tuple[3])))

plist_dict = {"CFBundleDevelopmentRegion": "English",
			  "CFBundleExecutable": name,
			  "CFBundleGetInfoString": version,
			  "CFBundleIdentifier": ".".join(reversed(domain.split("."))) +
									"." + name,
			  "CFBundleInfoDictionaryVersion": "6.0",
			  "CFBundleLongVersionString": version,
			  "CFBundleName": name,
			  "CFBundlePackageType": "APPL",
			  "CFBundleShortVersionString": version,
			  "CFBundleSignature": "????",
			  "CFBundleVersion": ".".join(map(str, version_tuple)),
			  "NSHumanReadableCopyright": "© %s %s" % (strftime("%Y"), author),
			  "LSMinimumSystemVersion": "10.6.0"}

class Target:
	def __init__(self, **kwargs):
		self.__dict__.update(kwargs)

def create_app_symlinks(dist_dir, scripts):
	maincontents_rel = os.path.join(name + ".app", "Contents")
	# Create ref, tests, ReadMe and license symlinks in directory
	# containing the app bundle
	for src, tgt in [("ref", "Reference"),
					 ("tests", "Tests"),
					 ("CHANGES.html", "CHANGES.html"),
					 ("README.html", "README.html"),
					 ("README-fr.html", "README-fr.html"),
					 ("LICENSE.txt", "LICENSE.txt")]:
		tgt = os.path.join(dist_dir, tgt)
		if os.path.islink(tgt):
			os.unlink(tgt)
		os.symlink(os.path.join(maincontents_rel, "Resources", src), tgt)
	# Create standalone tools app bundles by symlinking to the main bundle
	scripts = [(script2pywname(script), desc) for script, desc in scripts]
	toolscripts = [script for script in [script for script, desc in scripts] if script != name]
	for script, desc in scripts:
		if (script in (name, name + "-apply-profiles",
					   name + "-eeColor-to-madVR-converter") or
			script.endswith("-console")):
			continue
		toolname = desc.replace(name, "").strip()
		toolapp = os.path.join(dist_dir, toolname + ".app")
		if os.path.isdir(toolapp):
			if input('WARNING: The output directory "%s" and ALL ITS '
                         'CONTENTS will be REMOVED! Continue? (y/n)' % toolapp).lower() == 'y':
				print("Removing dir", toolapp)
				shutil.rmtree(toolapp)
			else:
				raise SystemExit('User aborted')
		toolscript = os.path.join(dist_dir, maincontents_rel, 'MacOS', script)
		has_tool_script = os.path.exists(toolscript)
		if not has_tool_script:
			# Don't symlink, apps won't be able to run in parallel!
			shutil.copy(os.path.join(dist_dir, maincontents_rel, 'MacOS',
						appname), toolscript)
		toolcontents = os.path.join(toolapp, "Contents")
		os.makedirs(toolcontents)
		subdirs = ["Frameworks", "Resources"]
		if has_tool_script:
			# PyInstaller
			subdirs.append("MacOS")
		for entry in os.listdir(os.path.join(dist_dir, maincontents_rel)):
			if entry in subdirs:
				os.makedirs(os.path.join(toolcontents, entry))
				for subentry in os.listdir(os.path.join(dist_dir,
														maincontents_rel,
														entry)):
					src = os.path.join(dist_dir, maincontents_rel,
									   entry, subentry)
					tgt = os.path.join(toolcontents, entry, subentry)
					if subentry == "main.py":
						# py2app
						with open(src, "rb") as main_in:
							py = main_in.read()
						py = py.replace("main()",
										"main(%r)" %
										script[len(name) + 1:])
						with open(tgt, "wb") as main_out:
							main_out.write(py)
						continue
					if subentry == name + ".icns":
						shutil.copy(os.path.join(pydir, "theme",
												 "icons",
												 "%s.icns" % script),
									os.path.join(toolcontents, entry,
												 "%s.icns" % script))
						continue
					if subentry == script:
						# PyInstaller
						os.rename(src, tgt)
					elif subentry not in toolscripts:
						os.symlink(os.path.join("..", "..", "..",
												maincontents_rel, entry,
												subentry), tgt)
			elif entry == "Info.plist":
				with codecs.open(os.path.join(dist_dir, maincontents_rel,
											  entry), "r", "UTF-8") as info_in:
					infoxml = info_in.read()
				# CFBundleName / CFBundleDisplayName
				infoxml = re.sub("(Name</key>\s*<string>)%s" % name,
								 lambda match: match.group(1) +
											   toolname, infoxml)
				# CFBundleIdentifier
				infoxml = infoxml.replace(".%s</string>" % name,
										  ".%s</string>" % script)
				# CFBundleIconFile
				infoxml = infoxml.replace("%s.icns</string>" % name,
										  "%s.icns</string>" % script)
				# CFBundleExecutable
				infoxml = re.sub("(Executable</key>\s*<string>)%s" % name,
								 lambda match: match.group(1) +
											   script, infoxml)
				with codecs.open(os.path.join(toolcontents, entry), "w",
								 "UTF-8") as info_out:
					info_out.write(infoxml)
			else:
				os.symlink(os.path.join("..", "..", maincontents_rel, entry),
						   os.path.join(toolcontents, entry))

def get_data(tgt_dir, key, pkgname=None, subkey=None, excludes=None):
	""" Return configured data files """
	files = config[key]
	src_dir = basedir
	if pkgname:
		files = files[pkgname]
		src_dir = os.path.join(src_dir, pkgname)
		if subkey:
			if subkey in files:
				files = files[subkey]
			else:
				files = []
	data = []
	for pth in files:
		if not [exclude for exclude in excludes or [] if fnmatch(pth, exclude)]:
			data.append((os.path.normpath(os.path.join(tgt_dir, os.path.dirname(pth))),
						 safe_glob(os.path.join(src_dir, pth))))
	return data

def get_scripts(excludes=None):
	# It is required that each script has an accompanying .desktop file
	scripts_with_desc = []
	scripts = safe_glob(os.path.join(pydir, "..", "scripts",
									 appname.lower() + "*"))
	def sortbyname(a, b):
		a, b = [os.path.splitext(v)[0] for v in (a, b)]
		if a > b:
			return 1
		elif a < b:
			return -1
		else:
			return 0
	scripts.sort(sortbyname)
	for script in scripts:
		script = os.path.basename(script)
		if script == appname.lower() + "-apply-profiles-launcher":
			continue
		desktopfile = os.path.join(pydir, "..", "misc", script + ".desktop")
		if os.path.isfile(desktopfile):
			cfg = ConfigParser()
			cfg.read(desktopfile)
			script = cfg.get("Desktop Entry", "Exec").split()[0]
			desc = cfg.get("Desktop Entry", "Name").decode("UTF-8")
		else:
			desc = ""
		if not [exclude for exclude in excludes or [] if fnmatch(script, exclude)]:
			scripts_with_desc.append((script, desc))
	return scripts_with_desc

def setup():
	print("***", os.path.abspath(sys.argv[0]), " ".join(sys.argv[1:]))

	bdist_bbfreeze = "bdist_bbfreeze" in sys.argv[1:]
	bdist_dumb = "bdist_dumb" in sys.argv[1:]
	bdist_win = "bdist_msi" in sys.argv[1:] or "bdist_wininst" in sys.argv[1:]
	debug = 0
	do_full_install = False
	do_install = False
	do_py2app = "py2app" in sys.argv[1:]
	do_py2exe = "py2exe" in sys.argv[1:]
	do_uninstall = "uninstall" in sys.argv[1:]
	doc_layout = "deb" if os.path.exists("/etc/debian_version") else ""
	dry_run = "-n" in sys.argv[1:] or "--dry-run" in sys.argv[1:]
	help = False
	install_data = None # data files install path (only if given)
	is_rpm_build = "bdist_rpm" in sys.argv[1:] or os.path.abspath(sys.argv[0]).endswith(
		os.path.join(os.path.sep, "rpm", "BUILD", name + "-" + version,
		os.path.basename(os.path.abspath(sys.argv[0]))))
	prefix = ""
	recordfile_name = None # record installed files to this file
	sdist = "sdist" in sys.argv[1:]
	setuptools = None
	skip_instrument_conf_files = "--skip-instrument-configuration-files" in \
		sys.argv[1:]
	skip_postinstall = "--skip-postinstall" in sys.argv[1:]
	use_distutils = not bdist_bbfreeze and not do_py2app
	use_setuptools = not use_distutils or "--use-setuptools" in \
		sys.argv[1:] or (os.path.exists("use-setuptools") and
						 not "--use-distutils" in sys.argv[1:])
	use_sdl = "--use-sdl" in sys.argv[1:]

	sys.path.insert(1, os.path.join(os.path.dirname(pydir), "util"))

	current_findall = distutils.filelist.findall

	if use_setuptools:
		if "--use-setuptools" in sys.argv[1:] and not \
		   os.path.exists("use-setuptools"):
			open("use-setuptools", "w").close()
		try:
			from ez_setup import use_setuptools as ez_use_setuptools
			ez_use_setuptools()
		except ImportError:
			pass
		try:
			from setuptools import setup, Extension
			setuptools = True
			print("using setuptools")
			current_findall = distutils.filelist.findall
		except ImportError:
			pass
	else:
		if os.path.exists("use-setuptools"):
			os.remove("use-setuptools")

	if distutils.filelist.findall is current_findall:
		# Fix traversing unneeded dirs which can take a long time (minutes)
		def findall(dir=os.curdir, original=distutils.filelist.findall, listdir=os.listdir,
					basename=os.path.basename):
			os.listdir = lambda path: [entry for entry in listdir(path) if entry not in ("build",
																		 "dist") and
														   not entry.startswith(".")]
			try:
				return original(dir)
			finally:
				os.listdir = listdir

		distutils.filelist.findall = findall

	if not setuptools:
		from distutils.core import setup, Extension
		print("using distutils")

	if do_py2exe:
		import py2exe
		# ModuleFinder can't handle runtime changes to __path__, but win32com
		# uses them
		try:
			# if this doesn't work, try import modulefinder
			import py2exe.mf as modulefinder
			import win32com
			for p in win32com.__path__[1:]:
				modulefinder.AddPackagePath("win32com", p)
			for extra in ["win32com.shell"]:
				__import__(extra)
				m = sys.modules[extra]
				for p in m.__path__[1:]:
					modulefinder.AddPackagePath(extra, p)
		except ImportError:
			# no build path setup, no worries.
			pass

	if do_py2exe:
		origIsSystemDLL = py2exe.build_exe.isSystemDLL
		systemroot = os.getenv("SystemRoot").lower()
		def isSystemDLL(pathname):
			if (os.path.basename(pathname).lower() in ("gdiplus.dll",
													   "mfc90.dll") or
				os.path.basename(pathname).lower().startswith("python") or
				os.path.basename(pathname).lower().startswith("pywintypes")):
				return 0
			return pathname.lower().startswith(systemroot + "\\")
		py2exe.build_exe.isSystemDLL = isSystemDLL

		# Numpy DLL paths fix
		def numpy_dll_paths_fix():
			import numpy
			paths = set()
			numpy_path = numpy.__path__[0]
			for dirpath, dirnames, filenames in os.walk(numpy_path):
				for item in filenames:
					if item.lower().endswith(".dll"):
						paths.add(dirpath)
			sys.path.extend(paths)
		numpy_dll_paths_fix()

	if do_uninstall:
		i = sys.argv.index("uninstall")
		sys.argv = sys.argv[:i] + ["install"] + sys.argv[i + 1:]
		install.create_home_path = lambda self: None

	if skip_instrument_conf_files:
		i = sys.argv.index("--skip-instrument-configuration-files")
		sys.argv = sys.argv[:i] + sys.argv[i + 1:]

	if skip_postinstall:
		i = sys.argv.index("--skip-postinstall")
		sys.argv = sys.argv[:i] + sys.argv[i + 1:]

	if "--use-distutils" in sys.argv[1:]:
		i = sys.argv.index("--use-distutils")
		sys.argv = sys.argv[:i] + sys.argv[i + 1:]

	if "--use-setuptools" in sys.argv[1:]:
		i = sys.argv.index("--use-setuptools")
		sys.argv = sys.argv[:i] + sys.argv[i + 1:]

	argv = list(sys.argv[1:])
	for i, arg in enumerate(reversed(argv)):
		n = len(sys.argv) - i - 1
		if arg in ("install", "install_lib", "install_headers",
				   "install_scripts", "install_data"):
			if arg == "install":
				do_full_install = True
			do_install = True
		elif arg == "-d" and len(sys.argv[1:]) > i:
			dist_dir = sys.argv[i + 2]
		else:
			arg = arg.split("=")
			if arg[0] == "--debug":
				debug = 1 if len(arg) == 1 else int(arg[1])
				sys.argv = sys.argv[:n] + sys.argv[n + 1:]
			elif len(arg) == 2:
				if arg[0] == "--dist-dir":
					dist_dir = arg[1]
				elif arg[0] == "--doc-layout":
					doc_layout = arg[1]
					sys.argv = sys.argv[:n] + sys.argv[n + 1:]
				elif arg[0] == "--install-data":
					install_data = arg[1]
				elif arg[0] == "--prefix":
					prefix = arg[1]
				elif arg[0] == "--record":
					recordfile_name = arg[1]
			elif arg[0] == "-h" or arg[0].startswith("--help"):
				help = True

	if not recordfile_name and (do_full_install or do_uninstall):
		recordfile_name = "INSTALLED_FILES"
		# if not do_uninstall:
			# sys.argv.append("--record=" + "INSTALLED_FILES")

	if sys.platform in ("darwin", "win32") or "bdist_egg" in sys.argv[1:]:
		doc = data = "." if do_py2app or do_py2exe or bdist_bbfreeze else name
	else:
		# Linux/Unix
		data = name
		if doc_layout.startswith("deb"):
			doc = os.path.join("doc", name.lower())
		elif "suse" in doc_layout:
			doc = os.path.join("doc", "packages", name)
		else:
			doc = os.path.join("doc", name + "-" + version)
		if not install_data:
			data = os.path.join("share", data)
			doc = os.path.join("share", doc)
			if is_rpm_build:
				doc = os.path.join(os.path.sep, "usr", doc)

	# Use CA file from certifi project
	if do_py2app or do_py2exe:
		import certifi
		cacert = certifi.where()
		if cacert:
			shutil.copyfile(cacert, os.path.join(pydir, "cacert.pem"))
			config["package_data"][name].append("cacert.pem")
		else:
			print("WARNING: cacert.pem from certifi project not found!")

	# on Mac OS X and Windows, we want data files in the package dir
	# (package_data will be ignored when using py2exe)
	package_data = {
		name: config["package_data"][name]
			  if sys.platform in ("darwin", "win32") and not do_py2app and not
			  do_py2exe else []
	}
	if sdist and sys.platform in ("darwin", "win32"):
		package_data[name].extend(["theme/icons/22x22/*.png",
								   "theme/icons/24x24/*.png"])
	if sys.platform == "win32" and not do_py2exe:
		package_data[name].append("theme/icons/*.ico")
	# Scripts
	if sys.platform == 'darwin':
		scripts = get_scripts(excludes=[appname.lower() + '-apply-profiles'])
	else:
		scripts = get_scripts()
	# Doc files
	data_files = []
	if not is_rpm_build or doc_layout.startswith("deb"):
		data_files += get_data(doc, "doc", excludes=["LICENSE.txt"])
	if data_files:
		if doc_layout.startswith("deb"):
			data_files.append((doc, [os.path.join(pydir, "..", "dist",
												  "copyright")]))
			data_files.append((os.path.join(os.path.dirname(data), "doc-base"),
							   [os.path.join(pydir, "..", "misc",
											 appname.lower() + "-readme")]))
		else:
			data_files.append((doc, [os.path.join(pydir, "..", "LICENSE.txt")]))
	if sys.platform not in ("darwin", "win32") or do_py2app or do_py2exe:
		# Linux/Unix or py2app/py2exe
		data_files += get_data(data, "package_data", name,
							   excludes=["theme/icons/*"])
		data_files += get_data(data, "data")
		data_files += get_data(data, "xtra_package_data", name, sys.platform)
		if sys.platform == "win32":
			# Add python and pythonw
			data_files.extend([(os.path.join(data, "lib"), [sys.executable,
				os.path.join(os.path.dirname(sys.executable), "pythonw.exe")])])
			if use_sdl:
				# SDL DLLs for audio module
				sdl2 = ctypes.util.find_library("SDL2")
				sdl2_mixer = ctypes.util.find_library("SDL2_mixer")
				if sdl2:
					sdl2_libs = [sdl2]
					if sdl2_mixer:
						sdl2_libs.append(sdl2_mixer)
						data_files.append((os.path.join(data, "lib"), sdl2_libs))
						config["excludes"]["all"].append("pyglet")
					else:
						print("WARNING: SDL2_mixer not found!")
				else:
					print("WARNING: SDL2 not found!")
			if not "pyglet" in config["excludes"]["all"]:
				# OpenAL DLLs for pyglet
				openal32 = ctypes.util.find_library("OpenAL32.dll")
				wrap_oal = ctypes.util.find_library("wrap_oal.dll")
				if openal32:
					oal = [openal32]
					if wrap_oal:
						oal.append(wrap_oal)
					else:
						print("WARNING: wrap_oal.dll not found!")
					data_files.append((data, oal))
				else:
					print("WARNING: OpenAL32.dll not found!")
		elif sys.platform != "darwin":
			# Linux
			data_files.append((os.path.join(os.path.dirname(data), "metainfo"),
							   [os.path.join(pydir, "..", "dist",
											 appstream_id + ".appdata.xml")]))
			data_files.append((os.path.join(os.path.dirname(data),
											"applications"),
							   [os.path.join(pydir, "..", "misc", name.lower() +
											 ".desktop")] +
							   safe_glob(os.path.join(pydir, "..", "misc",
													  name.lower() + "-*.desktop"))))
			data_files.append((autostart if os.geteuid() == 0 or prefix.startswith("/")
							   else autostart_home,
							   [os.path.join(pydir, "..", "misc",
											 "z-%s-apply-profiles.desktop" % name.lower())]))
			data_files.append((os.path.join(os.path.dirname(data), "man", "man1"),
							   safe_glob(os.path.join(pydir, "..", "man", "*.1"))))
			if not skip_instrument_conf_files:
				# device configuration / permission stuff
				if is_rpm_build:
					# RPM postinstall script will install these to the correct
					# locations. This allows us compatibility with Argyll
					# packages which may also contain same udev rules / hotplug
					# scripts, thus avoiding file conflicts
					data_files.append((os.path.join(data, "usb"), [os.path.join(
									   pydir, "..", "misc", "45-Argyll.rules")]))
					data_files.append((os.path.join(data, "usb"), [os.path.join(
									   pydir, "..", "misc", "55-Argyll.rules")]))
					data_files.append((os.path.join(data, "usb"), [os.path.join(
									   pydir, "..", "misc", "Argyll")]))
					data_files.append((os.path.join(data, "usb"), [os.path.join(
									   pydir, "..", "misc", "Argyll.usermap")]))
				else:
					devconf_files = []
					if os.path.isdir("/etc/udev/rules.d"):
						if safe_glob("/dev/bus/usb/*/*"):
							# USB and serial instruments using udev, where udev
							# already creates /dev/bus/usb/00X/00X devices
							devconf_files.append(
								("/etc/udev/rules.d", [os.path.join(
									pydir, "..", "misc", "55-Argyll.rules")]))
						else:
							# USB using udev, where there are NOT /dev/bus/usb/00X/00X
							# devices
							devconf_files.append(
								("/etc/udev/rules.d", [os.path.join(
									pydir, "..", "misc", "45-Argyll.rules")]))
					else:
						if os.path.isdir("/etc/hotplug"):
							# USB using hotplug and Serial using udev
							# (older versions of Linux)
							devconf_files.append(
								("/etc/hotplug/usb", [os.path.join(pydir, "..", "misc",
																   fname) for fname in
													  ["Argyll", "Argyll.usermap"]]))
					for entry in devconf_files:
						for fname in entry[1]:
							if os.path.isfile(fname):
								data_files.extend([(entry[0], [fname])])
		for dname in ("10x10", "16x16", "22x22", "24x24", "32x32", "48x48",
					  "72x72", "128x128", "256x256", "512x512"):
			# Get all the icons needed, depending on platform
			# Only the icon sizes 10, 16, 32, 72, 256 and 512 include icons
			# that are used exclusively for UI elements.
			# These should be installed in an app-specific location, e.g.
			# under Linux $XDG_DATA_DIRS/DisplayCAL/theme/icons/
			# The app icon sizes 16, 32, 48 and 256 (128 under Mac OS X),
			# which are used for taskbar icons and the like, as well as the
			# other sizes can be installed in a generic location, e.g.
			# under Linux $XDG_DATA_DIRS/icons/hicolor/<size>/apps/
			# Generally, icon filenames starting with the lowercase app name
			# should be installed in the generic location.
			icons = []
			desktopicons = []
			if sys.platform == "darwin":
				largest_iconbundle_icon_size = "128x128"
			else:
				largest_iconbundle_icon_size = "256x256"
			for iconpath in safe_glob(os.path.join(pydir, "theme", "icons",
												   dname, "*.png")):
				if not os.path.basename(iconpath).startswith(name.lower()) or (
					sys.platform in ("darwin", "win32") and
					dname in ("16x16", "32x32", "48x48",
							  largest_iconbundle_icon_size)):
					# In addition to UI element icons, we also need all the app
					# icons we use in get_icon_bundle under macOS/Windows,
					# otherwise they wouldn't be included (under Linux, these
					# are included for installation to the system-wide icon
					# theme location instead)
					icons.append(iconpath)
				elif sys.platform not in ("darwin", "win32"):
					desktopicons.append(iconpath)
			if icons:
				data_files.append((os.path.join(data, "theme", "icons", dname),
								   icons))
			if desktopicons:
				data_files.append((os.path.join(os.path.dirname(data), "icons",
											 "hicolor", dname, "apps"),
								   desktopicons))
	if do_py2app:
		data_files.append((os.path.join(data, "scripts"),
						   [os.path.join(pydir, "..", "scripts",
										 name.lower() +
										 "-eecolor-to-madvr-converter")]))

	sources = [os.path.join(name, "RealDisplaySizeMM.c")]
	if sys.platform == "win32":
		macros = [("NT", None)]
		libraries = ["user32", "gdi32"]
		link_args = None
	elif sys.platform == "darwin":
		macros = [("__APPLE__", None), ("UNIX", None)]
		libraries = None
		# XXX: Not sure which macOS version exactly removed the need
		# to specify -framework
		if intlist(platform.mac_ver()[0].split(".")) >= [10, 7]:
			link_args = None
		else:
			link_args = ["-framework Carbon", "-framework CoreFoundation",
							   "-framework Python", "-framework IOKit"]
			if not help and ("build" in sys.argv[1:] or
							 "build_ext" in sys.argv[1:] or
							 (("install" in sys.argv[1:] or
							   "install_lib" in sys.argv[1:]) and
							  not "--skip-build" in sys.argv[1:])):
				p = sp.Popen([sys.executable, '-c', '''import os
from distutils.core import setup, Extension

setup(ext_modules=[Extension("%s.lib%s.RealDisplaySizeMM", sources=%r,
							 define_macros=%r, extra_link_args=%r)])''' %
							  (name, bits, sources, macros, link_args)] + sys.argv[1:],
							 stdout = sp.PIPE, stderr = sp.STDOUT)
				lines = []
				while True:
					o = p.stdout.readline()
					if o == '' and p.poll() != None:
						break
					if o[0:4] == 'gcc ':
						lines.append(o)
					print(o.rstrip())
				if len(lines):
					os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.5'
					sp.call(lines[-1], shell = True)  # fix the library
	else:
		macros = [("UNIX", None)]
		libraries = ["X11", "Xinerama", "Xrandr", "Xxf86vm"]
		link_args = None
	if sys.platform == "darwin":
		extname = "%s.lib%s.RealDisplaySizeMM" % (name, bits)
	else:
		extname = "%s.lib%s.python%s%s.RealDisplaySizeMM" % ((name, bits) +
															 sys.version_info[:2])
	RealDisplaySizeMM = Extension(extname,
								  sources=sources,
								  define_macros=macros,
								  libraries=libraries,
								  extra_link_args=link_args)
	ext_modules = [RealDisplaySizeMM]

	requires = []
	if not setuptools or sys.platform != "win32":
		# wxPython windows installer doesn't add egg-info entry, so
		# a dependency check from pkg_resources would always fail
		requires.append(
			"wxPython (>= %s)" % ".".join(str(n) for n in wx_minversion))
	if sys.platform == "win32":
		requires.append("pywin32 (>= 213.0)")

	packages = [name, "%s.lib" % name, "%s.lib.agw" % name]
	if sdist:
		# For source desributions we want all libraries
		for tmpbits in ("32", "64"):
			for pycompat in ("26", "27"):
				packages.extend(["%s.lib%s" % (name, tmpbits),
								 "%s.lib%s.python%s" % (name, tmpbits, pycompat)])
	elif sys.platform == "darwin":
		# On Mac OS X we only want the universal binaries
		packages.append("%s.lib%s" % (name, bits))
	else:
		# On Linux/Windows we want separate libraries
		packages.extend(["%s.lib%s" % (name, bits),
						 "%s.lib%s.python%s%s" % ((name, bits) + sys.version_info[:2])])

	attrs = {
		"author": author_ascii,
		"author_email": author_email.replace("@", "_at_"),
		"classifiers": [
			"Development Status :: 5 - Production/Stable",
			"Environment :: MacOS X",
			"Environment :: Win32 (MS Windows)",
			"Environment :: X11 Applications",
			"Intended Audience :: End Users/Desktop",
			"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
			"Operating System :: OS Independent",
			"Programming Language :: Python :: 2.6",
			"Programming Language :: Python :: 2.7",
			"Topic :: Multimedia :: Graphics",
		],
		"data_files": data_files,
		"description": description,
		"download_url": "https://%(domain)s/download/"
						"%(name)s-%(version)s.tar.gz" %
						{"domain": domain, "name": name, "version": version},
		"ext_modules": ext_modules,
		"license": "GPL v3",
		"long_description": longdesc,
		"name": name,
		"packages": packages,
		"package_data": package_data,
		"package_dir": {
			name: name
		},
		"platforms": [
			"Python >= %s <= %s" % (".".join(str(n) for n in py_minversion),
									".".join(str(n) for n in py_maxversion)),
			"Linux/Unix with X11",
			"Mac OS X >= 10.4",
			"Windows 2000 and newer"
		],
		"requires": requires,
		"provides": [name],
		"scripts": [],
		"url": "https://%s/" % domain,
		"version": msiversion if "bdist_msi" in sys.argv[1:] else version
	}

	if setuptools:
		attrs["entry_points"] = {
			"gui_scripts": [
				"%s = %s.main:main%s" % (script, name,
					"" if script == name.lower()
					else script[len(name):].lower().replace("-", "_"))
				for script, desc in scripts
			]
		}
		attrs["exclude_package_data"] = {
			name: ["RealDisplaySizeMM.c"]
		}
		attrs["include_package_data"] = sys.platform in ("darwin", "win32") and not do_py2app
		install_requires = [req.replace("(", "").replace(")", "") for req in
							requires]
		attrs["install_requires"] = install_requires
		attrs["zip_safe"] = False
	else:
		attrs["scripts"].extend(os.path.join("scripts", script)
								for script, desc in
								[script_desc for script_desc in scripts if script_desc[0] != name.lower() + "-apply-profiles" or
									   sys.platform != "darwin"])

	if bdist_bbfreeze:
		attrs["setup_requires"] = ["bbfreeze"]

	if "bdist_wininst" in sys.argv[1:]:
		attrs["scripts"].append(os.path.join("util", name + "_postinstall.py"))

	if do_py2app:
		mainpy = os.path.join(basedir, "main.py")
		if not os.path.exists(mainpy):
			shutil.copy(os.path.join(basedir, "scripts", name.lower()), mainpy)
		attrs["app"] = [mainpy]
		dist_dir = os.path.join(pydir, "..", "dist",
								"py2app.%s-py%s" % (get_platform(),
													sys.version[:3]),
								name + "-" + version)
		from py2app.build_app import py2app as py2app_cls
		py2app_cls._copy_package_data = py2app_cls.copy_package_data
		def copy_package_data(self, package, target_dir):
			# Skip package data which is already included as data files
			if package.identifier.split('.')[0] != name:
				self._copy_package_data(package, target_dir)
		py2app_cls.copy_package_data = copy_package_data
		attrs["options"] = {
			"py2app": {
				"argv_emulation": True,
				"dist_dir": dist_dir,
				"excludes": config["excludes"]["all"] +
							config["excludes"]["darwin"],
				"iconfile": os.path.join(pydir, "theme", "icons",
										 name + ".icns"),
				"optimize": 0,
				"plist": plist_dict
			}
		}
		if use_sdl:
			attrs["options"]["py2app"]["frameworks"] = ["SDL2", "SDL2_mixer"]
		attrs["setup_requires"] = ["py2app"]

	if do_py2exe:
		import wx
		from winmanifest_util import getmanifestxml
		if platform.architecture()[0] == "64bit":
			arch = "amd64"
		else:
			arch = "x86"
		manifest_xml = getmanifestxml(os.path.join(pydir, "..", "misc",
			name + (".exe.%s.VC90.manifest" % arch if hasattr(sys, "version_info") and
			sys.version_info[:2] >= (2,6) else ".exe.manifest")))
		tmp_scripts_dir = os.path.join(basedir, "build", "temp.scripts")
		if not os.path.isdir(tmp_scripts_dir):
			os.makedirs(tmp_scripts_dir)
		apply_profiles_launcher = (appname.lower() + "-apply-profiles-launcher",
								   appname + " Profile Loader Launcher")
		for script, desc in scripts + [apply_profiles_launcher]:
			shutil.copy(os.path.join(basedir, "scripts", script),
						os.path.join(tmp_scripts_dir, script2pywname(script)))
		attrs["windows"] = [Target(**{
			"script": os.path.join(tmp_scripts_dir, script2pywname(script)),
			"icon_resources": [(1, os.path.join(pydir, "theme", "icons",
												os.path.splitext(os.path.basename(script))[0] +
												".ico"))],
			"other_resources": [(24, 1, manifest_xml)],
			"copyright": "© %s %s" % (strftime("%Y"), author),
			"description": desc
		}) for script, desc in [script_desc1 for script_desc1 in scripts if script_desc1[0] != appname.lower() +
									  "-eecolor-to-madvr-converter" and
									  not script_desc1[0].endswith("-console")]]

		# Add profile loader launcher
		attrs["windows"].append(Target(**{
			"script": os.path.join(tmp_scripts_dir,
								   script2pywname(apply_profiles_launcher[0])),
			"icon_resources": [(1, os.path.join(pydir, "theme", "icons",
												appname + "-apply-profiles" +
												".ico"))],
			"other_resources": [(24, 1, manifest_xml)],
			"copyright": "© %s %s" % (strftime("%Y"), author),
			"description": apply_profiles_launcher[1]
		}))

		# Programs that can run with and without GUI
		console_scripts = [name + "-VRML-to-X3D-converter"]  # No "-console" suffix!
		for console_script in console_scripts:
			console_script_path = os.path.join(tmp_scripts_dir,
											   console_script + "-console")
			if not os.path.isfile(console_script_path):
				shutil.copy(os.path.join(basedir, "scripts",
										 console_script.lower() + "-console"),
							console_script_path)
		attrs["console"] = [Target(**{
			"script": os.path.join(tmp_scripts_dir,
								   script2pywname(script) + "-console"),
			"icon_resources": [(1, os.path.join(pydir, "theme", "icons",
												os.path.splitext(os.path.basename(script))[0] +
												".ico"))],
			"other_resources": [(24, 1, manifest_xml)],
			"copyright": "© %s %s" % (strftime("%Y"), author),
			"description": desc
		}) for script, desc in [script_desc2 for script_desc2 in scripts if script2pywname(script_desc2[0]) in console_scripts]]

		# Programs without GUI
		attrs["console"].append(Target(**{
			"script": os.path.join(tmp_scripts_dir,
								   appname + "-eeColor-to-madVR-converter"),
			"icon_resources": [(1, os.path.join(pydir, "theme", "icons",
												appname + "-3DLUT-maker.ico"))],
			"other_resources": [(24, 1, manifest_xml)],
			"copyright": "© %s %s" % (strftime("%Y"), author),
			"description": "Convert eeColor 65^3 to madVR 256^3 3D LUT "
						   "(video levels in, video levels out)"
		}))

		dist_dir = os.path.join(pydir, "..", "dist", "py2exe.%s-py%s" %
								(get_platform(), sys.version[:3]), name +
								"-" + version)
		attrs["options"] = {
			"py2exe": {
				"dist_dir": dist_dir,
				"dll_excludes": [
					"iertutil.dll",
					"MPR.dll",
					"msvcm90.dll",
					"msvcp90.dll",
					"msvcr90.dll",
					"mswsock.dll",
					"urlmon.dll",
					"w9xpopen.exe"
				],
				"excludes": config["excludes"]["all"] +
							config["excludes"]["win32"],
				"bundle_files": 3 if wx.VERSION >= (2, 8, 10, 1) else 1,
				"compressed": 1,
				"optimize": 0  # 0 = don’t optimize (generate .pyc)
							   # 1 = normal optimization (like python -O)
							   # 2 = extra optimization (like python -OO)
			}
		}
		if debug:
			attrs["options"]["py2exe"].update({
				"bundle_files": 3,
				"compressed": 0,
				"optimize": 0,
				"skip_archive": 1
			})
		if setuptools:
			attrs["setup_requires"] = ["py2exe"]
		attrs["zipfile"] = os.path.join("lib", "library.zip")

	if (do_uninstall or do_install or bdist_win or bdist_dumb) and not help:
		distutils.core._setup_stop_after = "commandline"
		dist = setup(**attrs)
		distutils.core._setup_stop_after = None
		cmd = install(dist).get_finalized_command("install")
		if debug > 0:
			for attrname in [
				"base",
				"data",
				"headers",
				"lib",
				"libbase",
				"platbase",
				"platlib",
				"prefix",
				"purelib",
				"root",
				"scripts",
				"userbase"
			]:
				if attrname not in ["prefix", "root"]:
					attrname = "install_" + attrname
				if hasattr(cmd, attrname):
					print(attrname, getattr(cmd, attrname))
		if debug > 1:
			try:
				from ppdir import ppdir
			except ImportError:
				pass
			else:
				ppdir(cmd, types=[dict, list, str, tuple, type, str])
		if not install_data and sys.platform in ("darwin", "win32"):
			# on Mac OS X and Windows, we want data files in the package dir
			data_basedir = cmd.install_lib
		else:
			data_basedir = cmd.install_data
		data = change_root(data_basedir, data)
		doc = change_root(data_basedir, doc)
		# determine in which cases we want to make data file paths relative to
		# site-packages (on Mac and Windows) and when we want to make them
		# absolute (Linux)
		linux = sys.platform not in ("darwin", "win32") and (not cmd.root and
															 setuptools)
		dar_win = (sys.platform in ("darwin", "win32") and
				   (cmd.root or not setuptools)) or bdist_win
		if not do_uninstall and not install_data and (linux or dar_win) and \
		   attrs["data_files"]:
			if data_basedir.startswith(cmd.install_data + os.path.sep):
				data_basedir = relpath(data_basedir, cmd.install_data)
			print("*** changing basedir for data_files:", data_basedir)
			for i, f in enumerate(attrs["data_files"]):
				if type(f) is StringType:
					attrs["data_files"][i] = change_root(data_basedir, f)
				else:
					attrs["data_files"][i] = (change_root(data_basedir, f[0]),
											  f[1])

	if do_uninstall and not help:

		# Quick and dirty uninstall

		if dry_run:
			print("dry run - nothing will be removed")
		else:
			from postinstall import postuninstall
			# Yeah, yeah - its actually pre-uninstall
			if cmd.root:
				postuninstall(prefix=change_root(cmd.root, cmd.prefix))
			else:
				postuninstall(prefix=cmd.prefix)

		removed = []
		visited = []

		if os.path.exists(recordfile_name):
			paths = [(change_root(cmd.root, line.rstrip("\n")) if cmd.root else
				line.rstrip("\n")) for line in open(recordfile_name, "r")]
		else:
			paths = []
		if not paths:
			# If the installed files have not been recorded, use some fallback
			# logic to find them
			paths = safe_glob(os.path.join(cmd.install_scripts, name))
			if sys.platform == "win32":
				if setuptools:
					paths += safe_glob(os.path.join(cmd.install_scripts,
													name + ".exe"))
					paths += safe_glob(os.path.join(cmd.install_scripts,
													name + "-script.py"))
				else:
					paths += safe_glob(os.path.join(cmd.install_scripts,
													name + ".cmd"))
			paths += safe_glob(os.path.join(cmd.install_scripts, name +
											"_postinstall.py"))
			for attrname in [
				"data",
				"headers",
				"lib",
				"libbase",
				"platlib",
				"purelib"
			]:
				path = os.path.join(getattr(cmd, "install_" + attrname), name)
				if not path in paths:
					# Using sys.version in this way is consistent with
					# setuptools
					paths += safe_glob(path) + safe_glob(path +
						("-%(version)s-py%(pyversion)s*.egg" % {
							"version": version,
							"pyversion": sys.version[:3]
						})
					) + safe_glob(path +
						("-%(version)s-py%(pyversion)s*.egg-info" % {
							"version": version,
							"pyversion": sys.version[:3]
						})
					)
			if os.path.isabs(data) and not data in paths:
				for fname in [
					"lang",
					"presets",
					"ref",
					"report",
					"screenshots",
					"tests",
					"theme",
					"ti1",
					"x3d-viewer",
					"CHANGES.html",
					"LICENSE.txt",
					"README.html",
					"README-fr.html",
					"beep.wav",
					"cacert.pem",
					"camera_shutter.wav",
					"ColorLookupTable.fx",
					name.lower() + ".desktop",
					name.lower() + "-3dlut-maker.desktop",
					name.lower() + "-curve-viewer.desktop",
					name.lower() + "-profile-info.desktop",
					name.lower() + "-scripting-client.desktop",
					name.lower() + "-synthprofile.desktop",
					name.lower() + "-testchart-editor.desktop",
					"pnp.ids",
					"quirk.json",
					"linear.cal",
					"test.cal"
				]:
					path = os.path.join(data, fname)
					if not path in paths:
						paths += safe_glob(path)
			if os.path.isabs(doc) and not doc in paths:
				for fname in [
					"screenshots",
					"theme",
					"CHANGES.html",
					"LICENSE.txt",
					"README.html",
					"README-fr.html"
				]:
					path = os.path.join(doc, fname)
					if not path in paths:
						paths += safe_glob(path)
			if sys.platform == "win32":
				from postinstall import get_special_folder_path
				startmenu_programs_common = get_special_folder_path(
					"CSIDL_COMMON_PROGRAMS")
				startmenu_programs = get_special_folder_path("CSIDL_PROGRAMS")
				for path in (startmenu_programs_common, startmenu_programs):
					if path:
						for filename in (name, "CHANGES", "LICENSE", "README",
										 "Uninstall"):
							paths += safe_glob(os.path.join(path, name,
															filename + ".lnk"))

		for path in paths:
			if os.path.exists(path):
				if path in visited:
					continue
				else:
					visited.append(path)
				if dry_run:
					print(path)
					continue
				try:
					if os.path.isfile(path):
						os.remove(path)
					elif os.path.isdir(path):
						os.rmdir(path)
				except Exception as exception:
					print("could'nt remove", path)
					print("   ", exception)
				else:
					print("removed", path)
					removed.append(path)
			while path != os.path.dirname(path):
				# remove parent directories if empty
				# could also use os.removedirs(path) but we want some status
				# info
				path = os.path.dirname(path)
				if os.path.isdir(path):
					if len(os.listdir(path)) == 0:
						if path in visited:
							continue
						else:
							visited.append(path)
						if dry_run:
							print(path)
							continue
						try:
							os.rmdir(path)
						except Exception as exception:
							print("could'nt remove", path)
							print("   ", exception)
						else:
							print("removed", path)
							removed.append(path)
					else:
						break

		if not removed:
			print(len(visited), "entries found")
		else:
			print(len(removed), "entries removed")

	else:

		# To have a working sdist and bdist_rpm when using distutils,
		# we go to the length of generating MANIFEST.in from scratch everytime,
		# using the information available from setup.
		manifest_in = ["# This file will be re-generated by setup.py - do not"
					   "edit"]
		manifest_in.extend(["include LICENSE.txt", "include MANIFEST",
							"include MANIFEST.in", "include README.html",
							"include README-fr.html", "include CHANGES.html",
							"include %s*.pyw" % name, "include %s-*.pyw" % name,
							"include %s-*.py" % name, "include use-distutils"])
		manifest_in.append("include " + os.path.basename(sys.argv[0]))
		manifest_in.append("include " +
						   os.path.splitext(os.path.basename(sys.argv[0]))[0] +
						   ".cfg")
		for datadir, datafiles in attrs.get("data_files", []):
			for datafile in datafiles:
				manifest_in.append("include " + (
								   relpath(os.path.sep.join(datafile.split("/")),
										   basedir) or datafile))
		for extmod in attrs.get("ext_modules", []):
			manifest_in.extend("include " + os.path.sep.join(src.split("/"))
							   for src in extmod.sources)
		for pkg in attrs.get("packages", []):
			pkg = os.path.join(*pkg.split("."))
			pkgdir = os.path.sep.join(attrs.get("package_dir",
												{}).get(pkg, pkg).split("/"))
			manifest_in.append("include " + os.path.join(pkgdir, "*.py"))
			manifest_in.append("include " + os.path.join(pkgdir, "*.pyd"))
			manifest_in.append("include " + os.path.join(pkgdir, "*.so"))
			for obj in attrs.get("package_data", {}).get(pkg, []):
				manifest_in.append("include " + os.path.sep.join([pkgdir] +
																 obj.split("/")))
		for pymod in attrs.get("py_modules", []):
			manifest_in.append("include " + os.path.join(*pymod.split(".")))
		manifest_in.append("include " +
						   os.path.join(name, "theme", "theme-info.txt"))
		manifest_in.append("recursive-include %s %s %s" %
						   (os.path.join(name, "theme", "icons"),
						   "*.icns", "*.ico"))
		manifest_in.append("include " + os.path.join("man", "*.1"))
		manifest_in.append("recursive-include %s %s" % ("misc", "*"))
		if skip_instrument_conf_files:
			manifest_in.extend([
				"exclude misc/Argyll",
				"exclude misc/*.rules",
				"exclude misc/*.usermap",
			])
		manifest_in.append("include " + os.path.join("screenshots", "*.png"))
		manifest_in.append("include " + os.path.join("scripts", "*"))
		manifest_in.append("include " + os.path.join("tests", "*"))
		manifest_in.append("recursive-include %s %s" % ("theme", "*"))
		manifest_in.append("recursive-include %s %s" % ("util",
														"*.cmd *.py *.sh"))
		if sys.platform == "win32" and not setuptools:
			# Only needed under Windows
			manifest_in.append("global-exclude .svn/*")
		manifest_in.append("global-exclude *~")
		manifest_in.append("global-exclude *.backup")
		manifest_in.append("global-exclude *.bak")
		if not dry_run:
			manifest = open("MANIFEST.in", "w")
			manifest.write("\n".join(manifest_in))
			manifest.close()
			if os.path.exists("MANIFEST"):
				os.remove("MANIFEST")

		if bdist_bbfreeze:
			i = sys.argv.index("bdist_bbfreeze")
			if not "-d" in sys.argv[i + 1:] and \
			   not "--dist-dir" in sys.argv[i + 1:]:
				dist_dir = os.path.join(pydir, "..", "dist",
										"bbfreeze.%s-py%s" % (get_platform(),
															  sys.version[:3]))
				sys.argv.insert(i + 1, "--dist-dir=" + dist_dir)
			if not "egg_info" in sys.argv[1:i]:
				sys.argv.insert(i, "egg_info")

		if do_py2app or do_py2exe:
			sys.path.insert(1, pydir)
			i = sys.argv.index("py2app" if do_py2app else "py2exe")
			if not "build_ext" in sys.argv[1:i]:
				sys.argv.insert(i, "build_ext")

		setup(**attrs)

		if dry_run or help:
			return

		if do_py2app:
			frameworks_dir = os.path.join(dist_dir, name + ".app",
										  "Contents", "Frameworks")
			lib_dynload_dir = os.path.join(dist_dir, name + ".app", "Contents",
										   "Resources", "lib", "python%s.%s" %
										   sys.version_info[:2], "lib-dynload")
			# Fix Pillow (PIL) dylibs not being included
			pil_dylibs = os.path.join(lib_dynload_dir, "PIL", ".dylibs")
			if not os.path.isdir(pil_dylibs):
				import PIL
				pil_installed_dylibs = os.path.join(os.path.dirname(PIL.__file__),
													".dylibs")
				print("Copying", pil_installed_dylibs, "->", pil_dylibs)
				shutil.copytree(pil_installed_dylibs,
								pil_dylibs)
				for entry in os.listdir(pil_dylibs):
					print(os.path.join(pil_dylibs, entry))
				# Remove wrongly included frameworks
				dylibs_entries = os.listdir(pil_installed_dylibs)
				for entry in os.listdir(frameworks_dir):
					if entry in dylibs_entries:
						dylib = os.path.join(frameworks_dir, entry)
						print("Removing", dylib)
						os.remove(dylib)
			import wx
			if wx.VERSION >= (4, ):
				# Fix wxPython 4 dylibs being included in wrong location
				wx_dylibs = os.path.join(lib_dynload_dir, "wx")
				for entry in os.listdir(frameworks_dir):
					if entry.startswith("libwx"):
						dylib = os.path.join(frameworks_dir, entry)
						lib_dylib = os.path.join(wx_dylibs, entry)
						print("Moving", dylib, "->", lib_dylib)
						shutil.move(dylib, lib_dylib)

			create_app_symlinks(dist_dir, scripts)

		if do_py2exe:
			shutil.copy(os.path.join(dist_dir, "python%s.dll" %
											   (sys.version[0] + sys.version[2])),
						os.path.join(dist_dir, "lib", "python%s.dll" %
											   (sys.version[0] + sys.version[2])))

		if ((bdist_bbfreeze and sys.platform == "win32") or do_py2exe) and \
		   sys.version_info[:2] >= (2,6):
			from vc90crt import name as vc90crt_name, vc90crt_copy_files
			if do_py2exe:
				vc90crt_copy_files(dist_dir)
				vc90crt_copy_files(os.path.join(dist_dir,
												"lib"))
			else:
				vc90crt_copy_files(os.path.join(dist_dir,
												name + "-" + version))

		if do_full_install and not is_rpm_build and not skip_postinstall:
			from postinstall import postinstall
			if sys.platform == "win32":
				path = os.path.join(cmd.install_lib, name)
				# Using sys.version in this way is consistent with setuptools
				for path in safe_glob(path) + safe_glob(
					os.path.join(path + (
						"-%(version)s-py%(pyversion)s*.egg" %
						{
							"version": version,
							"pyversion": sys.version[:3]
						}
					), name)
				):
					if cmd.root:
						postinstall(prefix=change_root(cmd.root, path))
					else:
						postinstall(prefix=path)

			elif cmd.root:
				postinstall(prefix=change_root(cmd.root, cmd.prefix))
			else:
				postinstall(prefix=cmd.prefix)

if __name__ == "__main__":
	setup()


import cv2
import numpy as np

from tracker import Tracker

VIDEO_NAME = "best_video.mp4"
TRACKER_THRESHOLD = 10

object_detector = cv2.createBackgroundSubtractorMOG2(
        varThreshold=TRACKER_THRESHOLD)
object_tracker = Tracker()

cap = cv2.VideoCapture(VIDEO_NAME)
VIDEO_WIDTH = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
VIDEO_HEIGHT = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
RESIZE_DIM = (VIDEO_HEIGHT, VIDEO_HEIGHT)
DIFFERENCE_THRESHOLD = 500
CENTER_COORDS = (VIDEO_WIDTH // 2, VIDEO_HEIGHT // 2)

def crop(frame: np.array, center: tuple[int, int], width: int, height: int):
    left_bound = center[0] - width // 2
    right_bound = center[0] + width // 2
    upper_bound = center[1] + height // 2
    lower_bound = center[1] - height // 2

    return frame[lower_bound:upper_bound, left_bound:right_bound]

def frame_difference(frame1: np.array, frame2: np.array):
    img1 = cv2.cvtColor(frame1, cv2.COLOR_RGB2GRAY)
    img2 = cv2.cvtColor(frame2, cv2.COLOR_RGB2GRAY)

    result = (abs(img2 - img1)).sum()
    return result

ret, frame = cap.read()
frame = crop(frame, CENTER_COORDS, VIDEO_HEIGHT + 800, VIDEO_HEIGHT)

while True:
    last_frame = frame
    ret, frame = cap.read()

    if not ret:
        break

    frame = crop(frame, CENTER_COORDS, VIDEO_HEIGHT + 800, VIDEO_HEIGHT)

    if frame_difference(last_frame, frame) < DIFFERENCE_THRESHOLD:
        continue

    # contrast detection not canny
    mask = object_detector.apply(frame)
    contours, _ = cv2.findContours(mask, cv2.RETR_TREE,
                                   cv2.CHAIN_APPROX_SIMPLE)
    big_contours = []

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 3000:
            M = cv2.moments(cnt)
            cX = M["m10"] / M["m00"]
            if cX < VIDEO_WIDTH - TRACKER_THRESHOLD:
                big_contours.append(cnt)
                cv2.drawContours(frame, [cnt], -1, (0, 0, 255), 2)

    object_tracker.update(big_contours)
    print(object_tracker.cell_dict)

    cv2.imshow("Frame", object_tracker.show_contour_ids(frame))

    key = cv2.waitKey(100)

    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()


from .models import Category, Photo
from django.forms import ModelForm
from django import forms
# from django.forms.widgets import TextInput, Textarea

class CategoryForm(ModelForm):
	name = forms.CharField(
		widget=forms.TextInput(
			attrs={
				'placeholder' : 'Update Category Name..'
			}
		)
	)

	class Meta:
		model = Category
		fields = '__all__'

class PhotoForm(ModelForm):

	description = forms.CharField(
		required=False,
		widget=forms.TextInput(
			attrs={
				'class': 'form-control',
			}
		)
	)

	class Meta:
		model = Photo
		fields = '__all__'


from asyncio import CancelledError
import logging as lg

from typing import AsyncGenerator

from meow.app.config import conf
from meow.app.instances.databases import dbs
from meow.models.infra.locks import RedisLock

from redis.exceptions import LockError

from meow.models.local.event.final_proceedings.contribution_model import ContributionData
from meow.models.local.event.final_proceedings.proceedings_data_model import FinalProceedingsConfig, ProceedingsData

from meow.services.local.event.final_proceedings.collecting_contributions_and_files import (
    collecting_contributions_and_files)
from meow.services.local.event.final_proceedings.collecting_sessions_and_attachments import (
    collecting_sessions_and_attachments)

from meow.services.local.event.common.adapting_final_proceedings import adapting_final_proceedings
from meow.services.local.event.common.validate_proceedings_data import validate_proceedings_data

from meow.services.local.event.final_proceedings.concat_contribution_papers import concat_contribution_papers
from meow.services.local.event.final_proceedings.copy_contribution_papers import copy_contribution_papers
from meow.services.local.event.final_proceedings.copy_contribution_slides import copy_contribution_slides
from meow.services.local.event.final_proceedings.copy_event_attachments import copy_event_attachments

from meow.services.local.event.final_proceedings.download_contributions_slides import download_contributions_slides
from meow.services.local.event.final_proceedings.download_event_attachments import download_event_attachments
from meow.services.local.event.final_proceedings.download_contributions_papers import download_contributions_papers

from meow.services.local.event.final_proceedings.generate_contribution_references import (
    generate_contribution_references)
from meow.services.local.event.final_proceedings.generate_contributions_groups import generate_contributions_groups
from meow.services.local.event.final_proceedings.generate_contribution_doi import generate_dois
from meow.services.local.event.final_proceedings.build_doi_payloads import build_doi_payloads
from meow.services.local.event.final_proceedings.manage_duplicates import manage_duplicates

from meow.services.local.event.final_proceedings.link_static_site import (
    clean_static_site, link_static_site)
from meow.services.local.event.final_proceedings.read_papers_metadata import read_papers_metadata
from meow.services.local.event.final_proceedings.write_papers_metadata import write_papers_metadata

from meow.services.local.event.final_proceedings.hugo_plugin.hugo_final_proceedings_plugin import (
    HugoFinalProceedingsPlugin)
from meow.models.local.event.final_proceedings.client_log import ClientLog, ClientLogSeverity
from meow.app.errors.service_error import ProceedingsError

logger = lg.getLogger(__name__)

async def event_final_proceedings(event: dict, cookies: dict, settings: dict,
                                  config: FinalProceedingsConfig) -> AsyncGenerator:
    """ """

    try:
        event_id: str = event.get('id', '')

        if not event_id or event_id == '':
            raise BaseException('Invalid event id')

        async with acquire_lock(event_id) as lock:

            logger.debug(f"acquire_lock -> {lock.name}")

            async for r in _event_final_proceedings(event, cookies, settings, config, lock):
                yield r

            logger.debug(f"release_lock -> {lock.name}")

    except GeneratorExit:
        logger.error("Generator Exit")
    except CancelledError:
        logger.error("Task Cancelled")
    except LockError as le:
        logger.error("Lock error", exc_info=True)
        raise le
    except ProceedingsError as pe:
        async for r in handle_proceedings_error(pe):
            yield r
    except BaseException as be:
        logger.error("Generic error", exc_info=True)
        raise be

def acquire_lock(key: str) -> RedisLock:
    """ Create event lock """

    redis_lock = RedisLock(
        redis=dbs.redis_client,
        name=conf.REDIS_EVENT_LOCK_KEY(key),
        timeout=conf.REDIS_LOCK_TIMEOUT_SECONDS,
        sleep=0.5,
        blocking=True,
        blocking_timeout=conf.REDIS_LOCK_BLOCKING_TIMEOUT_SECONDS,
        thread_local=True,
    )

    return redis_lock

async def extend_lock(lock: RedisLock) -> RedisLock:
    """ Reset lock timeout (conf.REDIS_LOCK_TIMEOUT_SECONDS) """

    await lock.reacquire()
    return lock

async def _event_final_proceedings(event: dict, cookies: dict, settings: dict,
                                   config: FinalProceedingsConfig, lock: RedisLock) -> AsyncGenerator:
    """ """

    logger.info('event_final_proceedings - create_final_proceedings')

    """ """

    def filter_contributions_pubblicated(c: ContributionData) -> bool:
        if config.include_only_qa_green_contributions:
            return c.is_included_in_proceedings
        return c.is_included_in_prepress

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='collecting_sessions_and_attachments',
        text="Collecting sessions and attachments"
    ))

    # Bloccante

    [sessions, attachments] = await collecting_sessions_and_attachments(event, cookies, settings)

    # log number of sessions and attachments
    yield dict(type='log', value=ClientLog(
        severity=ClientLogSeverity.INFO,
        message=f'Found {len(sessions)} sessions.'
    ))

    yield dict(type='log', value=ClientLog(
        severity=ClientLogSeverity.INFO,
        message=f'Found {len(attachments)} attachments.'
    ))

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='collecting_contributions_and_files',
        text="Collecting contributions and files"
    ))

    # Bloccante

    [contributions] = await collecting_contributions_and_files(event, sessions, cookies, settings)

    # log number of contributions
    yield dict(type='log', value=ClientLog(
        severity=ClientLogSeverity.INFO,
        message=f'Found {len(contributions)} contributions.'
    ))

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='adapting_final_proceedings',
        text="Adapting final proceedings"
    ))

    # Bloccante

    final_proceedings = await adapting_final_proceedings(event, sessions, contributions, attachments, cookies, settings)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='clean_static_site',
        text='Clean Static site'
    ))

    await clean_static_site(final_proceedings, cookies, settings, config)

    """ """

    try:

        await extend_lock(lock)

        yield dict(type='progress', value=dict(
            phase='download_event_attachments',
            text="Download event attachments"
        ))

        # Bloccante

        await download_event_attachments(final_proceedings, cookies, settings)

    except Exception as ex:
        logger.error(ex, exc_info=True)

        # Produzione logs

        # Produzione result
        yield dict(type='result', value=dict(
            # metadata=metadata,
            # errors=errors
        ))

        # Se l'errore è bloccante
        return

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='download_contributions_papers',
        text="Download Contributions Papers"
    ))

    # Bloccante

    [final_proceedings, papers_data] = await download_contributions_papers(final_proceedings, cookies, settings,
                                                                           filter_contributions_pubblicated)

    # log number of files
    yield dict(type='log', value=ClientLog(
        severity=ClientLogSeverity.INFO,
        message=f'Downloaded {len(papers_data)} papers.'
    ))

    """ """

    if config.include_event_slides:

        await extend_lock(lock)

        yield dict(type='progress', value=dict(
            phase='download_contributions_slides',
            text="Download Contributions Slides"
        ))

        # Bloccante

        [final_proceedings, slides_data] = await download_contributions_slides(final_proceedings,
                                                                               cookies, settings)

        # log number of files
        yield dict(type='log', value=ClientLog(
            severity=ClientLogSeverity.INFO,
            message=f'Downloaded {len(slides_data)} slides.'
        ))

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='read_papers_metadata',
        text='Read Papers Metadata'
    ))

    # Bloccante

    await read_papers_metadata(final_proceedings, cookies, settings,
                               filter_contributions_pubblicated)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='validate_contributions_papers',
        text='Validate Contributions Papers'
    ))

    # Bloccante il processo di validazione
    # Mentre il risultato della validazione
    # è bloccante se strict_pdf_check

    [metadata, errors] = await validate_proceedings_data(final_proceedings, cookies, settings,
                                                         filter_contributions_pubblicated)

    if len(errors) > 0:
        if config.strict_pdf_check:

            yield dict(type='log', value=ClientLog(
                severity=ClientLogSeverity.ERROR,
                message='Errors when validating proceedings data.'
            ))

            yield dict(type='result', value=dict(
                metadata=metadata,
                errors=errors
            ))

            return

        else:
            yield dict(type='log', value=ClientLog(
                severity=ClientLogSeverity.WARNING,
                message='Errors when validating proceedings data.'
            ))

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='extract_contribution_references',
        text='Extract Contribution References'
    ))

    # Bloccante

    await generate_contribution_references(final_proceedings, cookies, settings, config,
                                           filter_contributions_pubblicated)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='generate_dois',
        text='Generate DOIs'
    ))

    # Bloccante

    await generate_dois(final_proceedings, cookies, settings, config,
                        filter_contributions_pubblicated)

    """ """

    if config.generate_doi_payload:

        await extend_lock(lock)

        yield dict(type='progress', value=dict(
            phase='generate_doi_payloads',
            text='Generate DOI payloads'
        ))

        # Bloccante

        # generation of payloads for DOIs
        await build_doi_payloads(final_proceedings)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='manage_duplicates',
        text='Managing duplicates'
    ))

    # Bloccante

    await manage_duplicates(final_proceedings, settings)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='write_papers_metadata',
        text='Write Papers Metadata'
    ))

    # Bloccante

    await write_papers_metadata(final_proceedings, cookies, settings, filter_contributions_pubblicated)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='generate_contributions_groups',
        text='Generate Contributions Groups'
    ))

    await generate_contributions_groups(final_proceedings, cookies, settings)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='concat_contribution_papers',
        text='Concat Contributions Papers'
    ))

    await concat_contribution_papers(final_proceedings, cookies, settings, config, filter_contributions_pubblicated)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='generate_site_pages',
        text='Generate Site Pages'
    ))

    plugin = HugoFinalProceedingsPlugin(
        final_proceedings, cookies, settings, config)

    await plugin.run_prepare()
    await plugin.run_build()

    """ """

    await extend_lock(lock)

    logger.info('event_final_proceedings - copy_event_attachments')

    yield dict(type='progress', value=dict(
        phase='copy_event_pdf',
        text='Copy event PDF'
    ))

    await copy_event_attachments(final_proceedings, cookies, settings)
    await copy_contribution_papers(final_proceedings, cookies, settings, filter_contributions_pubblicated)

    if config.include_event_slides:
        await copy_contribution_slides(final_proceedings, cookies, settings)

    """ """

    # await extend_lock(lock)

    # yield dict(type='progress', value=dict(
    #     phase='clean_static_site_2',
    #     text='Clean Static site'
    # ))

    # await clean_pdf_cache(final_proceedings, cookies, settings, config)

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='generate_final_proceedings',
        text='Generate Final Proceedings'
    ))

    await plugin.generate()

    """ """

    await extend_lock(lock)

    yield dict(type='progress', value=dict(
        phase='link_static_site',
        text='Link Static site'
    ))

    await link_static_site(final_proceedings, cookies, settings, config)

    """ """

    await extend_lock(lock)

    logger.info('event_final_proceedings - get_final_proceedings')

    result = await get_final_proceedings(final_proceedings)

    yield result

async def get_final_proceedings(final_proceedings: ProceedingsData) -> dict:
    """ """

    event_code = final_proceedings.event.id
    event_name = final_proceedings.event.name
    event_title = final_proceedings.event.title
    event_path = final_proceedings.event.path

    return dict(
        type='result',
        value=dict(
            event_code=event_code,
            event_name=event_name,
            event_title=event_title,
            event_path=event_path
        )
    )

async def handle_proceedings_error(error: ProceedingsError):
    """ Handle proceedings error """

    yield dict(type='log', value=ClientLog(
        severity=ClientLogSeverity.ERROR,
        message=str(error)
    ))

    # stop generation
    yield dict(type='result', value=dict())

    raise error


from django.shortcuts import render
from .models import Item
from .forms import ItemSearchForm
from django.db.models import Q
def search_alter(request):
    if request.method == 'POST':
        try:
            Length = request.POST.get('length')
            Force = request.POST.get('T_Force')
            Dia = request.POST.get('Dia_dr')
            print(Length, Force, Dia)
            results = Item.objects.filter(length=Length, Dia_dr = Dia, T_Force__gt=Force)
            print(results)
        except ValueError:
            return render(request, 'error.html')

        if results.exists():
            mapcodes = [r.map_code for r in results]
            weights = [r.T_Weight for r in results]
            weights_J = [r.T_Weight_J for r in results]

            return render(request, 'results_alter.html', {'weights': weights, 'weights_J': weights_J, 'mapcodes': mapcodes})
        else:
            # print(length)
            # print(T_Force)
            return render(request, 'no_results.html')
    return render(request, 'search_alter.html')

from django.shortcuts import render
from .models import Item

def show_all_data(request):
    # 从数据库中获取所有数据
    all_data = Item.objects.all()
    # 将数据传递到模板中进行渲染
    return render(request, 'all_data.html', {'data': all_data})

# 假设这样一种情况，我已经用django开发了一个网页，并且他可以对我本地的数据库的一张表单进行一些基本的筛选工作，我在我的models.py里
# 用meta函数提到了这张表，那现在如果我想换一张表应该怎么操作呢，我并不是需要简单的在models.py里更改表单，而是通过用户的要求来选择应该使用哪张表单
# 大致的情况是这样，用户在网页上选择要对a或者b进行筛选，而a和b分别对应我本地数据库的表，如果用户选择a那么就对a表进行筛选操作，此外a，b量表的数据类型是相同的 只是数值不同，所以我希望他们可以共用一个筛选函数

# 工作流程: 多app方向 字典查阅 ---> 写出父类class --->


#!/usr/bin/python
import footgen

cNumber = 4

f = footgen.Footgen("MOLEX_RJ45_TRAV","geda")

w = 15.75
h = 14.99
y = -2.42

bDrill = 3.25
bTic = 0
bX = 12.7 /2

cDrill = 0.89
cTic = 0.7
cPitch = 1.02
cX0 = 3.81
cX1 = 2.79
cY0 = -2.54
cY1 = -4.32

m = 1
n = 2
for i in range(cNumber):
	f.add_pin("%d"%m, cX0, cY0, cDrill, cDrill+cTic)
	f.add_pin("%d"%n, cX1, cY1, cDrill, cDrill+cTic)
	m += 2
	n += 2
	cX0 -= cPitch*2
	cX1 -= cPitch*2

f.add_pin("9", -bX, 0, bDrill, bDrill+bTic)
f.add_pin("9", +bX, 0, bDrill, bDrill+bTic)

# left
f.generator.silk_line(-0.5*w, -0.5*h+y, -0.5*w, 0.5*h+y)
# right
f.generator.silk_line(0.5*w, -0.5*h+y, 0.5*w, 0.5*h+y)
# bottom
f.generator.silk_line(-0.5*w, 0.5*h+y, 0.5*w, 0.5*h+y)
# top
f.generator.silk_line(-0.5*w, -0.5*h+y, 0.5*w, -0.5*h+y)

f.finish()


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

import tempfile
from itertools import islice
from pathlib import Path
import numpy as np
from tempfile import TemporaryDirectory

import pytest
from crystals import Crystal, Atom, __version__
from crystals.writers import CIF_HEADER

try:
    import ase
except ImportError:
    WITH_ASE = False
else:
    WITH_ASE = True

@pytest.mark.skipif(not WITH_ASE, reason="ASE not installed or importable")
@pytest.mark.parametrize("name", islice(Crystal.builtins, 10))
def test_ase_atoms_construction(name):
    """Test that ase_atoms returns without error"""
    crystal = Crystal.from_database(name)
    to_ase = crystal.to_ase()
    assert len(crystal) == len(to_ase)

@pytest.mark.skipif(not WITH_ASE, reason="ASE not installed or importable")
@pytest.mark.parametrize("name", islice(Crystal.builtins, 10))
def test_ase_atoms_back_and_forth(name):
    """Test conversion to and from ase Atoms"""
    crystal = Crystal.from_database(name)
    to_ase = crystal.to_ase()
    crystal2 = Crystal.from_ase(to_ase)

    # ase has different handling of coordinates which can lead to
    # rounding beyond 1e-3. Therefore, we cannot compare directly sets
    # assertSetEqual(set(crystal), set(crystal2))
    assert len(crystal) == len(crystal2)

@pytest.mark.parametrize("name", Crystal.builtins)
def test_cif_writer_idempotence(name):
    """Test that conversion to CIF of a structure loaded from CIF is idempotent."""
    # Testing on all built-in structure assures us that corner cases
    # are taken care of.
    cryst = Crystal.from_database(name)
    with tempfile.TemporaryDirectory() as temp_dir:
        f = Path(temp_dir) / "temp.cif"
        cryst.to_cif(f)
        cryst2 = Crystal.from_cif(f)
        assert cryst == cryst2

def test_cif_writer_writes_version():
    """Test that the `crystals` version is contained in the CIF header."""
    # See https://github.com/LaurentRDC/crystals/issues/14
    assert f"`crystals` {__version__}" in CIF_HEADER

def test_supercell_preserved_in_cif():
    """See issue #13."""
    a = np.asfarray([3, 0.2, 0])
    b = np.asfarray([0.4, 8, 0])
    c = np.asfarray([0, 0, 9])

    dimer = Crystal(
        unitcell=[Atom("C", coords=(0.5, 0, 0)), Atom("C", coords=(0, 0, 0))],
        lattice_vectors=[a * 2, b, c],
    )
    with TemporaryDirectory() as tmpdir:
        dimer.to_cif(Path(tmpdir) / "dimer.cif")
        from_file = Crystal.from_cif(Path(tmpdir) / "dimer.cif")

    assert set(tuple(atm.coords_fractional) for atm in dimer.unitcell) == set(
        tuple(atm.coords_fractional) for atm in from_file.unitcell
    )

@pytest.mark.parametrize("name", Crystal.builtins)
def test_vasp_writer_idempotence(name):
    """Test that conversion to VASP of a structure loaded from VASP is idempotent."""
    # Testing on all built-in structure assures us that corner cases
    # are taken care of.
    cryst = Crystal.from_database(name)
    with tempfile.TemporaryDirectory() as temp_dir:
        f = Path(temp_dir) / "temp.POSCAR"
        cryst.to_poscar(f)
        cryst2 = Crystal.from_poscar(f)
        assert cryst == cryst2


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

# First do a simple sampling. We sample two images from different folders randomly.If these two images are from the same folder, we label it as 1(True), else 0 (False)
# Build a n-ary tree to store the path and nparray of pictures so it will be easier for to manage.

class nTreeNode:
    def __init__(self, fname):
        self.path =fname
        self.lastdir = False
        self.children = []

def generate_ntree(rootdir):
    """
    :type rootdir: String(path of current file/dir)
    :rtype: nTreeNode
    """
    root = nTreeNode(rootdir)
    def router(node):
        if os.path.isdir(node.path):
            for f in os.listdir(node.path):
                curpath = node.path + '/' + f
                if os.path.isdir(curpath):
                     newnode = nTreeNode(curpath)
                     node.children.append(newnode)
                     router(newnode)
                else:
                    if curpath.endswith('.pgm'):
                        newnode = nTreeNode(curpath)
                        node.lastdir = True
                        node.children.append(newnode)
    router(root)
    return root

def sampling(root, num, same_label):
    """
    :type root: nTrereNode
    :type num: int(Time of sampling)
    :type same_label: bool(sample in the same lastdir or not)
    :rtype: pandas.DataFrame
    """
    paths = []
    def traveller(start):
        if start.lastdir == False:
            for p in start.children:
                traveller(p)
        else:
            paths.append(start)
    traveller(root)

    df = pd.DataFrame(columns = ("img1", "img2", "same_face"))
    if same_label == True:
        for _ in range(num):
            idx = random.randint(0, len(paths) - 1)
            curnode = paths[idx]
            l = len(curnode.children)
            imgidx1 = random.randint(0, l - 1)
            imgidx2 = random.randint(0, l - 1)
            img1 = curnode.children[imgidx1].path
            img2 = curnode.children[imgidx2].path
            df = df.append({"img1": img1, "img2": img2, "same_face": 1}, ignore_index=True)
        return df
    else:
        if len(paths) < 2:
            print("Invalid number of folders")
            return
        for _ in range(num):
            img1_path = random.randint(0, len(paths) - 1)
            img2_path = random.randint(0, len(paths) - 1)
            while img1_path == img2_path:
                img2_path = random.randint(0, len(paths) - 1)
            img1_parent = paths[img1_path]
            img2_parent = paths[img2_path]
            img1 = img1_parent.children[random.randint(0, len(img1_parent.children) - 1)].path
            img2 = img2_parent.children[random.randint(0, len(img2_parent.children) - 1)].path
            df = df.append({"img1": img1, "img2": img2, "same_face": 0}, ignore_index=True)
        return df

def export_files(file_tree, total_num, shuffle = True):
    """
    Generate training and test set with 8:2 principle.
    Half of data are True and another half are False
    """
    half_train = int(total_num * 0.4)
    half_test = int(total_num * 0.1)
    train_1, train_2 = sampling(file_tree, half_train, True), sampling(file_tree, half_train, False)
    df_train = pd.concat([train_1, train_2])
    test_1, test_2 = sampling(file_tree, half_test, True), sampling(file_tree, half_test, False)
    df_test = pd.concat([test_1, test_2])
    if not os.path.exists('./middleware'):
        os.mkdir('./middleware')
    if shuffle:
        df_train = df_train.sample(frac=1).reset_index(drop=True)
        df_test = df_test.sample(frac=1).reset_index(drop=True)
    df_train.to_csv('./middleware/train.csv', index=False)
    df_test.to_csv('./middleware/test.csv', index=False)
    print('Finished generating training and test set \n')
    print('Training size: ' + str(half_train * 2) + '\n')
    print('Test size: ' + str(half_test * 2) + '\n')


"""
Дано ціле число N (> 1). Знайти найменше ціле число K, при якому виконується нерівність 3K> N.
"""

N = int(input("Введите число:"))
K = 1

if N <= 1:
    print("Введено неверное значение")
while 3*K <= N:
    K += 1
print("Наименьшее число при котором выполняется неравность (3K > N) будет " + str(K))


import os

import click
import pandas as pd
from sklearn.model_selection import train_test_split

@click.command("split")
@click.option("--input_dir")
def split_data(input_dir):
    X = pd.read_csv(os.path.join(input_dir, "data_normalized.csv"))
    y = pd.read_csv(os.path.join(input_dir, "target.csv"))
    X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=123)

    X_train.to_csv(os.path.join(input_dir, "train_data.csv"), index=False)
    y_train.to_csv(os.path.join(input_dir, "train_target.csv"), index=False)
    X_val.to_csv(os.path.join(input_dir, "val_data.csv"), index=False)
    y_val.to_csv(os.path.join(input_dir, "val_target.csv"), index=False)

if __name__ == '__main__':
    split_data()