from django.test import TestCase
from django.core.exceptions import ValidationError
from payments.models import Payment

class PaymentModelTestCase(TestCase):
    def create_payment(self):
        payment = Payment.objects.create(
            name="Test Payment",
            merchant="12345678-1234-1234-1234-123456789012",
            types="zarinpal",
            available=True
        )
        return payment

    def test_payment_creation(self):
        self.payment = self.create_payment()
        self.assertIsInstance(self.payment, Payment)
        self.assertEqual(self.payment.name, "Test Payment")
        self.assertEqual(self.payment.merchant,
                         "12345678-1234-1234-1234-123456789012")
        self.assertEqual(self.payment.types, "zarinpal")
        self.assertTrue(self.payment.available)

    def test_payment_str_representation(self):
        self.payment = self.create_payment()
        expected_str = "Test Payment: Zarinpal Payment Gateway"
        self.assertEqual(str(self.payment), expected_str)

    def test_payment_save_invalid_merchant(self):
        self.payment = self.create_payment()
        invalid_merchant = "invalid_merchant_id"
        payment = Payment(
            name="Invalid Payment",
            merchant=invalid_merchant,
            types="zarinpal",
            available=True
        )
        with self.assertRaises(ValueError):
            payment.save()

    def test_payment_save_valid_merchant(self):
        valid_merchant = "87654321-4321-4321-4321-210987654321"
        payment = Payment(
            name="Valid Payment",
            merchant=valid_merchant,
            types="zarinpal",
            available=True
        )
        payment.save()
        self.assertEqual(payment.merchant, valid_merchant)

    def test_payment_verbose_names(self):
        self.assertEqual(Payment._meta.verbose_name, "Payment")
        self.assertEqual(Payment._meta.verbose_name_plural, "Payments")

    def test_payment_invalid_type(self):
        invalid_type = "invalid_type"
        with self.assertRaises(ValidationError):
            payment = Payment(
                name="Invalid Payment",
                merchant="12345678-1234-1234-1234-123456789012",
                types=invalid_type,
                available=True
            )
            payment.full_clean()


from django.conf.urls import include,url,patterns
from . import views
import django.contrib.auth.views as auth_views

urlpatterns = [
	url(r'^$', views.index, name='index'),
	url(r'^about-us/$', views.about_us, name='about_us'),
	url(r'^members/$', views.members, name='members'),
	url(r'^achievements/$', views.achievements, name='achievements'),
	url(r'^projects/$', views.our_projects, name='our_projects'),
	url(r'^tutorials/$', views.tutorials, name='tutorials'),
	url(r'^support-us/$', views.support_us, name='support_us'),
	url(r'^members/alumni/$', views.alumni, name='alumni'),
	url(r'^members/active/$', views.active_members, name='active_members'),
	url(r'^projects/ongoing/$', views.ongoing_projects, name='ongoing_projects'),
	url(r'^projects/completed/$', views.completed_projects, name='completed_projects'),
    url(r'^login/',auth_views.login, name="auth_views.login"),
    url(r'^home/', views.index, name='index'),
    url(r'^logout/$', views.logout_page),
	url(r'^accounts/login/$',auth_views.login, name="auth_views.login"),
	url(r'^accounts/userprofile/$', views.userprofile, name='userprofile'),
    url(r'^register/$', views.register),
    url(r'^profile/$', views.userprofile, name='userprofile'),
    url(r'^profile/edit/$', views.editprofile, name='editprofile'),
    url(r'^profile/addproject/$', views.addproject, name='addproject'),
    url(r'^profile/editproject/(?P<proj>)/$', views.editproject, name='editproject'),
    url(r'^register/success/$', views.success, name='success'),
    url(r'^register/fill_info/$', views.fill_info, name='fill_info'),
    url(r'^expo/$', views.expo, name='expo'),
]


import os

execname = "TBA.exe"

#basedir = "D:\Downloads\projects\TBA\NEWEST\\"
basedir = os.path.dirname(os.path.realpath(__file__))+"/../../"

makefile = open(basedir+"makefile","w+")

filesources = ["src/ui/","src/tools/","src/common/","src/game/","src/"]

srcs=[]
heads=[]

for dir in filesources:
	srcs.extend([dir+src.split(".")[0] for src in os.listdir(basedir+dir) if src[-4:] == ".cpp"])
	heads.extend([dir+src.split(".")[0] for src in os.listdir(basedir+dir) if src[-2:] == ".h"])

makestr = ""

binlist = ["bin"+src[src.rfind('/'):]+".o" for src in srcs]

makestr += execname+": "+" ".join(binlist)+"\n\tx86_64-w64-mingw32-g++ -std=c++11 "+" ".join(binlist)+" -o "+execname+" -lmingw32 -I/usr/include/SDL2 -L/usr/x86_64-w64-mingw32/lib -lSDL2main -lSDL2 -lSDL2_image -O2 \n\n"

for src in srcs:
	head=""
	if src in heads:
		head = src+".h"
	makestr += "bin/{1}.o: {0}.cpp {2} \n\tx86_64-w64-mingw32-g++ -std=c++11 -c {0}.cpp -o bin/{1}.o -lmingw32 -I/usr/include/SDL2 -L/usr/x86_64-w64-mingw32/lib -lSDL2main -lSDL2 -lSDL2_image -O2\n\n".format(src,src[src.rfind('/')+1:],head)

makefile.write(makestr)
makefile.close()


from django.contrib import admin
from django.urls import path, re_path, include
from django.views.generic import TemplateView
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
    TokenVerifyView
)

urlpatterns = [
    # Django
    path('admin/', admin.site.urls),
    # Api
    path('api/', include('api.urls')),

    # DJOSER/JWT
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.jwt')),

    # Frontend
    re_path(r'^.*', TemplateView.as_view(template_name='index.html'))
]


from evaluation import Evaluation
from data_preprocess import DataPreprocessing
from bayesian_classifier import BayesClassifier_Case1, BayesClassifier_Case2, BayesClassifier_Case3, BayesClassifier_Case4

# Enter the paths of each class data in corresponding variable
path_data_1 = '.../class1.txt'  # Path to class_1 data for a particular dataset
path_data_2 = '.../class2.txt'  # Path to class_2 data for a particular dataset
path_data_3 = '.../class3.txt'  # Path to class_3 data for a particular dataset

""" Instantiate an object of Data Preprocessing Class (read the documentation to understand what it does.) """

data_preprocess = DataPreprocessing(path_data_1, path_data_2, path_data_3, train_size=0.75)

""" Instantiate an object of Bayesian_Classifier Case (read the documentation for more insights.) """

bayes_classifier = BayesClassifier_Case1(data_prep=data_preprocess, train_size=0.70)
# bayes_classifier = BayesClassifier_Case2(data_prep=data_preprocess, train_size=0.70)
# bayes_classifier = BayesClassifier_Case3(data_prep=data_preprocess, train_size=0.70)
# bayes_classifier = BayesClassifier_Case4(data_prep=data_preprocess, train_size=0.70)

""" Plot the decision boundaries between required classes: (Read the documentation.) """

    # Between all three classes.
bayes_classifier.plot_contour(x_min=-500, x_max=2600, y_min=-100, y_max=3000, steps=750, pair_wise=None, train_or_test=0, smoothness=0.1, contour=False)

    # Between class 1 and class 2.
bayes_classifier.plot_contour(x_min=-500, x_max=2600, y_min=-100, y_max=3000, steps=750, pair_wise=[1, 2], train_or_test=0, smoothness=0.1, contour=False)

    # Between class 2 and class 3.
bayes_classifier.plot_contour(x_min=-500, x_max=2600, y_min=-100, y_max=3000, steps=750, pair_wise=[2, 3], train_or_test=0, smoothness=0.1, contour=False)

    # Between class 3 and class 1.
bayes_classifier.plot_contour(x_min=-500, x_max=2600, y_min=-100, y_max=3000, steps=750, pair_wise=[3, 1], train_or_test=0, smoothness=0.1, contour=False)

""" Instantiate an object of Evaluation class to calculate various model metrics. """

eval = Evaluation(bayes_case=bayes_classifier, data_prep=data_preprocess, test_size=0.30)
class_id = 1 # The class_id for the required class

    # Returns confusion matrix for a given Bayesian Classifier Case
cm = eval.confusion_matrix()

    # Returns the accuracy of classification for a given Bayesian Classifier Case
acc = eval.accuracy()

    # Returns the precision for a given class for a given Bayesian Classifier Case
prec = eval.precision(class_id)

    # Returns the recall for a given class for a given Bayesian Classifier Case
rec = eval.recall(class_id)

    # Returns the F-score for a given class for a given Bayesian Classifier Case
f_score = eval.f_score(class_id)

    # Returns the mean precision of classification for a given Bayesian Classifier Case
mean_prec = eval.mean_precision()

    # Returns the mean recall of classification for a given Bayesian Classifier Case
mean_rec = eval.mean_recall()

    # Returns the mean F-score of classification for a given Bayesian Classifier Case
mean_f_score = eval.mean_f_score()

    # Plots the confusion matrix of classification for a given Bayesian Classifier Case
eval.plot_confusion_matrix()


import pytest
from datetime import datetime
from src.utils.utils import view_list_generator, format_date

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

class TestUtils:
    def test_view_list_generator(self, my_config_loader):
        g = view_list_generator(sample_list)
        assert next(g) == sample_list[:2]

    def test_view_list_generator_next_page(self, my_config_loader):
        g = view_list_generator(sample_list)
        first_two = next(g)
        next_two = next(g)
        assert next_two == sample_list[2:4]

    @pytest.mark.parametrize("bad_dates", ['abc', '2023-10-15', 'lo', '  ', '2023-10-87 22:15:33.77777'])
    def test_format_date_with_bad_date(self, bad_dates, my_config_loader):
        with pytest.raises(ValueError):
            format_date(bad_dates)

    @pytest.mark.parametrize('inp_date, expected', [('2023-10-25 11:37:54.637963', "25/10/2023 at 11:37")])
    def test_format_date_with_good_date(self, inp_date, expected, my_config_loader):
        date: datetime = format_date(inp_date)
        assert date == expected


import email
import hashlib
import logging
from email.message import Message
from pathlib import Path
from typing import Optional, Tuple

from logger import get_logger
from model import Attachment, MsgMeta, RawMsg, db, pw

log = get_logger(__name__)

def process_message(email_msg: Message, checksum: str, m_uid: str):
    """
    Process an entire message object.

    Split attachment files from rawmsg, create db entries for
    each rawmsg, message meta and attachment.
    """

    # We need to parse attachments first.
    # They are extracted and removed from messages.
    _attachments = [process_attachment(part) for part in email_msg.walk()]
    attachments = list(filter(None, _attachments))
    has_attachments = len(attachments) > 0

    # Parse metadata
    from_ = email_msg.get('From')
    to = email_msg.get('To')
    subject = email_msg.get('Subject')
    date = (
        email.utils.parsedate_to_datetime(email_msg.get('Date'))
        if email_msg.get('Date')
        else None
    )

    with db.atomic():
        rmsg = RawMsg.create(email_blob=email_msg.as_bytes(), original_checksum=checksum)

        if has_attachments:
            for file_checksum, filename, content_type in attachments:
                att = Attachment.create(
                    file_checksum=file_checksum,
                    original_filename=filename,
                    content_type=content_type,
                )
                rmsg.attachments.add(att)

        mmeta = MsgMeta.create(
            rawmsg=rmsg,
            imap_uid=m_uid,
            from_=from_,
            to=to,
            subject=subject,
            date=date,
            has_attachments=has_attachments,
        )

    log.info(
        'Processed message: m_uid=%s, from_=%s, to=%s, subject=%s',
        m_uid,
        from_,
        to,
        subject,
    )

def process_attachment(part: Message) -> Optional[Tuple[str, str, str]]:
    """
    Remove attachments from email messages and save them as files.
    The message will be altered.
    """

    filename = part.get_filename()
    if not filename:
        return None

    content_type = part.get_content_type()
    payload = part.get_payload(decode=True)  # decode from base64
    file_checksum = hashlib.sha256(payload).hexdigest()
    file_path = Path(f'attachments/{file_checksum}')

    log.debug(
        'Attachment found: file_checksum=%s, filename=%s, content_type=%s',
        file_checksum,
        filename,
        content_type,
    )

    if file_path.is_file():
        log.info('Attachment file already exists for: %s, Skipping', file_checksum)
    else:
        log.info('Writing file: %s', file_checksum)
        file_path.write_bytes(payload)

    part.set_param(file_checksum, None, header='X-File-Checksum')
    part.set_payload(None)

    return file_checksum, filename, content_type


import asyncio

from skellycam.detection.detect_cameras import detect_cameras
from skellycam.opencv.camera.camera import Camera
from skellycam.opencv.camera.models.camera_config import CameraConfig

async def imshow_testing():
    cams = detect_cameras()
    cvcams = []
    for info in cams.cameras_found_list:
        c = Camera(CameraConfig(camera_id=info))
        c.connect()
        cvcams.append(c)

    await asyncio.gather(*[cam.show_async() for cam in cvcams])

if __name__ == "__main__":
    asyncio.run(imshow_testing())


from firebase_admin import credentials, messaging
import os
from datetime import datetime, timedelta

cred = credentials.Certificate({
  "type": "service_account",
  "project_id": os.environ.get("PROJECT_ID"),
  "private_key_id": os.environ.get("PRIVATE_KEY_ID"),
  "private_key": os.environ.get("PRIVATE_KEY").replace("\\n", "\n"),
  "client_email": os.environ.get("CLIENT_EMAIL"),
  "client_id": os.environ.get("CLIENT_ID"),
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": os.environ.get("CLIENT_X509_CERT_URL"),
})

firebase_admin.initialize_app(cred)

def generate_notification_options():
    return messaging.AndroidConfig(
        priority='high',
        ttl=datetime.utcnow() + timedelta(days=1)
    )

def send_message_to_token(token, notification, options):
    message = messaging.Message(
        notification=notification,
        token=token,
        android=options
    )
    return messaging.send(message)

def send_message_to_topic(topic, notification, options):
    message = messaging.Message(
        notification=notification,
        topic=topic,
        android=options
    )
    return messaging.send(message)


"""Tests for SystemConfigurationModel class.

Note: Do not need to test matching module names because module names cannot be the same
by definition of dict.
"""
from typing import Any, Callable, Dict

import pytest
from pydantic import ValidationError
from pytest_lazyfixture import lazy_fixture  # type: ignore[import]

from emulation_system import SystemConfigurationModel
from emulation_system.compose_file_creator.errors import DuplicateHardwareNameError
from emulation_system.compose_file_creator.input.hardware_models import (
    HeaterShakerModuleInputModel,
    MagneticModuleInputModel,
    OT2InputModel,
    TemperatureModuleInputModel,
    ThermocyclerModuleInputModel,
)
from tests.conftest import (
    HEATER_SHAKER_MODULE_ID,
    MAGNETIC_MODULE_ID,
    OT2_ID,
    SYSTEM_UNIQUE_ID,
    TEMPERATURE_MODULE_ID,
    THERMOCYCLER_MODULE_ID,
)

@pytest.fixture
def matching_module_names(make_config: Callable) -> Dict[str, Any]:
    """Dict with matching moudle names."""
    config = make_config(modules={"magnetic-module": 1})
    config["modules"].extend(config["modules"])
    return config

@pytest.fixture
def matching_robot_and_module_names(make_config: Callable) -> Dict[str, Any]:
    """Dict with matching robot and module name."""
    config = make_config(robot="ot2", modules={"magnetic-module": 1})
    config["robot"]["id"] = config["modules"][0]["id"]
    return config

@pytest.fixture
def invalid_ot2_name(make_config: Callable) -> Dict[str, Any]:
    """Dict with ot2 that has invalid name."""
    config = make_config(robot="ot2")
    config["robot"]["id"] = "Invalid Name"
    return config

@pytest.fixture
def null_robot_with_modules(make_config: Callable) -> Dict[str, Any]:
    """Structure of SystemConfigurationModel with modules and null robot."""
    config = make_config(
        robot="ot2",
        modules={
            "magnetic-module": 1,
            "temperature-module": 1,
            "thermocycler-module": 1,
            "heater-shaker-module": 1,
        },
        system_unique_id="test",
    )
    config["robot"] = None
    config["system-unique-id"] = None
    return config

@pytest.fixture
def null_module_with_robot(make_config: Callable) -> Dict[str, Any]:
    """Structure of SystemConfigurationModel with modules and null robot."""
    config = make_config(
        robot="ot2",
        modules={
            "magnetic-module": 1,
            "temperature-module": 1,
            "thermocycler-module": 1,
            "heater-shaker-module": 1,
        },
        system_unique_id="test",
    )
    config["modules"] = None
    config["system-unique-id"] = None
    return config

@pytest.fixture
def null_everything() -> Dict[str, None]:
    """Structure of SystemConfigurationModel with all values null."""
    return {
        "robot": None,
        "modules": None,
        "system-unique-id": None,
    }

@pytest.fixture
def with_invalid_system_unique_id(make_config: Callable) -> Dict[str, Any]:
    """Structure of SystemConfigurationModel with robot, modules, and an invalid system-unique-id."""
    config = make_config(
        robot="ot2",
        modules={
            "magnetic-module": 1,
            "temperature-module": 1,
            "thermocycler-module": 1,
            "heater-shaker-module": 1,
        },
        system_unique_id="test",
    )
    config["system-unique-id"] = "I aM uNiQuE bUt InVaLiD"
    return config

@pytest.mark.parametrize(
    "config",
    [
        lazy_fixture("matching_robot_and_module_names"),
        lazy_fixture("matching_module_names"),
    ],
)
def test_duplicate_names(config: Dict[str, Any]) -> None:
    """Confirm that ValidationError is thrown when a robot and module have the same name."""
    with pytest.raises(DuplicateHardwareNameError) as err:
        SystemConfigurationModel.from_dict(config)
    expected_error_text = (
        "The following container names are duplicated in the "
        f"configuration file: {MAGNETIC_MODULE_ID}"
    )
    assert err.match(expected_error_text)

def test_invalid_container_name(invalid_ot2_name: Dict[str, Any]) -> None:
    """Confirm that ValidationError is thrown when a robot and module have the same name."""
    with pytest.raises(ValidationError) as err:
        SystemConfigurationModel.from_dict(invalid_ot2_name)
    expected_error_text = ".*string does not match regex.*"
    assert err.match(expected_error_text)

@pytest.mark.parametrize(
    "config",
    [
        lazy_fixture("modules_only"),
        lazy_fixture("ot2_and_modules"),
        lazy_fixture("null_robot_with_modules"),
    ],
)
def test_modules_exist_is_true(config: Dict[str, Any]) -> None:
    """Test that modules_exist property is true when it is supposed to be."""
    assert SystemConfigurationModel.from_dict(config).modules_exist  # type: ignore [truthy-function]

@pytest.mark.parametrize(
    "config", [lazy_fixture("ot2_only"), lazy_fixture("null_module_with_robot")]
)
def test_modules_exist_is_false(config: Dict[str, Any]) -> None:
    """Test that modules_exist property is false when it is supposed to be."""
    configuration_file = SystemConfigurationModel.from_dict(config)
    assert not configuration_file.modules_exist(configuration_file.modules)

@pytest.mark.parametrize(
    "config",
    [
        lazy_fixture("ot2_only"),
        lazy_fixture("ot2_and_modules"),
        lazy_fixture("null_module_with_robot"),
    ],
)
def test_robot_exists_is_true(config: Dict[str, Any]) -> None:
    """Test that robot_exists property is true when it is supposed to be."""
    configuration_model = SystemConfigurationModel.from_dict(config)
    assert configuration_model.robot_exists(configuration_model.robot)

@pytest.mark.parametrize(
    "config", [lazy_fixture("modules_only"), lazy_fixture("null_robot_with_modules")]
)
def test_robot_exists_is_false(config: Dict[str, Any]) -> None:
    """Test that robot_exists property is false when it is supposed to be."""
    configuration_model = SystemConfigurationModel.from_dict(config)
    assert not configuration_model.robot_exists(configuration_model.robot)

def test_containers_property(ot2_and_modules: Dict[str, Any]) -> None:
    """Test the containers property is constructed correctly."""
    containers = SystemConfigurationModel.from_dict(ot2_and_modules).containers
    magnetic_module_id = f"{MAGNETIC_MODULE_ID}-1"
    temperature_module_id = f"{TEMPERATURE_MODULE_ID}-1"
    thermocycler_module_id = f"{THERMOCYCLER_MODULE_ID}-1"
    heater_shaker_module_id = f"{HEATER_SHAKER_MODULE_ID}-1"

    assert set(containers.keys()) == {
        OT2_ID,
        magnetic_module_id,
        temperature_module_id,
        thermocycler_module_id,
        heater_shaker_module_id,
    }
    assert isinstance(containers[OT2_ID], OT2InputModel)
    assert isinstance(containers[magnetic_module_id], MagneticModuleInputModel)
    assert isinstance(containers[temperature_module_id], TemperatureModuleInputModel)
    assert isinstance(containers[thermocycler_module_id], ThermocyclerModuleInputModel)
    assert isinstance(containers[heater_shaker_module_id], HeaterShakerModuleInputModel)

def test_get_by_id(ot2_and_modules: Dict[str, Any]) -> None:
    """Test that loading containers by id works correctly."""
    system_config = SystemConfigurationModel.from_dict(ot2_and_modules)
    magnetic_module_id = f"{MAGNETIC_MODULE_ID}-1"
    temperature_module_id = f"{TEMPERATURE_MODULE_ID}-1"
    thermocycler_module_id = f"{THERMOCYCLER_MODULE_ID}-1"
    heater_shaker_module_id = f"{HEATER_SHAKER_MODULE_ID}-1"
    assert isinstance(system_config.get_by_id(OT2_ID), OT2InputModel)
    assert isinstance(
        system_config.get_by_id(heater_shaker_module_id), HeaterShakerModuleInputModel
    )
    assert isinstance(
        system_config.get_by_id(magnetic_module_id), MagneticModuleInputModel
    )
    assert isinstance(
        system_config.get_by_id(temperature_module_id), TemperatureModuleInputModel
    )
    assert isinstance(
        system_config.get_by_id(thermocycler_module_id), ThermocyclerModuleInputModel
    )

@pytest.mark.parametrize(
    "config", [lazy_fixture("ot2_and_modules"), lazy_fixture("null_everything")]
)
def test_no_system_unique_id(config: Dict[str, Any]) -> None:
    """Test that default network name is set correctly when field is not specified."""
    assert SystemConfigurationModel.from_dict(config).system_unique_id is None

def test_overriding_system_unique_id(with_system_unique_id: Dict[str, Any]) -> None:
    """Test that system network name is overridden correctly."""
    system_config = SystemConfigurationModel.from_dict(with_system_unique_id)
    assert system_config.system_unique_id == SYSTEM_UNIQUE_ID

def test_invalid_system_unique_id(
    with_invalid_system_unique_id: Dict[str, Any]
) -> None:
    """Verify exception is thrown when invalid system-unique-id is passed."""
    with pytest.raises(ValidationError):
        SystemConfigurationModel.from_dict(with_invalid_system_unique_id)


# Напишите программу, удаляющую из текста все слова, содержащие 'абв'
# 'абв роро длдлдл оооабв лоло абв' => 'роро длдлдл лоло'

txt = input('Введите текст: ')
sb_str = input('Введите подстроку: ')

def del_word(txt, sub_str):
    lst = txt.split()
    i = len(lst) - 1
    while i >= 0:
        if lst[i].find(sub_str) != -1:
            lst.pop(i)
        i -= 1
    res = ''
    for elem in lst:
        if res != '':
            res += ' '
        res += elem
    return res

print(del_word(txt, sb_str))


import random
import tkinter as tk

#================================================ lijsten zitten hier onder===========================
lijst = ['Gaming Pc','Gaming laptop','Gaming muis','Gaming Keyboard','4k scherm 32 inch']
listt = """
De Prijzen zijn:
Gaming Pc
Gaming laptop
Gaming muis
Gaming Keyboard
4k scherm 32 inch
"""
#============================ tkinter en varibales setup ===========================================
counter = 0
window = tk.Tk()
window.title('Grabbelton')
window.config(bg='grey')
button1 = tk.Button(text='klik hier om een prijs te grabbelen', bg="black", fg="white")
stringvar = tk.StringVar(value=listt)
window.geometry('300x300')
label1 = tk.Label(
    button1.pack(side=tk.TOP),
)
label1.config(textvariable=stringvar,bg='grey')
label1.place(relx = 0.5,rely = 0.5,anchor = 'center',)

#================================================functies hier onder=============================
def click():
    global counter
    if len(lijst) != 0:
        counter += 1
        root = tk.Tk()
        root.title(f'Prijz nummer :{counter}')
        root.config(bg='grey')
        root.geometry('300x300')
        rand = random.choice(lijst)
        lijst.remove(rand)
        label2 = tk.Label(
            root,
            text =f'Gefeliciteerd! Jou prijz is:\n {rand}',
            bg='grey'
        )
        label1.config(bg='grey')
        label2.place(relx = 0.5,rely = 0.5,anchor = 'center')
    elif len(lijst) == 0:
        window2 = tk.Tk()
        window2.geometry('350x300')
        window2.config(bg='grey')
        window2.title('Prijzen zijn op!')
        win2Label = tk.Label(
            window2,
            text='Sorry er zij geen Prijzen meer :(',
            font=("Terminal", 15)
        )
        win2Label.place(relx = 0.5,rely = 0.5,anchor = 'center',)

button1.config(command=click)
window.mainloop()


def index_to_column(data, indx_col, power_col):
    import pandas as pd
    data = data.reset_index()
    data[indx_col] = pd.to_datetime(data[indx_col])
    data = data.sort_values(indx_col)

    data = data.rename(columns={indx_col: 'ds', power_col: 'y'})
    return data

def xgboost_algorithm(file, checked_columns, col_names):
    import numpy as np
    import pandas as pd
    import matplotlib
    import matplotlib.pyplot as plt
    from prophet import Prophet
    from xgboost import XGBRegressor
    from sklearn.metrics import mean_squared_error
    from math import sqrt
    from sklearn.model_selection import GridSearchCV

    useColumns = []
    i = 0

    for column in checked_columns:
        if (checked_columns[i].get() == 1):
            useColumns.append(col_names[i])
        i = i + 1

    df = pd.read_csv(file, usecols=useColumns, index_col=useColumns[0], parse_dates=True)

    print(df)

    indx_col = useColumns[0]
    power_col = useColumns[1]

    df.sort_values(by=useColumns[0], ascending=True)
    df = df.fillna(method='ffill')
    df = df.sort_values(by=useColumns[0], ascending=True)
    df.dropna(axis=0, how='any', subset=None, inplace=True)

    df = df[~df.index.duplicated(keep='first')]

    df = df.asfreq('H')
    df = df.fillna(method='ffill')

    #############################################################################################
    #training section

    # Before building and training our model, let's split the data into training and testing
    #df_train, df_test = df[df.index < '2016-01-01'], df[df.index >= '2016-01-01']
    df_train, df_test = df[:], df[-22000:]

    X_train, y_train = date_transform(df_train, power_col)
    X_test, y_test = date_transform(df_test, power_col)

    print(X_train)
    print(y_train)

    print(X_test)
    print(y_test)

    xgb_model = XGBRegressor(n_estimators=1000, learning_rate=0.05, early_stopping_rounds=10)
    xgb_model.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)])
    xgb_pred = xgb_model.predict(X_test)

    rmse = sqrt(mean_squared_error(y_test, xgb_pred))  # root mean square error

    df_plot = pd.DataFrame({'y_test': y_test, 'xgb_pred': xgb_pred})

    plt.figure(figsize=(20, 8))

    df_plot['y_test'].plot(label='Actual')
    df_plot['xgb_pred'].plot(label='Predicted')
    plt.text(16770, 3250, 'RMSE: {}'.format(rmse), fontsize=20, color='red')
    plt.title('Testing Set Forecast', weight='bold', fontsize=25)
    plt.legend()

    #####################################################################################################
    #prediction section
    new_df = index_to_column(df, indx_col, power_col)
    new_df = remove_tz_from_dataframe(new_df)
    prophet_model2 = Prophet(interval_width=0.95)
    prophet_model2.fit(new_df)
    # 7 days to the future (7x24 = 168)
    future_dates = prophet_model2.make_future_dataframe(periods=168, freq='H')

    future_dates2 = future_dates.iloc[-168:, :].copy()

    future_dates2['ds'] = pd.to_datetime(future_dates2['ds'])
    future_dates2 = future_dates2.set_index('ds')

    future_dates2['Hour'] = future_dates2.index.hour
    future_dates2['Dayofweek'] = future_dates2.index.dayofweek
    future_dates2['Dayofmonth'] = future_dates2.index.day
    future_dates2['Dayofyear'] = future_dates2.index.dayofyear
    future_dates2['weekofyear'] = future_dates2.index.weekofyear
    future_dates2['Month'] = future_dates2.index.month
    future_dates2['Quarter'] = future_dates2.index.quarter
    future_dates2['Year'] = future_dates2.index.year

    X = pd.concat([X_train, X_test], ignore_index=True)
    y = pd.concat([y_train, y_test], ignore_index=True)

    xgb_model2 = XGBRegressor(n_estimators=1000, learning_rate=0.05)
    xgb_model2.fit(X, y)
    xgb_pred2 = xgb_model2.predict(future_dates2)

    df_plot2 = pd.DataFrame({'Hour': future_dates2['Hour'], 'xgb_pred2': xgb_pred2})

    #last_week = df['2018-07-01':'2018-08-15']
    last_week = df[-168:]

    plt.figure(figsize=(20, 8))

    last_week[power_col].plot()
    df_plot2['xgb_pred2'].plot()
    plt.title('7 Days Forecast', weight='bold', fontsize=25)
    plt.show()

def date_transform(data, power_col):
    df = data.copy()

    print(data)

    df['Hour'] = df.index.hour
    df['Dayofweek'] = df.index.dayofweek
    df['Dayofmonth'] = df.index.day
    df['Dayofyear'] = df.index.dayofyear
    df['weekofyear'] = df.index.weekofyear
    df['Month'] = df.index.month
    df['Quarter'] = df.index.quarter
    df['Year'] = df.index.year

    X = df.drop(power_col, axis=1)
    y = df[power_col]

    return X, y

def remove_tz_from_dataframe(df_in):
    import pandas as pd
    df = df_in.copy()
    col_times = [ col for col in df.columns if any([isinstance(x, pd.Timestamp) for x in df[col]])]
    for col in col_times:
        df[col] = pd.to_datetime(
            df[col], infer_datetime_format=True)
        df[col] = df[col].dt.tz_localize(None)
    return df


from player import *
from experiment_random_search import *
import time

def main():
    # runs the default
    default_types()
    experiment_between_def_types()

'''
def random_search_for_better_policy(n_test=10000, n_opp=10000):
    """
    This function will test a random policy against another random policy
    :param n_test: Number of policies to test
    :param n_opp: Number of opposition policies to test
    :return:
    """
    most_wins = dict()
    most_wins["policy"] = [0, 0, 0]
    most_wins["win"] = 0
    most_wins["tie"] = 0
    most_wins["avg"] = 0
    most_ties = dict()
    most_ties["policy"] = [0, 0, 0]
    most_ties["win"] = 0
    most_ties["tie"] = 0
    most_ties["avg"] = 0
    best_vals = dict()
    best_vals["policy"] = [0, 0, 0]
    best_vals["win"] = 0
    best_vals["tie"] = 0
    best_vals["avg"] = 0

    for i in range(n_test):
        print(" Executing Test", i)
        win = 0
        tie = 0
        val = list()
        f1 = random.randint(0, 100) / 100.0
        i1 = random.randint(0, 100) / 100.0
        v1 = random.randint(0, 100) / 100.0
        p1_pol = [f1, i1, v1]
        for i in range(n_opp):
            f2 = random.randint(0, 100) / 100.0
            i2 = random.randint(0, 100) / 100.0
            v2 = random.randint(0, 100) / 100.0
            p2_pol = [f2, i2, v2]
            p1v, p2v = experiment(p1_pol, p2_pol)
            val.append(p1v)
            if p1v > p2v:
                win += 1
            if p1v == p2v:
                tie += 1
        avg = sum(val)/n_opp
        if win > most_wins["win"]:
            most_wins["policy"] = p1_pol.copy()
            most_wins["win"] = win
            most_wins["tie"] = tie
            most_wins["avg"] = avg
            print("  Most Wins  ", most_wins["policy"], most_wins["win"], most_wins["tie"], most_wins["avg"])
        if tie > most_ties["tie"]:
            most_ties["policy"] = p1_pol.copy()
            most_ties["win"] = win
            most_ties["tie"] = tie
            most_ties["avg"] = avg
            print("  Most Ties  ", most_ties["policy"], most_ties["win"], most_ties["tie"], most_ties["avg"])
        if avg > best_vals["avg"]:
            best_vals["policy"] = p1_pol.copy()
            best_vals["win"] = win
            best_vals["tie"] = tie
            best_vals["avg"] = avg
            print("  Best Value ", best_vals["policy"], best_vals["win"], best_vals["tie"], best_vals["avg"])

    print()
    print("Most Wins  ", most_wins["policy"], "\t", most_wins["win"], "\t", most_wins["tie"], "\t", most_wins["avg"])
    print("Most Ties  ", most_ties["policy"], "\t", most_ties["win"], "\t", most_ties["tie"], "\t", most_ties["avg"])
    print("Best Value ", best_vals["policy"], "\t", best_vals["win"], "\t", best_vals["tie"], "\t", best_vals["avg"])
'''

def default_types():
    pol1 = [1, 0, 0]  # Cooperator
    pol2 = [0.5, 0, 0]  # Coin Flipper
    pol3 = [1, 1, 0]  # Copycat
    pol4 = [1, 1, 0.25]  # Retaliator
    pol5 = [1, 1, 1]  # Grudge Holder
    pol6 = [0, 0, 1]  # Defector
    print("For Policy ", pol1)
    experiments(pol1)
    print()
    print("For Policy ", pol2)
    experiments(pol2)
    print()
    print("For Policy ", pol3)
    experiments(pol3)
    print()
    print("For Policy ", pol4)
    experiments(pol4)
    print()
    print("For Policy ", pol5)
    experiments(pol5)
    print()
    print("For Policy ", pol6)
    experiments(pol6)
    print()

def experiment_between_def_types():
    """
    Does the experiment with different policies, specifically the default types in the
    :return:
    """
    pol1 = [1, 0, 0]  # Cooperator
    pol2 = [0.5, 0, 0]  # Coin Flipper
    pol3 = [1, 1, 0]  # Copycat
    pol4 = [1, 1, 0.25]  # Retaliator
    pol5 = [1, 1, 1]  # Grudge Holder
    pol6 = [0, 0, 1]  # Defector
    pol_set_1 = [pol1, pol2, pol3, pol4, pol5, pol6]
    pol_set_2 = [pol1, pol2, pol3, pol4, pol5, pol6]
    for i in pol_set_1:
        win = 0
        tie = 0
        for j in pol_set_2:
            p1v, p2v = experiment(i, j)
            if p1v > p2v:
                win += 1
            if p1v == p2v:
                tie += 1
        print(i)
        print("Wins : ", win)
        print("Ties : ", tie)
        print()

if __name__ == '__main__':
    n_me, n_them = 100, 100
    begin = time.clock()
    random_search_for_better_policy(n_me, n_them)
    a = time.clock()-begin
    print("time: ", a)
    begin = time.clock()
    random_search_for_better_policy(n_me, n_them, 2)
    b = time.clock() - begin
    print("time: ", b)
    begin = time.clock()
    random_search_for_better_policy(n_me, n_them, False)
    c = time.clock() - begin
    print("time: ", c)
    print()
    print("Multiprocess  : ", a)
    print("Async Multi   : ", b)
    print("Single Thread : ", c)


import pytest
from typing import Dict, Any, cast
from opentrons_shared_data.pipette import (
    load_data,
    pipette_load_name_conversions,
    dev_types,
)
from opentrons_shared_data.pipette.types import (
    PipetteChannelType,
    PipetteModelType,
    PipetteVersionType,
    PipetteTipType,
    Quirks,
    LiquidClasses,
)

def test_load_pipette_definition() -> None:
    pipette_config_one = load_data.load_definition(
        PipetteModelType.p50,
        PipetteChannelType.SINGLE_CHANNEL,
        PipetteVersionType(major=3, minor=3),
    )

    assert pipette_config_one.channels == 1
    assert pipette_config_one.pipette_type.value == "p50"
    assert pipette_config_one.nozzle_offset == [-8.0, -22.0, -259.15]

    assert (
        pipette_config_one.liquid_properties[LiquidClasses.default]
        .supported_tips[PipetteTipType.t50]
        .default_aspirate_flowrate.default
        == 8.0
    )

    assert pipette_config_one.quirks == []
    pipette_config_two = load_data.load_definition(
        PipetteModelType.p50,
        PipetteChannelType.SINGLE_CHANNEL,
        PipetteVersionType(major=1, minor=0),
    )

    assert pipette_config_two.channels == 1
    assert pipette_config_two.pipette_type.value == "p50"
    assert pipette_config_two.nozzle_offset == [0.0, 0.0, 25.0]
    assert (
        pipette_config_two.liquid_properties[LiquidClasses.default]
        .supported_tips[PipetteTipType.t200]
        .default_aspirate_flowrate.default
        == 25.0
    )
    assert pipette_config_two.quirks == [Quirks.dropTipShake]

@pytest.mark.parametrize(
    argnames=["key_spot_check", "value_spot_check"],
    argvalues=[
        ["P1KSV10", "p1000_single_v1.0"],
        ["P1KHV33", "p1000_96_v3.3"],
        ["P20MV21", "p20_multi_v2.1"],
        ["P300MV10", "p300_multi_v1.0"],
        ["P3HMV14", "p300_multi_v1.4"],
    ],
)
def test_build_serial_number_lookup(key_spot_check: str, value_spot_check: str) -> None:
    lookup_table = load_data.load_serial_lookup_table()
    assert lookup_table[key_spot_check] == value_spot_check

@pytest.mark.parametrize(
    argnames=["pipette_model", "v1_configuration_changes"],
    argvalues=[
        ["p300_multi_v1.4", {"max_volume": 200, "min_volume": 10}],
        ["p1000_96_v3.3", {"tip_length": 40, "min_volume": 300}],
    ],
)
def test_update_pipette_configuration(
    pipette_model: str, v1_configuration_changes: Dict[str, Any]
) -> None:

    liquid_class = LiquidClasses.default
    model_name = pipette_load_name_conversions.convert_pipette_model(
        cast(dev_types.PipetteModel, pipette_model)
    )
    base_configurations = load_data.load_definition(
        model_name.pipette_type, model_name.pipette_channels, model_name.pipette_version
    )
    updated_configurations = load_data.update_pipette_configuration(
        base_configurations, v1_configuration_changes, liquid_class
    )

    updated_configurations_dict = updated_configurations.dict()
    for k, v in v1_configuration_changes.items():
        if k == "tip_length":
            for i in updated_configurations_dict["liquid_properties"][liquid_class][
                "supported_tips"
            ].values():
                assert i["default_tip_length"] == v
        else:
            assert (
                updated_configurations_dict["liquid_properties"][liquid_class][k] == v
            )


import urllib.request
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import sqlite3
import re
ignorewords = set(['the', 'of', 'to', 'and', 'a', 'in', 'is', 'it'])
class Crawler:
   # iniitialize the Crawler with the name database
    def __init__(self, dbname):
        self.con = sqlite3.connect(dbname)

    def __del__(self):
        self.con.close()

    def dbcommit(self):
        self.con.commit()

   # Auxilary function for getting an <entry: word_of_wordlist, url_of_urllist> id and adding
   # if it's not present
    def getentryid(self, table, field, value, createnew=True):
        # table = 'wordlist', field='word', value = word whose id is to be fetchd
        # table = 'urllist', field='url', value = url whose id is to be fetchd
        current_record = self.con.execute(
            "select rowid from %s where %s='%s'" % (table, field, value))
        res = current_record.fetchone()
        if res == None:
            current_record = self.con.execute(
                "insert into %s (%s) values ('%s')" % (table, field, value))
            return current_record.lastrowid
        else:
            return res[0]

    # index an individual page
    def addtoindex(self, url, soup):
        if self.isindexed(url):
            return
        print('Indexing ' + url)

        # Get the individual words
        text = self.gettextonly(soup)
        words = self.separatewords(text)

        # Get the URL id
        urlid = self.getentryid('urllist', 'url', url)

        # Link each word to this url
        for i in range(len(words)):
            word = words[i]
            if word in ignorewords:
                continue
            wordid = self.getentryid('wordlist', 'word', word)
            self.con.execute("insert into wordlocation(urlid,wordid,location) \
                values (%d,%d,%d)" % (urlid, wordid, i))
        self.storepdf(url, urlid)

    # Extract the text from an HTML page (no tags)
    def gettextonly(self, soup):
        # Finding the Words on a Page
        v = soup.string
        if v == None:
            c = soup.contents
            resulttext = ''
            for t in c:
                subtext = self.gettextonly(t)
                resulttext += subtext+'\n'
            return resulttext
        else:
            return v.strip()

    # Seperate the words by any non-whitespace character
    def separatewords(self, text):
        # source: https://www.pythontutorial.net/python-regex/python-regex-split/

        # splitter = re.compile('\W*')
        # return [s.lower() for s in splitter.split(text) if s != '']
        splitter = r'\W+'
        return [s.lower() for s in re.split(splitter, text) if s != '']

    # Return True if this url is already indexed
    def isindexed(self, url):
        u = self.con.execute(
            "select rowid from urllist where url='%s'" % url).fetchone()
        if u != None:
            # Check if it has actually been crawled
            v = self.con.execute(
                'select * from wordlocation where urlid=%d' % u[0]).fetchone()
            if v != None:
                return True
        return False

    # Add link between two pages
    def addlinkref(self, urlFrom, urlTo, linkText):
        words=self.separatewords(linkText)
        fromid=self.getentryid('urllist','url',urlFrom)
        toid=self.getentryid('urllist','url',urlTo)
        if fromid==toid: return  # i.e. fromurl_id == tourl_id
        cur=self.con.execute("insert into link(fromid,toid) values (%d,%d)" % (fromid,toid))
        linkid=cur.lastrowid
        for word in words:
            if word in ignorewords: continue
            wordid=self.getentryid('wordlist','word',word)
            self.con.execute("insert into linkwords(linkid,wordid) values (%d,%d)" % (linkid,wordid))

    # Starting with a list of pages, do breadth first search
    # to the given depth, indexing pages as we go
    def crawl(self, pages, depth=2):
        for i in range(depth):
            newpages = set()
            for page in pages:  # pages = url_list
                try:
                    # c = urllib.request.urlopen(page)
                    c = requests.get(page)
                except:
                    print(f"cound not open {page}")
                    continue
                # soup = BeautifulSoup(c.read())
                soup = BeautifulSoup(c.text)
                self.addtoindex(page, soup)

                links = soup('a')
                for link in links:
                    if('href' in dict(link.attrs)):
                        # if <a> has a link
                        url = urljoin(page, link['href'])
                        if url.find("\'") != -1:    # ignore url with quote
                            continue
                        url = url.split('#')[0]   # remove location portion
                        if url[:4] == 'http' and not self.isindexed(url):
                            newpages.add(url)
                        linkText = self.gettextonly(link)   # strange links e.g.
                        self.addlinkref(page, url, linkText)    # # Add link between two pages:
                self.dbcommit()
            pages = newpages

    # Create the database tables
    def createindextables(self):
        self.con.execute('create table urllist(url)')
        self.con.execute('create table wordlist(word)')
        self.con.execute('create table wordlocation(urlid,wordid,location)')
        self.con.execute('create table link(fromid integer,toid integer)')
        self.con.execute('create table linkwords(wordid,linkid)')
        self.con.execute('create table pdfs(urlid)')

        self.con.execute('create index wordidx on wordlist(word)')
        self.con.execute('create index urlidx on urllist(url)')
        self.con.execute('create index wordurlidx on wordlocation(wordid)')
        self.con.execute('create index urltoidx on link(toid)')
        self.con.execute('create index urlfromidx on link(fromid)')
        self.con.execute('create index pdfurl on pdfs(urlid)')  #  creating index of each  pdf_url
        self.dbcommit()

    def storepdf(self, url, url_id):
        # store to database: pdfs <if link is pdf>
        document_prefixes = ['https://drive.google.com/', ]
        document_suffixes = ['pdf', 'epub', 'doc', 'docx', 'odt', 'xls', 'xlsx', 'ppt', 'pptx']
        if True in [url.startswith(document_prefix) for document_prefix in document_prefixes] + [url.endswith(document_suffix) for document_suffix in document_suffixes]:
            print(f'pdf:{url}, {url_id}')
            self.conn.execute("insert into pdfs(urlid) values (%d)" % (url_id))
        else:
            print(f'not_: {url} {url_id}')


"""
Assumptions made:
1. For the GET method, assuming that whenever that GET method is ran, list will always be size 500,
so no need to check and just return the sorted list.

2. For the overall API, assuming this would be ran locally so enabled it to be ran locally. Otherwise,
possible to corrected and be ran on a server and use a curl command to access it.
"""

"""
Used Flask to be able to create the REST API and used some in built functions to be able to execute
certain calculations more efficiently.
"""

from flask import Flask, request
from flask_restful import Resource, Api, reqparse, abort
import pandas as pd
import ast
import random, json, requests, re, bisect

app = Flask(__name__)
api = Api(app)
NUMBERLIST = {"list":[]}

# Class Declaration that contains all 3 different methods
class ListData(Resource):
    # Retrieve Data, sort before returning
    def get(self):
        NUMBERLIST['list'].sort()
        return NUMBERLIST

    # Create Data, make sure all entries are numbers and size is of 500
    def post(self):
        numlist = []
        templist = str(request.data).split(',')
        for i in templist:
            temp = re.sub("[^0-9]", "", i)
            numlist.append(int(temp))

        if(len(numlist) == 500):
            result = all(isinstance(x, int) for x in numlist)
            if (result == True):
                NUMBERLIST['list'] = numlist
                return NUMBERLIST
            else:
                abort(400,"Invalid Input. All entries have to be numbers.")
        else:
            abort(400, "Invalid input. Length is not 500.")

    # Insert one element in corresponding order
    def patch(self):
        entry = str(request.data).strip()
        temp = re.sub("[^0-9]", "", entry)

        # Check if the single entry is a number or not
        if(temp.isnumeric()):
            # Use built in function to insert entry in a sorted list
            bisect.insort(NUMBERLIST['list'], int(temp))
            return NUMBERLIST
        else:
            abort(400,"Invalid Input. All entries have to be numbers.")

api.add_resource(ListData, '/data/')  # '/data' is our entry point
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

# Testing Commands
payload = []
for i in range(0, 500):
    payload.append(random.randint(0,1000))

newPayload = json.dumps(payload)
newData = str(random.randint(0,1000))

r=requests.post("http://localhost:5000/data/",data=newPayload)
r=requests.get("http://localhost:5000/data/")
r=requests.patch("http://localhost:5000/data/",data=newData)


# ---
# jupyter:
#   jupytext:
#     formats: ipynb,py:percent
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.14.0
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# %% [markdown]
# # Convert NWB files to pandas Dataframes

# %%
# general python modules for scientific analysis
import sys, pathlib, os
import numpy as np

# add the python path:
sys.path.append('../../src')
from physion.analysis.dataframe import NWB_to_dataframe
from physion.utils import plot_tools as pt

# %%
filename = os.path.join(os.path.expanduser('~'), 'CURATED' , 'NDNF-December-2022', '2022_12_14-13-27-41.nwb')
data = NWB_to_dataframe(filename,
                        visual_stim_label='per-protocol',
                        #visual_stim_label='per-protocol-and-parameters',
                        #visual_stim_label='per-protocol-and-parameters-and-timepoints', #
                        subsampling = 10,
                        verbose=False)

# %%
def min_max(array):
    return (array-array.min())/(array.max()-array.min())

def color(key):
    if 'Pupil' in key:
        return pt.plt.cm.Set1(0)
    elif 'Gaze' in key:
        return pt.plt.cm.Set1(4)
    elif 'Running' in key:
        return pt.plt.cm.Set1(1)
    elif 'Whisking' in key:
        return pt.plt.cm.Set1(3)
    elif 'VisStim' in key:
        return pt.plt.cm.Greys(np.random.uniform(0.2, .6))
    else:
        return pt.plt.cm.Greens(np.random.uniform(0.5, .8))

fig, ax = pt.plt.subplots(figsize=(8,10))
i = 0
for key in data.keys():
    if key !='time':
        c = color(key)
        ax.plot(data['time'], -i+.8*min_max(data[key].astype(float)), color=c, lw=1) # convert bool to float when needed
        ax.annotate(key+' ', (0, -i+.1), ha='right', color=c)
        i+=1

ax.axis('off');


import time
import pandas as pd
import pyclone2revolver as p2r
from pathlib import Path

def AssignCopyNumber(battenberg_ouput, patient_data):
    # Patient number
    mutation_id_begin = patient_data.split('.')[0].split('/')[1] + ":"
    # print(mutation_id_begin)
    # print(patient_data)
    # print(battenberg_ouput)

    copy_number_info = pd.read_csv(battenberg_ouput, sep="\t")
    copy_number_info.drop(copy_number_info.columns[[3, 4, 5, 9, 10, 11, 12, 13, 14, 15, 16]], axis=1, inplace=True)

    # rounding copy number
    copy_number_info['ntot'] = copy_number_info['ntot'].round()

    patient_df = pd.read_csv(patient_data, sep='\t', low_memory=False)

    patient_df['#CHROM'] = patient_df['#CHROM'].astype(str)

    mutation_id = []
    sample_id = []
    normal_cn = []
    minor_cn = []
    major_cn = []
    alt_counts = []
    ref_counts = []

    print("Data mapping")
    start_time = time.time()
    for i in range(len(patient_df)):

        from_tumour_file = patient_df.iloc[:, -1][i]
        from_control_file = patient_df.iloc[:, -2][i]

        # only needed 0/0 0/1
        if from_tumour_file == "./." or from_control_file == "./.":
            continue

        from_tumour_file = from_tumour_file.split(':')
        from_control_file = from_control_file.split(':')

        if from_tumour_file[0] == "0/0":
            continue

        if from_control_file[0] == from_tumour_file[0]:
            continue
        if from_control_file[0] != "0/0" and from_tumour_file[0] != "0/1":
            continue

        from_tumour_file = from_tumour_file[1]
        # getting referenced and altered genome counts
        to_counts = ''.join(from_tumour_file)
        to_counts = to_counts.split(',')

        if len(to_counts) == 1:
            continue

        if patient_df['#CHROM'][i] == 'Y':
            break
        if len(patient_df['#CHROM'][i]) < 3:
            for j in range(len(copy_number_info)):
                if patient_df['#CHROM'][i] == copy_number_info['chr'][j] and \
                        (copy_number_info['startpos'][j] <= patient_df['POS'][i] <= copy_number_info['endpos'][j]):
                    # nomral cn
                    normal_cn.append(int(copy_number_info['ntot'][j]))
                    # major cn
                    major_cn.append(int(copy_number_info['nMaj1_A'][j]))
                    # minor cn
                    minor_cn.append(int(copy_number_info['nMin1_A'][j]))
                    mutation_id.append(
                        mutation_id_begin + str(patient_df['#CHROM'][i]) + ":" + str(patient_df['POS'][i]) + ":" + str(
                            patient_df['REF'][i]))
                    sample_id.append("R1")
                    alt_counts.append(to_counts[0])
                    ref_counts.append(to_counts[1])

                    break

    output = {"mutation_id": mutation_id,
              "sample_id": sample_id,
              "ref_counts": ref_counts,
              "alt_counts": alt_counts,
              "normal_cn": normal_cn,
              "major_cn": major_cn,
              "minor_cn": minor_cn
              }
    PyClone_input = pd.DataFrame(output)

    PyClone_input.to_csv("PyClone" + patient_data.split('.')[0].split('/')[1], sep='\t')
    print("--- %s seconds ---" % (time.time() - start_time))

def EraseVCFHeader(vcf_file):
    with open(vcf_file, "r") as f:
        lines = f.readlines()

    with open(vcf_file, "w") as f:
        for line in lines:
            if line[0:2] != "##":
                f.write(line)

if __name__ == '__main__':
    list_of_files = []

    list_of_cn = []
    for path in Path('drive-download-20230509T123841Z-002').rglob('*'):
        list_of_files.append(path.name)

    for path in Path('CN_files').rglob('*'):
        list_of_cn.append(path.name)

    # remove header
    for file_name in list_of_files:
        print("Running header removal")
        EraseVCFHeader("drive-download-20230509T123841Z-002/"+file_name)
        print("Header removed")
        get_subclone_file_name = file_name.split('.')[1].split('-')[0]
        subclone : str
        for subclone_name in list_of_cn:
            get_sublone_name_1 = subclone_name.split('-')[0]
            subclone = get_sublone_name_1

            if subclone == get_subclone_file_name:
                print(f'subclone {subclone_name} VCF {file_name}')

                AssignCopyNumber("CN_files/"+subclone_name, "drive-download-20230509T123841Z-002/"+file_name)
                list_of_cn.remove(subclone_name)
                break

        # print(get_subclone_file_name)

    pyclone_files = []
    annovar_files = []
    for path in Path('pyclone-vi').rglob('PyClone.*.tsv'):
        pyclone_files.append(path.name)
    print(len(pyclone_files))

    for path in Path('annovar').rglob('*.cut.txt'):
        annovar_files.append(path.name)
    print(annovar_files)

    for file_name in pyclone_files:
        print("Running Revolver input creator")
        patient=file_name.split('.')[1]
        for anno_file_name in annovar_files:
            anno_patient = anno_file_name.split('.')[0]
            if patient == anno_patient:
                try:
                    p2r.SortOutputPyClone("/media/kovac/Resources1/MartinD/pyclone-vi/"+file_name)
                except:
                    print("Already done")
                p2r.MergeSortedWithAnnovar("/media/kovac/Resources1/MartinD/pyclone-vi/"+file_name,
                                           "/media/kovac/Resources1/MartinD/annovar/"+anno_file_name)
                annovar_files.remove(anno_file_name)
    # p2r.SortOutputPyClone("/media/kovac/Resources1/MartinD/pyclone-vi/PyClone.P2.tsv.h5.tsv")

    files_for_revolver = []
    for path in Path('/media/kovac/Resources1/MartinD/').glob('*.tsv'):
        print(path.name)
        p2r.RemoveDuplicates(path.name)
        files_for_revolver.append(path.name)
    p2r.CreateRevolverInput(files_for_revolver)

    p2r.DetermineDriver("revolver_input.tsv","IntOGen-DriverGenes.txt")

    revolver_inputDF = pd.read_csv("data.tsv", sep="\t")
    revolver_inputDF2 = pd.read_csv("revolver_input.tsv", sep="\t")
    print(len(revolver_inputDF2))
    df_subset = revolver_inputDF[revolver_inputDF['N_tot'] == 1]
    values = df_subset['variantID'].values.tolist()
    print(values)
    revolver_inputDF2 = revolver_inputDF2.query("variantID != @values")

    print(len(revolver_inputDF2))
    revolver_inputDF2.to_csv("revolver_input.tsv", sep='\t', index=False)


# coding=gbk

# 字符串与数值型数据混合输出

# 在编写程序的过程中，经常会遇到字符串与数值型数据混合输出的情况。代码如下：

str1 = '广东珠海'                      # 定义字符串
str2 = '吉林大学珠海学院'               # 定义字符串
num = 17                             # 定义一个整数
print(str1 + str2 + str(num)+ '年！')      # 对字符串和整数进行拼接


# The intro from the following code is from CS psets 7 and 8
import os

from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
import datetime

# Configure application
app = Flask(__name__, static_url_path='/static')

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached

@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

@app.route("/", methods=["GET"])
def get_index():
    return redirect("/form")

@app.route("/form", methods=["GET"])
def get_form():
    return render_template("quiz.html")

# Determine the user's spirit Vine
@app.route("/form", methods=["POST"])
def post_form():
    # Uses the answers to the first three questions to determine introversion or extroversion
    # The rest of the Vine deciding is a series of for loops, structured according to our magical formula
    # Starts with a pool of eight vines, and future questions go down a binary tree we've predetermined
    i_count = 0;
    if request.form.get("q1")== "i":
        i_count += 1
    if request.form.get("q2")== "i":
        i_count += 1
    if request.form.get("q3")== "i":
        i_count += 1
    # Introverted path
    if i_count > 1:
        if request.form.get("q5") == "cut":
            if request.form.get("q7") == "croissant":
                # I COULD HAVE DROPPED MY CROISSANT
                return render_template("results.html", title="I could have dropped my croissant!", url="hRFUZBXOWZI", description="You are kind and caring and always look out for others before yourself. You are extremely precious and it is hard to come by people like you in this world. You care deeply about others and the world and is secretly an introvert.")
            else:
                # I'M SENSITIVE, AUBREY
                return render_template("results.html", title="I'M SENSITIVE, AUBREY!", url="7xZDaw2H9GU", description= "You are typically a sensitive person that takes into account everything others say, sometimes too personally. You are also somewhat clumsy and most likely have a true age somewhere between 13-17, those darn angsty teenage years.")
        elif request.form.get("q8") == "road":
            # ROAD WORK AHEAD
            return render_template("results.html", title="Road work ahead!", url="6AYv6rV3NXE", description= "You are sassy, but down to Earth, and everyone loves being around you. You have an uncomparable sense of humor, but sometimes, you come off as too sarcastic. However, with the correct audience you are the life of the party and always a loyal friend. You will grow up to wield an arsenal of dad jokes in which you will use at every opportunity.")
        else:
            # GOOD EVENING
            return render_template("results.html", title="Good evening!", url="OyBmEeojfKo", description= "You are smooth in both actions and words and others often look at you in envy because of your mad stylishness. Sliding in and out and those dms are no problem for you and you can strike up a conversation with almost anyone. Your sense of humor is unique in its own special way.")
    # Extroverted path
    else:
        if request.form.get("q6") == "bump":
            #KING BACH
            if request.form.get("q9") == "kb":
                return render_template("results.html", title="What's up, brah!", url="kNsYxYOcSwc", description= "You act hard and possess so much swagger but when adversity presents itself, you react with gentleness. You hit the gym often and people can be intimidated by you but you're actually a gentle giant inside. You like to wear tight shirts to flex on em and sometimes you're guilty of saying you got a woman at home when you really don't.")

            else:
            #ASK ALL MY FRIENDS IF I'M THE NICEST...
                return render_template("results.html", title="Ask all my friends...", url="UGTNAnQFpUE", description= "You are a protective and caring soul and their are a lot of things on this Earth that are precious to you and worth protecting. Yet sometimes you take things too seriously and come off as overprotective when others are just joking. You're also extremely patriotic and probably own at least three American flags.")

        elif request.form.get("q10") == "be me":
            #IT'S GONNA BE ME
            return render_template("results.html", title="It's Gonna Be Me!", url="t0R13Ix2630", description= "You're the type to pull up at red lights, roll down your windows, and serenade the other drivers around you. You listen to the good ol bops and quality music and everyone claims that you have a good music taste. You're playlist is absolute fire and you carry your aux cord and speakers with you wherever you go. Furthermore, you have little grooves to whip out to every song you listen to.")

        else:
            #ARKANSAS AND KANSAS
            return render_template("results.html", title= "I am confusion!", url="BXt6NwKGJW0", description="You take everything as they come quite literally and often question other's thoughts when they don't align with your own. Sometimes, you come off as incredibly funny to your friends because you are lost by something that should seem obvious. You are most likely active in the Subtle Asian traits Facebook page.")

def errorhandler(e):
    """Handle error"""
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return render_template("error.html", message="Not all fields were filled in")

# Listen for errors
for code in default_exceptions:
    app.errorhandler(code)(errorhandler)


import pprint
from typing import List, Optional, Dict
from pydantic import BaseModel, Field
from unskript.thirdparty.pingdom import swagger_client as pingdom_client

pp = pprint.PrettyPrinter(indent=4)

class InputSchema(BaseModel):
    checkIds: Optional[List[str]] = Field(
        title='checkIds',
        description='List of check Ids to be modified. eg: ["1643815305","1643815323"].')
    pause: bool = Field(
        title="pause",
        description='True to pause the check Ids and false to unpause it.')
    resolution: int = Field(
        title="resolution",
        description='Interval time to test website (In Minutes). eg: 1 5 15 30 60.')

def pingdom_pause_or_unpause_checkids_printer(output):
    if output is None:
        return
    pprint.pprint(output)

def pingdom_pause_or_unpause_checkids(handle, pause: bool, resolution: int, checkIds=None) -> Dict:
    """pingdom_pause_or_unpause_checkids returns the results pause or unpause check ids

        :type handle: object
        :param handle: Object returned from task.validate(...).

        :type pause: bool
        :param pause: True to pause the check Ids and false to unpause it.

        :type resolution: int
        :param resolution: Interval time to test website (In Minutes). eg: 1 5 15 30 60.

        :type checkIds: List
        :param checkIds: List of check Ids to be modified.

        :rtype: Returns the list of result of all pause or unpause check ids
    """
    if checkIds is None:
        checkIds = []
    data = {"paused": pause, "resolution": resolution}
    if checkIds:
        data["checkids"] = ",".join(checkIds)
    check = pingdom_client.ChecksApi(api_client=handle)
    result = check.checks_put_with_http_info(body=data, _return_http_data_only=True)

    return result


# if __name__ == '__main__':
if False:
    n = int(input())
    student_marks = {}
    for _ in range(n):
        name, *line = input().split()
        scores = list(map(float, line))
        student_marks[name] = scores
    query_name = input()

def my_average(scores):
    print("{:.2f}".format(sum(scores) / len(scores)))

def solve(name):
    return my_average(student_marks[name])


def SecondsToDuration(seconds):
    days = seconds // 86400
    hours = (seconds - days * 86400) // 3600
    minutes = (seconds - days * 86400 - hours * 3600) // 60
    seconds = seconds - days * 86400 - hours * 3600 - minutes * 60
    if (len(str(days)) == 1):
        days = "0" + str(days)
    if (len(str(hours)) == 1):
        hours = "0" + str(hours)
    if (len(str(minutes)) == 1):
        minutes = "0" + str(minutes)
    if (len(str(seconds)) == 1):
        seconds = "0" + str(seconds)
    formatted_duration = str(days) + ":" + str(hours) + ":" + str(minutes) + ":" + str(seconds)
    return formatted_duration


# -- coding: utf-8 --
import torch.nn.init as init
import math

def weights_init(init_type='gaussian'):
    def init_fun(model):
        classname = model.__class__.__name__
        if (classname.find('Conv') == 0 or classname.find('Linear') == 0) and hasattr(m, 'weight'):
            if init_type == 'gaussian':
                init.normal_(model.weight.data, 0.0, 0.02)
            elif init_type == 'xavier':
                init.xavier_normal_(model.weight.data, gain=math.sqrt(2))
            elif init_type == 'kaiming':
                init.kaiming_normal_(model.weight.data, a=0, mode='fan_in')
            elif init_type == 'orthogonal':
                init.orthogonal_(model.weight.data, gain=math.sqrt(2))
            elif init_type == 'default':
                pass
            else:
                assert 0, "Unsupported initialization: {}".format(init_type)

            if hasattr(model, 'bias') and model.bias is not None:
                init.constant_(model.bias.data, 0.0)

    return init_fun


# blender CAM ops.py (c) 2012 Vilem Novak
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****

# blender operators definitions are in this file. They mostly call the functions from utils.py

import bpy
from bpy.props import *
from bpy_extras.io_utils import ImportHelper

import subprocess, os, threading
from cam import utils, pack, polygon_utils_cam, simple, gcodepath, bridges, simulation
import shapely
import mathutils
import math
import cam
from cam.exception import *

class threadCom:  # object passed to threads to read background process stdout info
    def __init__(self, o, proc):
        self.opname = o.name
        self.outtext = ''
        self.proc = proc
        self.lasttext = ''

def threadread(tcom):
    """reads stdout of background process, done this way to have it non-blocking"""
    inline = tcom.proc.stdout.readline()
    inline = str(inline)
    s = inline.find('progress{')
    if s > -1:
        e = inline.find('}')
        tcom.outtext = inline[s + 9:e]

@bpy.app.handlers.persistent
def timer_update(context):
    """monitoring of background processes"""
    text = ''
    s = bpy.context.scene
    if hasattr(bpy.ops.object.calculate_cam_paths_background.__class__, 'cam_processes'):
        processes = bpy.ops.object.calculate_cam_paths_background.__class__.cam_processes
        for p in processes:
            # proc=p[1].proc
            readthread = p[0]
            tcom = p[1]
            if not readthread.is_alive():
                readthread.join()
                # readthread.
                tcom.lasttext = tcom.outtext
                if tcom.outtext != '':
                    print(tcom.opname, tcom.outtext)
                    tcom.outtext = ''

                if 'finished' in tcom.lasttext:
                    processes.remove(p)

                    o = s.cam_operations[tcom.opname]
                    o.computing = False
                    utils.reload_paths(o)
                    update_zbufferimage_tag = False
                    update_offsetimage_tag = False
                else:
                    readthread = threading.Thread(target=threadread, args=([tcom]), daemon=True)
                    readthread.start()
                    p[0] = readthread
            o = s.cam_operations[tcom.opname]  # changes
            o.outtext = tcom.lasttext  # changes

class PathsBackground(bpy.types.Operator):
    """calculate CAM paths in background. File has to be saved before."""
    bl_idname = "object.calculate_cam_paths_background"
    bl_label = "Calculate CAM paths in background"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        s = bpy.context.scene
        o = s.cam_operations[s.cam_active_operation]
        self.operation = o
        o.computing = True

        bpath = bpy.app.binary_path
        fpath = bpy.data.filepath

        for p in bpy.utils.script_paths():
            scriptpath = p + os.sep + 'addons' + os.sep + 'cam' + os.sep + 'backgroundop.py'
            print(scriptpath)
            if os.path.isfile(scriptpath):
                break
        proc = subprocess.Popen([bpath, '-b', fpath, '-P', scriptpath, '--', '-o=' + str(s.cam_active_operation)],
                                bufsize=1, stdout=subprocess.PIPE, stdin=subprocess.PIPE)

        tcom = threadCom(o, proc)
        readthread = threading.Thread(target=threadread, args=([tcom]), daemon=True)
        readthread.start()
        # self.__class__.cam_processes=[]
        if not hasattr(bpy.ops.object.calculate_cam_paths_background.__class__, 'cam_processes'):
            bpy.ops.object.calculate_cam_paths_background.__class__.cam_processes = []
        bpy.ops.object.calculate_cam_paths_background.__class__.cam_processes.append([readthread, tcom])
        return {'FINISHED'}

class KillPathsBackground(bpy.types.Operator):
    """Remove CAM path processes in background."""
    bl_idname = "object.kill_calculate_cam_paths_background"
    bl_label = "Kill background computation of an operation"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        s = bpy.context.scene
        o = s.cam_operations[s.cam_active_operation]
        self.operation = o

        if hasattr(bpy.ops.object.calculate_cam_paths_background.__class__, 'cam_processes'):
            processes = bpy.ops.object.calculate_cam_paths_background.__class__.cam_processes
            for p in processes:
                tcom = p[1]
                if tcom.opname == o.name:
                    processes.remove(p)
                    tcom.proc.kill()
                    o.computing = False

        return {'FINISHED'}

class CalculatePath(bpy.types.Operator):
    """calculate CAM paths"""
    bl_idname = "object.calculate_cam_path"
    bl_label = "Calculate CAM paths"
    bl_options = {'REGISTER', 'UNDO'}

    # this property was actually ignored, so removing it in 0.3
    # operation= StringProperty(name="Operation", description="Specify the operation to calculate",default='Operation')

    def execute(self, context):
        print("CALCULATE")
        # getIslands(context.object)
        s = bpy.context.scene
        o = s.cam_operations[s.cam_active_operation]
        if o.geometry_source == 'OBJECT':
            ob = bpy.data.objects[o.object_name]
            ob.hide_set(False)
        if o.geometry_source == 'COLLECTION':
            obc = bpy.data.collections[o.collection_name]
            for ob in obc.objects:
                ob.hide_set(False)
        if o.strategy == "CARVE":
            curvob = bpy.data.objects[o.curve_object]
            curvob.hide_set(False)
        print(bpy.context.mode)
        if bpy.context.mode != 'OBJECT':
            bpy.ops.object.mode_set(mode='OBJECT')	    # force object mode
        bpy.ops.object.select_all(action='DESELECT')
        path = bpy.data.objects.get('cam_path_{}'.format(o.name))
        if path:
            path.select_set(state=True)
            bpy.ops.object.delete()

        if not o.valid:
            self.report({'ERROR_INVALID_INPUT'}, "Operation can't be performed, see warnings for info")
            print("Operation can't be performed, see warnings for info")
            return {'CANCELLED'}

        #check for free movement height < maxz and return with error
        if(o.movement.free_height < o.maxz):
            self.report({'ERROR_INVALID_INPUT'}, "Free movement height is less than Operation depth start \n correct and try again.")
            return {'CANCELLED'}

        if o.computing:
            return {'FINISHED'}

        o.operator = self

        if o.use_layers:
            o.movement.parallel_step_back = False
        try:
            gcodepath.getPath(context, o)
        except CamException as e:
            self.report({'ERROR'},str(e))
            return {'CANCELLED'}
        coll = bpy.data.collections.get('RigidBodyWorld')
        if coll:
            bpy.data.collections.remove(coll)

        return {'FINISHED'}

class PathsAll(bpy.types.Operator):
    """calculate all CAM paths"""
    bl_idname = "object.calculate_cam_paths_all"
    bl_label = "Calculate all CAM paths"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        i = 0
        for o in bpy.context.scene.cam_operations:
            bpy.context.scene.cam_active_operation = i
            print('\nCalculating path :' + o.name)
            print('\n')
            bpy.ops.object.calculate_cam_paths_background()
            i += 1

        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout
        layout.prop_search(self, "operation", bpy.context.scene, "cam_operations")

class CamPackObjects(bpy.types.Operator):
    """calculate all CAM paths"""
    bl_idname = "object.cam_pack_objects"
    bl_label = "Pack curves on sheet"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.ops.object.mode_set(mode='OBJECT')	    # force object mode
        obs = bpy.context.selected_objects
        pack.packCurves()
        # layout.
        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout

class CamSliceObjects(bpy.types.Operator):
    """Slice a mesh object horizontally"""
    # warning, this is a separate and neglected feature, it's a mess - by now it just slices up the object.
    bl_idname = "object.cam_slice_objects"
    bl_label = "Slice object - usefull for lasercut puzzles e.t.c."
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        from cam import slice
        ob = bpy.context.active_object
        slice.sliceObject(ob)
        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout

def getChainOperations(chain):
    """return chain operations, currently chain object can't store operations directly due to blender limitations"""
    chop = []
    for cho in chain.operations:
        for so in bpy.context.scene.cam_operations:
            if so.name == cho.name:
                chop.append(so)
    return chop

class PathsChain(bpy.types.Operator):
    """calculate a chain and export the gcode alltogether. """
    bl_idname = "object.calculate_cam_paths_chain"
    bl_label = "Calculate CAM paths in current chain and export chain gcode"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        s = bpy.context.scene
        bpy.ops.object.mode_set(mode='OBJECT')	    # force object mode
        chain = s.cam_chains[s.cam_active_chain]
        chainops = getChainOperations(chain)
        meshes = []

        # if len(chainops)<4:
        for i in range(0, len(chainops)):
            s.cam_active_operation = s.cam_operations.find(chainops[i].name)
            bpy.ops.object.calculate_cam_path()

        for o in chainops:
            # bpy.ops.object.calculate_cam_paths_background()
            meshes.append(bpy.data.objects["cam_path_{}".format(o.name)].data)
        gcodepath.exportGcodePath(chain.filename, meshes, chainops)
        return {'FINISHED'}

class PathExportChain(bpy.types.Operator):
    """calculate a chain and export the gcode alltogether. """
    bl_idname = "object.cam_export_paths_chain"
    bl_label = "Export CAM paths in current chain as gcode"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        s = bpy.context.scene

        chain = s.cam_chains[s.cam_active_chain]
        chainops = getChainOperations(chain)
        meshes = []

        # if len(chainops)<4:

        for o in chainops:
            # bpy.ops.object.calculate_cam_paths_background()
            meshes.append(bpy.data.objects["cam_path_{}".format(o.name)].data)
        gcodepath.exportGcodePath(chain.filename, meshes, chainops)
        return {'FINISHED'}

class PathExport(bpy.types.Operator):
    """Export gcode. Can be used only when the path object is present"""
    bl_idname = "object.cam_export"
    bl_label = "Export operation gcode"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):

        s = bpy.context.scene
        operation = s.cam_operations[s.cam_active_operation]

        print("EXPORTING", operation.filename, bpy.data.objects["cam_path_{}".format(operation.name)].data, operation)

        gcodepath.exportGcodePath(operation.filename, [bpy.data.objects["cam_path_{}".format(operation.name)].data],
                                  [operation])
        return {'FINISHED'}

class CAMSimulate(bpy.types.Operator):
    """simulate CAM operation
    this is performed by: creating an image, painting Z depth of the brush substractively.
    Works only for some operations, can not be used for 4-5 axis."""
    bl_idname = "object.cam_simulate"
    bl_label = "CAM simulation"
    bl_options = {'REGISTER', 'UNDO'}

    operation: StringProperty(name="Operation",
                              description="Specify the operation to calculate", default='Operation')

    def execute(self, context):
        s = bpy.context.scene
        operation = s.cam_operations[s.cam_active_operation]

        operation_name = "cam_path_{}".format(operation.name)

        if operation_name in bpy.data.objects:
            simulation.doSimulation(operation_name, [operation])
        else:
            print('no computed path to simulate')
            return {'FINISHED'}
        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout
        layout.prop_search(self, "operation", bpy.context.scene, "cam_operations")

class CAMSimulateChain(bpy.types.Operator):
    """simulate CAM chain, compared to single op simulation just writes into one image and thus enables
    to see how ops work together."""
    bl_idname = "object.cam_simulate_chain"
    bl_label = "CAM simulation"
    bl_options = {'REGISTER', 'UNDO'}

    operation: StringProperty(name="Operation",
                              description="Specify the operation to calculate", default='Operation')

    def execute(self, context):
        s = bpy.context.scene
        chain = s.cam_chains[s.cam_active_chain]
        chainops = getChainOperations(chain)

        canSimulate = True
        for operation in chainops:
            if operation.name not in bpy.data.objects:
                canSimulate = True  # force true
            print("operation name " + str(operation.name))
        if canSimulate:
            simulation.doSimulation(chain.name, chainops)
        else:
            print('no computed path to simulate')
            return {'FINISHED'}
        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout
        layout.prop_search(self, "operation", bpy.context.scene, "cam_operations")

class CamChainAdd(bpy.types.Operator):
    """Add new CAM chain"""
    bl_idname = "scene.cam_chain_add"
    bl_label = "Add new CAM chain"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        # main(context)
        s = bpy.context.scene
        s.cam_chains.add()
        chain = s.cam_chains[-1]
        s.cam_active_chain = len(s.cam_chains) - 1
        chain.name = 'Chain_' + str(s.cam_active_chain + 1)
        chain.filename = chain.name
        chain.index = s.cam_active_chain

        return {'FINISHED'}

class CamChainRemove(bpy.types.Operator):
    """Remove  CAM chain"""
    bl_idname = "scene.cam_chain_remove"
    bl_label = "Remove CAM chain"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        bpy.context.scene.cam_chains.remove(bpy.context.scene.cam_active_chain)
        if bpy.context.scene.cam_active_chain > 0:
            bpy.context.scene.cam_active_chain -= 1

        return {'FINISHED'}

class CamChainOperationAdd(bpy.types.Operator):
    """Add operation to chain"""
    bl_idname = "scene.cam_chain_operation_add"
    bl_label = "Add operation to chain"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        chain = s.cam_chains[s.cam_active_chain]
        s = bpy.context.scene
        chain.operations.add()
        chain.active_operation += 1
        chain.operations[-1].name = s.cam_operations[s.cam_active_operation].name
        return {'FINISHED'}

class CamChainOperationUp(bpy.types.Operator):
    """Add operation to chain"""
    bl_idname = "scene.cam_chain_operation_up"
    bl_label = "Add operation to chain"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        chain = s.cam_chains[s.cam_active_chain]
        a = chain.active_operation
        if a > 0:
            chain.operations.move(a, a - 1)
            chain.active_operation -= 1
        return {'FINISHED'}

class CamChainOperationDown(bpy.types.Operator):
    """Add operation to chain"""
    bl_idname = "scene.cam_chain_operation_down"
    bl_label = "Add operation to chain"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        chain = s.cam_chains[s.cam_active_chain]
        a = chain.active_operation
        if a < len(chain.operations) - 1:
            chain.operations.move(a, a + 1)
            chain.active_operation += 1
        return {'FINISHED'}

class CamChainOperationRemove(bpy.types.Operator):
    """Remove operation from chain"""
    bl_idname = "scene.cam_chain_operation_remove"
    bl_label = "Remove operation from chain"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        chain = s.cam_chains[s.cam_active_chain]
        chain.operations.remove(chain.active_operation)
        chain.active_operation -= 1
        if chain.active_operation < 0:
            chain.active_operation = 0
        return {'FINISHED'}

def fixUnits():
    """Sets up units for blender CAM"""
    s = bpy.context.scene

    s.unit_settings.system_rotation = 'DEGREES'

    s.unit_settings.scale_length = 1.0
    # Blender CAM doesn't respect this property and there were users reporting problems, not seeing this was changed.

# add pocket op for medial axis and profile cut inside to clean unremoved material
def Add_Pocket(self, maxdepth, sname, new_cutter_diameter):
    bpy.ops.object.select_all(action='DESELECT')
    s = bpy.context.scene
    mpocket_exists = False
    for ob in s.objects:  # delete old medial pocket
        if ob.name.startswith("medial_poc"):
            ob.select_set(True)
            bpy.ops.object.delete()

    for op in s.cam_operations:  # verify medial pocket operation exists
        if op.name == "MedialPocket":
            mpocket_exists = True

    ob = bpy.data.objects[sname]
    ob.select_set(True)
    bpy.context.view_layer.objects.active = ob
    utils.silhoueteOffset(ob, -new_cutter_diameter/2, 1, 0.3)
    bpy.context.active_object.name = 'medial_pocket'

    if not mpocket_exists:     # create a pocket operation if it does not exist already
        s.cam_operations.add()
        o = s.cam_operations[-1]
        o.object_name= 'medial_pocket'
        s.cam_active_operation = len(s.cam_operations) - 1
        o.name = 'MedialPocket'
        o.filename = o.name
        o.strategy = 'POCKET'
        o.use_layers = False
        o.material.estimate_from_model = False
        o.material.size[2] = -maxdepth
        o.minz_from = 'MATERIAL'

class CamOperationAdd(bpy.types.Operator):
    """Add new CAM operation"""
    bl_idname = "scene.cam_operation_add"
    bl_label = "Add new CAM operation"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        fixUnits()

        ob = bpy.context.active_object
        if ob is None:
            self.report({'ERROR_INVALID_INPUT'}, "Please add an object to base the operation on.")
            return {'CANCELLED'}

        minx, miny, minz, maxx, maxy, maxz = utils.getBoundsWorldspace([ob])
        s.cam_operations.add()
        o = s.cam_operations[-1]
        o.object_name = ob.name
        o.minz = minz

        s.cam_active_operation = len(s.cam_operations) - 1

        o.name = f"Op_{ob.name}_{s.cam_active_operation + 1}"
        o.filename = o.name

        if s.objects.get('CAM_machine') is None:
            utils.addMachineAreaObject()

        return {'FINISHED'}

class CamOperationCopy(bpy.types.Operator):
    """Copy CAM operation"""
    bl_idname = "scene.cam_operation_copy"
    bl_label = "Copy active CAM operation"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        # main(context)
        scene = bpy.context.scene

        fixUnits()

        scene = bpy.context.scene
        if len(scene.cam_operations) == 0: return {'CANCELLED'}
        copyop = scene.cam_operations[scene.cam_active_operation]
        scene.cam_operations.add()
        scene.cam_active_operation += 1
        l = len(scene.cam_operations) - 1
        scene.cam_operations.move(l, scene.cam_active_operation)
        o = scene.cam_operations[scene.cam_active_operation]

        for k in copyop.keys():
            o[k] = copyop[k]
        o.computing = False

        # ###get digits in the end

        isdigit = True
        numdigits = 0
        num = 0
        if o.name[-1].isdigit():
            numdigits = 1
            while isdigit:
                numdigits += 1
                isdigit = o.name[-numdigits].isdigit()
            numdigits -= 1
            o.name = o.name[:-numdigits] + str(int(o.name[-numdigits:]) + 1).zfill(numdigits)
            o.filename = o.name
        else:
            o.name = o.name + '_copy'
            o.filename = o.filename + '_copy'

        return {'FINISHED'}

class CamOperationRemove(bpy.types.Operator):
    """Remove CAM operation"""
    bl_idname = "scene.cam_operation_remove"
    bl_label = "Remove CAM operation"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        scene = context.scene
        try:
            if len(scene.cam_operations) == 0: return {'CANCELLED'}
            active_op = scene.cam_operations[scene.cam_active_operation]
            active_op_object = bpy.data.objects[active_op.name]
            scene.objects.active = active_op_object
            bpy.ops.object.delete(True)
        except:
            pass

        ao = scene.cam_operations[scene.cam_active_operation]
        print(cam.was_hidden_dict)
        if ao.name in cam.was_hidden_dict:
            del cam.was_hidden_dict[ao.name]

        scene.cam_operations.remove(scene.cam_active_operation)
        if scene.cam_active_operation > 0:
            scene.cam_active_operation -= 1

        return {'FINISHED'}

# move cam operation in the list up or down
class CamOperationMove(bpy.types.Operator):
    """Move CAM operation"""
    bl_idname = "scene.cam_operation_move"
    bl_label = "Move CAM operation in list"
    bl_options = {'REGISTER', 'UNDO'}

    direction: EnumProperty(name='direction',
                            items=(('UP', 'Up', ''), ('DOWN', 'Down', '')),
                            description='direction', default='DOWN')

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        # main(context)
        a = bpy.context.scene.cam_active_operation
        cops = bpy.context.scene.cam_operations
        if self.direction == 'UP':
            if a > 0:
                cops.move(a, a - 1)
                bpy.context.scene.cam_active_operation -= 1

        else:
            if a < len(cops) - 1:
                cops.move(a, a + 1)
                bpy.context.scene.cam_active_operation += 1

        return {'FINISHED'}

class CamOrientationAdd(bpy.types.Operator):
    """Add orientation to cam operation, for multiaxis operations"""
    bl_idname = "scene.cam_orientation_add"
    bl_label = "Add orientation"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        a = s.cam_active_operation
        o = s.cam_operations[a]
        gname = o.name + '_orientations'
        bpy.ops.object.empty_add(type='ARROWS')

        oriob = bpy.context.active_object
        oriob.empty_draw_size = 0.02  # 2 cm

        simple.addToGroup(oriob, gname)
        oriob.name = 'ori_' + o.name + '.' + str(len(bpy.data.collections[gname].objects)).zfill(3)

        return {'FINISHED'}

class CamBridgesAdd(bpy.types.Operator):
    """Add bridge objects to curve"""
    bl_idname = "scene.cam_bridges_add"
    bl_label = "Add bridges"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.scene is not None

    def execute(self, context):
        s = bpy.context.scene
        a = s.cam_active_operation
        o = s.cam_operations[a]
        bridges.addAutoBridges(o)
        return {'FINISHED'}


#  coding utf-8
# @time      :2019/6/24 17:09
# @Author    :zjunbin
# @Email     :648060307@qq.com
# @File      :alarm_first.py
from common.basepage import BasePage
from PageLocator.Alarm_locator import Alarm as loc
from Testdatas import common_data

class AlarmPage(BasePage):

    def alarm_first(self, value):
        self.switch_iframe(iframe=loc.alarm_page)
        self.wait_element_Visible(locator=loc.idcard,model_name='接警第一步')
        self.input_text(model_name='接警第一步输入信息',locator=loc.idcard,value=value)
        self.click_element(model_name='接警第一步信息提交提交',locator=loc.btn)

    def get_message(self):
        self.switch_iframe(iframe=loc.alarm_page)
        self.wait_element_Visible(locator=loc.lblResult,model_name='')
        ele = self.get_element_text(locator=loc.lblResult,model_name='')
        return ele


'''
Problem 3
 What happens when the above sum function is called with a list of strings? Can you make your sum function work for a list of strings as well.

>>> sum(["hello", "world"])
"helloworld"
>>> sum(["aa", "bb", "cc"])
"aabbcc" '''

def sum(l):
    string = ''
    for s in l:
        string += s
    return string

print(sum(["hello", "world"]))


input = [" " + line[:-1] + " " for line in open("input").readlines()]

input = [" " * len(input[0])] + input + [" " * len(input[0])]

x, y, h = input[1].index("|"), 0, "s"
move = {
    "s": (0, 1),
    "w": (-1, 0),
    "n": (0, -1),
    "e": (1, 0)
}

chars = ""
while True:
    x += move[h][0]
    y += move[h][1]

    if input[y][x] == " ":
        break

    if input[y][x] == "+":
        if h in "ns":
            if input[y][x - 1] != " ":
                h = "w"
            elif input[y][x + 1] != " ":
                h = "e"
        else:
            if input[y - 1][x] != " ":
                h = "n"
            elif input[y + 1][x] != " ":
                h = "s"
    elif input[y][x] not in "|-":
        chars += input[y][x]

print(chars)


def add_quiet_option(parser):
    parser.add_option(
        "-q", "--quiet", action="store_false", dest="verbose", default=True,
        help="Don't print any output."
    )

def add_slice_option(parser):
    parser.add_option(
        "-s", "--slice", default="::",
        help="Subsample the (time dependent) input tracks with the given slice "
             "start:stop:step where start, stop and step must be integers or "
             "can be omitted. The slice interpretation is pythonic. "
             "[default=%default]",
    )

def add_append_option(parser):
    parser.add_option(
        "--append", action="store_false", dest="clear", default=True,
        help="Append to existing tracks if possible."
    )

def add_cell_option(parser):
    parser.add_option(
        "-c", "--cell", dest="unit_cell_str", default=None,
        help="Take into account the given periodic boundary conditions. "
             "The unit cell parameters. Several formats are supported. "
             "(i) 'a,' A cubic unit cell with ridge a. "
             "(ii) 'a,b,c' The parameters of an orthorhombic cell. "
             "(iii) 'a,b,c,alpha,beta,gamma' The parameters for a triclinic cell. "
             "(iv) 'ax,ay,az,bx,by,bz,cx,cy,cz' The cartesian parameters for a triclinic cell. "
             "(v) 'cell_prefix' A track prefix can be used for a time dependent unit cell. "
             "The presence of comma's is used to differentiate between all "
             "the possibilities."
    )

def add_cos_option(parser):
    parser.add_option(
        "--cos", action="store_true", default=False,
        help="Compute the cosine instead of the angle."
    )

def add_filter_atoms_option(parser):
    parser.add_option(
        "-a", "--filter-atoms",
        help="Only consider the atoms listed in FILTER_ATOMS. FILTER_ATOMS is a "
             "comma separated list of of integers. Counting starts at zero.",
    )

def add_ic_project_option(parser, name):
    parser.add_option(
        "-p", "--project", action="store_true", default=False,
        help="Project the cartesian velocity vector on the tangents of the internal"
             "coordinate. (in this case %s)" % name,
    )

def add_select_options(parser):
    parser.add_option(
        "-p", "--prefix", help="Format the indexes with the given prefix. The "
        "output will look like 'PREFIX.0000000 PREFIX.0000001 ...'"
    )
    parser.add_option(
        "--xyz", action='store_true', default=False,
        help="Append x, y and z extension to the prefixes. (Only applicable when "
        "-p is used. The output will look like 'PREFIX.0000000.x prefix.0000000.y "
        "PREFIX.0000000.z PREFIX.0000001.x ...'"
    )

def add_cor_time_unit(parser):
    parser.add_option(
        "-t", "--time-unit", default='au',
        help="The correlation time is printed in the given TIME_UNIT. [default=%default]",
    )

def add_blocks_option(parser):
    parser.add_option(
        "-b", "--blocks", default="1",
        help="The input data is divided in BLOCKS and the final "
        "power spectrum is the average over all the power spectra of the distinct "
        "blocks. This reduces the noise in the amplitude vector, but it also "
        "reduces the resolution on the frequency/wavenumber axis. "
        "[default=%default]"
    )

def add_pca_options(parser, default_unit):
    parser.add_option(
        "-c", "--corr-coeff", action="store_true", default=False,
        help="Perform pca on the correlation coefficient matrix instead of the "
             "covariance matrix.",
    )
    parser.add_option(
        "-p", "--dump-pcs", action="store_true", default=False,
        help="Dump the principal components in the tracks database",
    )
    parser.add_option(
        "-n", "--num-levels", default=2, type="int",
        help="The number of levels of block sizes to run the pca. "
             "[default=%default]. At least 2."
    )
    parser.add_option(
        "-u", "--unit", default=default_unit,
        help="The unit in which the sigma's are printed on screen. [default=%default]",
    )

def add_zero_mean_option(parser):
    parser.add_option(
        "-z", "--zero-mean", action="store_true", default=False,
        help="Do not substract the mean from the input tracks prior to pca.",
    )