#!/usr/bin/env python
# -*- coding: euc-jp -*-

#
# \file test_CORBA_RTCUtil.py
# \brief
# \date $Date: $
# \author Nobuhiko Miyamoto
#

import sys
sys.path.insert(1,"../")

try:
    import unittest2 as unittest
except (ImportError):
    import unittest

import time

#from Manager import *
import OpenRTM_aist
import RTC, RTC__POA
import OpenRTM, OpenRTM__POA

testcomp1_spec = ["implementation_id", "TestComp1",
                 "type_name",         "TestComp1",
                 "description",       "Test example component",
                 "version",           "1.0",
                 "vendor",            "Nobuhiko Myiyamoto",
                 "category",          "example",
                 "activity_type",     "DataFlowComponent",
                 "max_instance",      "10",
                 "language",          "C++",
                 "lang_type",         "compile",
                 "conf.default.test1", "0",
                 ""]

testcomp2_spec = ["implementation_id", "TestComp2",
                 "type_name",         "TestComp2",
                 "description",       "Test example component",
                 "version",           "1.0",
                 "vendor",            "Nobuhiko Myiyamoto",
                 "category",          "example",
                 "activity_type",     "DataFlowComponent",
                 "max_instance",      "10",
                 "language",          "C++",
                 "lang_type",         "compile",
                 ""]

class Test_i(OpenRTM__POA.InPortCdr):
  def __init__(self):
    pass
  def put(self, data):
    return OpenRTM.PORT_OK

class TestComp1(OpenRTM_aist.DataFlowComponentBase):
  def __init__(self, manager):
    OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
    self._d_out = RTC.TimedLong(RTC.Time(0,0),0)
    self._outOut = OpenRTM_aist.OutPort("out", self._d_out)
    self._d_in = RTC.TimedLong(RTC.Time(0,0),0)
    self._inIn = OpenRTM_aist.InPort("in", self._d_in)

    self._servicePort_provided = OpenRTM_aist.CorbaPort("service")
    self._testService_provided = Test_i()

    self._test1 = [0]

  def onInitialize(self):
    self.addOutPort("out",self._outOut)
    self.addInPort("in",self._inIn)

    self._servicePort_provided.registerProvider("service", "TestService", self._testService_provided)
    self.addPort(self._servicePort_provided)

    self.bindParameter("test1", self._test1, "0")

    return RTC.RTC_OK

class TestComp2(OpenRTM_aist.DataFlowComponentBase):
  def __init__(self, manager):
    OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
    self._d_out = RTC.TimedLong(RTC.Time(0,0),0)
    self._outOut = OpenRTM_aist.OutPort("out", self._d_out)
    self._d_in = RTC.TimedLong(RTC.Time(0,0),0)
    self._inIn = OpenRTM_aist.InPort("in", self._d_in)

    self._servicePort_required = OpenRTM_aist.CorbaPort("service")
    self._testService_required = OpenRTM_aist.CorbaConsumer(interfaceType=OpenRTM.InPortCdr)

    return

  def onInitialize(self):
    self.addInPort("in",self._inIn)
    self.addOutPort("out",self._outOut)

    self._servicePort_required.registerConsumer("service", "TestService", self._testService_required)
    self.addPort(self._servicePort_required)

    return RTC.RTC_OK

def TestComp1Init(manager):
  profile = OpenRTM_aist.Properties(defaults_str=testcomp1_spec)
  manager.registerFactory(profile,
                          TestComp1,
                          OpenRTM_aist.Delete)

def TestComp2Init(manager):
  profile = OpenRTM_aist.Properties(defaults_str=testcomp2_spec)
  manager.registerFactory(profile,
                          TestComp2,
                          OpenRTM_aist.Delete)

def MyModuleInit(manager):
  TestComp1Init(manager)
  TestComp2Init(manager)
  com = manager.createComponent("TestComp1")
  com = manager.createComponent("TestComp2")

class Test_CORBA_RTCUtil(unittest.TestCase):

  def setUp(self):
    sys.argv.extend(['-d'])
    sys.argv.extend(['-o', 'exec_cxt.periodic.rate:1000'])
    sys.argv.extend(['-o','naming.type:corba,manager'])
    self.manager = OpenRTM_aist.Manager.init(sys.argv)
    self.manager.setModuleInitProc(MyModuleInit)
    self.manager.activateManager()

    self.comp1 = self.manager.getComponent("TestComp10").getObjRef()
    self.comp2 = self.manager.getComponent("TestComp20").getObjRef()

  def tearDown(self):
    comps = self.manager.getComponents()[:]
    for comp in comps:
        self.manager.unregisterComponent(comp)
        comp_id = comp.getProperties()
        factory = self.manager._factory.find(comp_id)
        factory.destroy(comp)
    self.manager.shutdownNaming()
    time.sleep(0.1)

  def test_Component(self):
    compProf = OpenRTM_aist.get_component_profile(self.comp1)
    self.assertEqual(compProf.getProperty("implementation_id"), "TestComp1")
    ret = OpenRTM_aist.is_existing(self.comp1)
    self.assertTrue(ret)

  def test_EC(self):
    ec = OpenRTM_aist.get_actual_ec(self.comp1,0)
    ec_id = OpenRTM_aist.get_ec_id(self.comp1, ec)
    self.assertEqual(ec_id, 0)

    ret = OpenRTM_aist.add_rtc_to_default_ec(self.comp1, self.comp2)
    self.assertEqual(ret, RTC.RTC_OK)

    ret = OpenRTM_aist.is_alive_in_default_ec(self.comp1)
    self.assertEqual(ret, True)

    ret = OpenRTM_aist.set_default_rate(self.comp1, 500)
    self.assertEqual(ret, RTC.RTC_OK)

    rate = OpenRTM_aist.get_default_rate(self.comp1)
    self.assertEqual(int(rate), 500)

    ret = OpenRTM_aist.set_current_rate(self.comp2,1000, 100)
    self.assertEqual(ret, RTC.RTC_OK)

    rate = OpenRTM_aist.get_current_rate(self.comp2, 1000)
    self.assertEqual(int(rate), 100)

    ret = OpenRTM_aist.activate(self.comp1,0)
    self.assertEqual(ret, RTC.RTC_OK)
    state = OpenRTM_aist.is_in_active(self.comp1, 0)
    self.assertTrue(state)

    ret = OpenRTM_aist.deactivate(self.comp1,0)
    self.assertEqual(ret, RTC.RTC_OK)
    state = OpenRTM_aist.is_in_inactive(self.comp1, 0)
    self.assertTrue(state)

    #state = OpenRTM_aist.is_in_error(self.comp1, 0)
    #ret = OpenRTM_aist.reset(self.comp1,0)
    #self.assertEqual(ret, RTC.RTC_OK)

    ret = [None]
    ans = OpenRTM_aist.get_state(ret, self.comp1, 0)
    self.assertEqual(ret[0], RTC.INACTIVE_STATE)

    ret = OpenRTM_aist.remove_rtc_to_default_ec(self.comp1, self.comp2)
    self.assertEqual(ret, RTC.RTC_OK)

  def test_Port(self):
    port_names = OpenRTM_aist.get_port_names(self.comp1)
    self.assertTrue("TestComp10.out" in port_names)

    inport_names = OpenRTM_aist.get_inport_names(self.comp2)
    self.assertTrue("TestComp20.in" in inport_names)

    outport_names = OpenRTM_aist.get_outport_names(self.comp1)
    self.assertTrue("TestComp10.out" in outport_names)

    svcport_names = OpenRTM_aist.get_svcport_names(self.comp1)
    self.assertTrue("TestComp10.service" in svcport_names)

    rtc1_port_out = OpenRTM_aist.get_port_by_name(self.comp1,"TestComp10.out")
    rtc2_port_out = OpenRTM_aist.get_port_by_name(self.comp2,"TestComp20.out")
    rtc2_port_in = OpenRTM_aist.get_port_by_name(self.comp2,"TestComp20.in")
    rtc1_port_in = OpenRTM_aist.get_port_by_name(self.comp1,"TestComp10.in")

    pp = rtc1_port_out.get_port_profile()
    self.assertEqual(pp.name, "TestComp10.out")

    prop = OpenRTM_aist.Properties()
    connect_profile = OpenRTM_aist.create_connector("con1",prop,rtc1_port_out,rtc2_port_in)
    ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in)
    self.assertEqual(ret, RTC.RTC_OK)

    con_names = OpenRTM_aist.get_connector_names_by_portref(rtc1_port_out)
    self.assertTrue("con1" in con_names)
    con_names = OpenRTM_aist.get_connector_names(self.comp1,"TestComp10.out")
    self.assertTrue("con1" in con_names)
    con_ids = OpenRTM_aist.get_connector_ids_by_portref(rtc1_port_out)
    con_ids = OpenRTM_aist.get_connector_ids(self.comp1,"TestComp10.out")

    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertTrue(ret)

    ret = OpenRTM_aist.disconnect(rtc1_port_out.get_connector_profiles()[0])
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect_multi("con2",prop,rtc1_port_out,[rtc1_port_in,rtc2_port_in])
    self.assertEqual(ret, RTC.RTC_OK)

    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc1_port_in)
    self.assertTrue(ret)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertTrue(ret)

    ret = OpenRTM_aist.disconnect_all_by_ref(rtc1_port_out)
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect_by_name("con3",prop,self.comp1,"TestComp10.out",self.comp2,"TestComp20.in")
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertTrue(ret)

    ret = OpenRTM_aist.disconnect_by_portref_connector_name(rtc1_port_out, "con3")
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in)
    ret = OpenRTM_aist.disconnect_by_portref_connector_id(rtc1_port_out,rtc1_port_out.get_connector_profiles()[0].connector_id)
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in)
    ret = OpenRTM_aist.disconnect_by_port_name(rtc1_port_out,"TestComp20.in")
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in)
    ret = OpenRTM_aist.disconnect_all_by_name("rtcloc://localhost:2810/example/TestComp20.in")
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in)
    ret = OpenRTM_aist.disconnect_by_portname_connector_name("rtcloc://localhost:2810/example/TestComp20.in","con1")
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

    ret = OpenRTM_aist.connect("con1",prop,rtc1_port_out,rtc2_port_in)
    ret = OpenRTM_aist.disconnect_by_portname_connector_id("rtcloc://localhost:2810/example/TestComp10.out",rtc1_port_out.get_connector_profiles()[0].connector_id)
    self.assertEqual(ret, RTC.RTC_OK)
    ret = OpenRTM_aist.already_connected(rtc1_port_out,rtc2_port_in)
    self.assertFalse(ret)

  def test_configuration(self):
    conf = OpenRTM_aist.get_configuration(self.comp1, "default")
    self.assertEqual(conf.getProperty("test1"),"0")

    ret = OpenRTM_aist.get_parameter_by_key(self.comp1,"default","test1")
    self.assertEqual(ret,"0")

    conf = OpenRTM_aist.get_active_configuration(self.comp1)
    self.assertEqual(conf.getProperty("test1"),"0")

    ret = OpenRTM_aist.set_configuration(self.comp1,"default","test1","1")
    self.assertTrue(ret)
    ret = OpenRTM_aist.get_parameter_by_key(self.comp1,"default","test1")
    self.assertEqual(ret,"1")

    ret = OpenRTM_aist.set_active_configuration(self.comp1,"test1","2")
    self.assertTrue(ret)
    ret = OpenRTM_aist.get_parameter_by_key(self.comp1,"default","test1")
    self.assertEqual(ret,"2")

    confsetname = OpenRTM_aist.get_active_configuration_name(self.comp1)
    self.assertEqual(confsetname,"default")

    #ec = self.comp1.get_owned_contexts()[0]

    #print OpenRTM_aist.get_participants_rtc(ec)

    #print ec.add_component(self.comp2)
    #print ec.get_profile()
    #prop = OpenRTM_aist.Properties()
    #conf = self.comp1.get_configuration()
    #print conf.get_configuration_sets()
    #confsets = conf.get_configuration_sets()
    #print confsets
    #OpenRTM_aist.NVUtil.copyToProperties(prop,confsets)
    #print prop
    # self.comp1.get_status_list()

############### test #################
if __name__ == '__main__':
        unittest.main()


f = open("regex_sum_1482698.txt")
import re #import regex
total = 0
totalvals = list()

for line in f:
    x= re.findall('[0-9]+' , line) #find all numbers
    if x: #if found
       totalvals.extend(x) #extend the list, append does not work because it will make lists within lists

print(sum(map(int, totalvals))) #map is like a for loop that does int for each value in the list, if you just do int(totalvals), it won't work, since totalvals is a list
print(len(totalvals))


from typing import Dict, Generator, List, Union
from elasticsearch import helpers
from elasticsearch.client import Elasticsearch
import logging
import time

logger = logging.getLogger(__name__)

class EsBulkInjector:
    """ Wrapper class to bulk inject documents to elasticsearch

        Parameters
        ----------
        - es_client : Elasticsearch
            - Elasticsearch low-level client instance
        - index : str
            - Name of the index
        - mappings : Dict or None
            - Configuration for the index ({'mappings': {...}, 'settings': {...})
        - aliases : List[str]
            - List of aliases for the index
    """
    def __init__(self, es_client: Elasticsearch, index: str, doc_generator: Generator, max_chunk_bytes: float=100, **kwargs):
        self.es_client = es_client
        self.index = index
        self.doc_generator = doc_generator
        self.max_chunk_bytes = max_chunk_bytes

        self.mappings = kwargs['mappings'] if 'mappings' in kwargs else None
        self.aliases = kwargs['aliases'] if 'aliases' in kwargs else None

    def _check_index_exist(self) -> None:
        if self.es_client.indices.exists(index=self.index):
            logger.info("index {} exists. It will be removed and created again.".format(self.index))
            self.es_client.indices.delete(index=self.index, ignore=[400, 404])

    def _create_index(self) -> None:
        """Creates an index in Elasticsearch. If index exists, it is removed before before being created again."""
        self._check_index_exist()
        self.es_client.indices.create(
            index=self.index,
            body=self.mappings,
            ignore=400,
        )
        if self.aliases:
            self._put_alias()

    def _put_alias(self) -> None:
        for alias in self.aliases:
            self.es_client.indices.put_alias(index=self.index, name=alias)

    def _bulk(self) -> None:
        self._create_index()
        _success, _errors = helpers.bulk(
            client=self.es_client,
            index=self.index,
            actions=self.doc_generator,
            max_chunk_bytes=self.max_chunk_bytes * 1024 * 1024,
            max_retries=3,
        )

        logger.info("- Number of success in document injection: {}".format(_success))
        logger.info("- Number of errors in document injection: {}".format(_errors))

    def run(self):
        self._bulk()


import cv2 as cv
import sys
import numpy as np

def main():
    orgImg = cv.imread('../resource/unevenness.tiff', 0)
    if orgImg is None:
        print('fialed load image')
        sys.exit(1)

    #kernel = np.ones((15,15), np.uint8)
    kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (100,100))
    openImg = cv.morphologyEx(orgImg, cv.MORPH_OPEN, kernel)
    closeImg = cv.morphologyEx(orgImg, cv.MORPH_CLOSE, kernel)
    cv.imshow('org', orgImg)
    cv.imshow('opening', openImg)
    cv.imshow('closeImg', closeImg)

    cv.waitKey(0)

    mask = cv.absdiff(orgImg, closeImg)

    cv.imshow('mask', mask)
    cv.waitKey(0)

    cv.imwrite('./foreground.tiff', mask)

if __name__ == "__main__":
    main()


import io
import re
from contextlib import closing
from zipfile import ZipFile

import requests
from django.core.files.base import ContentFile
from django_boto.s3 import upload
from rarfile import RarFile

from dashboard.models import Comic, CBR, CBZ

def upload_comic(series_id, file=None, file_url=None):
    """
    Given a series id and a file or a file url, upload the comic pages
    to s3 and create a new Comic instance in the given series.
    """
    # We need at least one of the arguments.
    if file is None and file_url is None:
        return None

    # If a file url is provided, download it to memory and get its file name.
    if file_url:
        req = requests.get(file_url, stream=True)
        d = req.headers['content-disposition']
        file_name = re.findall("filename=(.+)", d)
        file_name = file_name[0][:-1][1:]  # Remove double quotes.
        file = io.BytesIO(req.content)
        closing(req)
    # Otherwise simply take its file name.
    else:
        file_name = file.name

    # Determine whether it's a CBR or a CBZ and create a RarFile or a ZipFile.
    if file_name.endswith('.{}'.format(CBR)):
        cb_file = RarFile(file)
        cb_type = CBR
    elif file_name.endswith('.{}'.format(CBZ)):
        cb_file = ZipFile(file)
        cb_type = CBZ
    else:
        return None

    # Go through the CBZ/CBR pages and upload all of them to s3.
    page_urls = []
    for file_name in cb_file.namelist():
        if not file_name.lower().endswith('.jpg') and not file_name.lower().endswith('.png'):
            continue
        image_url = upload(
            ContentFile(cb_file.read(file_name)),
            name=file_name,
            prefix=False,
            bucket_name=False,
            key=None,
            secret=None,
            host=None,
            expires=0,
            query_auth=False,
            force_http=True,
            policy=None
        )
        page_urls.append(image_url)

    # Create a comic.
    return Comic.objects.create(
        title=file_name.replace('.cbz', ''),
        file_type=cb_type,
        pages='|'.join(page_urls),
        series_id=series_id
    )


from mchy.common.com_loc import ComLoc
from mchy.common.config import Config
from mchy.contextual.struct import *
from mchy.contextual.struct.expr import CtxExprLitWorld
from mchy.stmnt.struct import *
from mchy.stmnt.generation import convert
from mchy.stmnt.struct.cmds.tag_ops import SmtRawEntitySelector
from tests.stmnt_layer.helper import diff_cmds_list

import pytest

from mchy.stmnt.struct.cmds import SmtInvokeFuncCmd

_INT = InertType(InertCoreTypes.INT)

class TestMchyFunc1:

    _MODULE = CtxModule(Config())
    _MARKER_GET42 = MarkerDeclFunc([])
    _FUNC_GET42 = CtxMchyFunc(ExecType(ExecCoreTypes.WORLD, False), ComLoc(), "get42", [], InertType(InertCoreTypes.INT), ComLoc(), ComLoc(), ComLoc(), _MARKER_GET42)
    _MARKER_GET42.with_func(_FUNC_GET42)
    _MODULE.add_function(_FUNC_GET42)
    _INT_VAR_FOO = _MODULE.global_var_scope.register_new_var("foo", InertType(InertCoreTypes.INT), False, MarkerDeclVar().with_enclosing_function(None), ComLoc())

    _FUNC_GET42.exec_body = [
        CtxReturn(CtxExprLitInt(42, src_loc=ComLoc()))
    ]

    _MODULE.exec_body = [
        _MARKER_GET42,
        CtxAssignment(_INT_VAR_FOO, CtxExprFuncCall(CtxExprLitWorld(src_loc=ComLoc()), _FUNC_GET42, [], src_loc=ComLoc())),
    ]

    @pytest.fixture
    def ctx_module(self) -> CtxModule:
        TestMchyFunc1._FUNC_GET42.exec_body = [
            CtxReturn(CtxExprLitInt(42, src_loc=ComLoc()))
        ]

        TestMchyFunc1._MODULE.exec_body = [
            TestMchyFunc1._MARKER_GET42,
        ]
        return TestMchyFunc1._MODULE

    def test_converted_function_exists(self, ctx_module: CtxModule):
        smt_module = convert(ctx_module, Config())
        assert TestMchyFunc1._FUNC_GET42 in smt_module._mchy_funcs_link.keys()

    def test_calling_mchy_function_works(self, ctx_module: CtxModule):
        ctx_module.exec_body.append(
            CtxAssignment(TestMchyFunc1._INT_VAR_FOO, CtxExprFuncCall(CtxExprLitWorld(src_loc=ComLoc()), TestMchyFunc1._FUNC_GET42, [], src_loc=ComLoc()))
        )
        smt_module = convert(ctx_module, Config())

        func = smt_module.get_smt_func(TestMchyFunc1._FUNC_GET42)
        diff_bool, explanation = diff_cmds_list(smt_module.initial_function.func_frag.body, [
            SmtInvokeFuncCmd(func, SmtWorld()),
            SmtSpecialStackIncSourceAssignCmd(SmtPseudoVar(0, func.return_var.get_type()), func.return_var),
            SmtAssignCmd(SmtPublicVar('foo', _INT), SmtPseudoVar(0, func.return_var.get_type())),
        ])
        assert diff_bool, "Converted function call does not match expected:\n" + explanation

    def test_converted_function_has_correct_body(self, ctx_module: CtxModule):
        smt_module = convert(ctx_module, Config())
        func = smt_module.get_smt_func(TestMchyFunc1._FUNC_GET42)
        assert len(func.func_frag.body) > 0, "Empty function body?"

        diff_bool, explanation = diff_cmds_list(func.func_frag.body, [
            SmtRawEntitySelector(SmtWorld(), func.executor_var, "@s"),
            SmtAssignCmd(func.return_var, SmtConstInt(42))
        ])
        assert diff_bool, "Converted function body does not match expected:\n" + explanation


def memoised(function_):
    """ Deprecated - use @functools.cache"""
    pre_computed = {}

    def wrapper(*args):
        if args not in pre_computed:
            answer = function_(*args)
            pre_computed[args] = answer

        return pre_computed[args]

    return wrapper

def print_results(function_):
    def wrapper(*args, **kwargs):
        arguments = ', '.join(map(str, args))
        for key, value in kwargs.items():
            arguments = arguments and arguments + ', ' or arguments
            arguments += f'{key}={value}'

        results = function_(*args, **kwargs)
        print(f'{function_.__name__}({arguments})={results}')
        return results

    return wrapper

def timed_function(function_, print_output=True):
    def wrapper(*args, **kwargs):
        arguments = ', '.join(map(str, args))
        for key, value in kwargs.items():
            arguments = arguments and arguments + ', ' or arguments
            arguments += f'{key}={value}'

        import time
        start_time = time.time()

        results = function_(*args, **kwargs)

        if not print_output: results = ''

        time_taken = (time.time() - start_time) * 1000
        print(f'{function_.__name__}({arguments})={results}')
        print(f'Took {time_taken} ms')

        return results

    return wrapper


import threading
'''

Requirements:Create a class that extends the 'threading.Thread'
1.  class (see https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python). This means that the class IS a thread.

Requirements:
1. Create a class that extends the 'threading.Thread' class (see https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python).
   This means that the class IS a thread.
   Any objects instantiated using this class ARE threads.
2. Instantiate this thread class that computes the sum of all numbers
   between one and that number (exclusive)

Psuedocode:
1. In your class, write a constructor (in python a constructor is __init__) and allow a number
   to be passed in as a parameter.
2. The constructor should call the parent class's constructor:
   threading.Thread.__init__(self)
3. Create a local sum variable in your constructor.
4. A thread must have a run function, so create a run function that sums from one to the
   passed in number (exclusive).
5. In the run function, set the sum on self.
6. In main, instantiate your thread class with the a value of 10.
7. Start the thread.
8. Wait for the thread to finish.
9. Assert that thread object's sum attribute is equal to the appropriate value (see main).
10. Repeat steps 7 through 10 using a value of 13.
11. Repeat steps 7 through 10 using a value of 17.

Things to consider:
a. How do you instantiate a class and pass in arguments (see https://realpython.com/lessons/instantiating-classes/)?
b. How do you start a thread object (see this week's reading)?
c. How will you wait until the thread is done (see this week's reading)?
d. How do you get the value an object's attribute (see https://datagy.io/python-print-objects-attributes/)?
'''
######################
# DO NOT USE GLOBALS #
######################

class SummingNumbers(threading.Thread):
    '''Sums numbers'''

    def __init__(self, number):
        threading.Thread.__init__(self)
        self.sum = 0
        self.number = number

# Summation function class as a thread object.
class threaded_sum(threading.Thread):

    # Class constructor.
    def __init__(self, number):
        super().__init__()
        self.number = number
        self.sum = 0

    # Summation function performed during thread run.
    def run(self):
        for num in range(1, self.number, 1):
            self.sum += num

    def run(self):
        for x in range(self.number):
            self.sum = self.sum + x
            # print(f'{self.sum=}')

def main():

    t1 = SummingNumbers(10)
    t2 = SummingNumbers(13)
    t3 = SummingNumbers(17)

    t1.start()
    t2.start()
    t3.start()

    t1.join()
    t2.join()
    t3.join()

    # Instantiate your thread class and pass in 10.
    # Test (assert) if its sum attribute is equal to 45.
    # Note: do no use 'yourThread' for the name of your thread object
    assert t1.sum == 45, f'The sum should equal 45 but instead was {t1.sum}'

    # Repeat, passing in 13
    assert t2.sum == 78, f'The sum should equal 78 but instead was {t2.sum}'

    # Repeat, passing in 17
    assert t3.sum == 136, f'The sum should equal 136 but instead was {t3.sum}'

    # For each thread, we instantiate the thread object, start it, join it (finish the thread), and then assert the sum value is correct.

    t1 = threaded_sum(10)
    t1.start()
    t1.join()

    # Assert the sum value is 45.
    assert t1.sum == 45, f'The sum should equal 45 but instead was {t1.sum}'

    t2 = threaded_sum(13)
    t2.start()
    t2.join()

    # Assert the sum value is 78.
    assert t2.sum == 78, f'The sum should equal 78 but instead was {t2.sum}'

    # Assert the sum value is 45.
    assert t1.sum == 45, f'The sum should equal 45 but instead was {t1.sum}'

    t2 = threaded_sum(13)
    t2.start()
    t2.join()

    # Assert the sum value is 78.
    assert t2.sum == 78, f'The sum should equal 78 but instead was {t2.sum}'

    t3 = threaded_sum(17)
    t3.start()
    t3.join()

    # Assert the sum value is 136.
    assert t3.sum == 136, f'The sum should equal 136 but instead was {t3.sum}'

# Main function.
if __name__ == '__main__':
    main()
    assert threading.active_count() == 1
    print("DONE")

# Assignment completed by Mark Vagil.


CipherText = 16
CipherText = int(CipherText)
Product = 0
PublicKey = [5, 35]
PlainText = 0
ciphertext1 = 0
ciphertext2 = 0

while ciphertext2 != 16:
    print ('Encrypting...')
    ciphertext1 = PlainText ** PublicKey[0]
    ciphertext2 = ciphertext1 % PublicKey[1]
    print ('Ciphertext: ', ciphertext2)
    if ciphertext2 == 16:
        print ('Plaintext == ', PlainText)
    else:
        PlainText = PlainText + 1


import numpy as np
import tensorflow as tf
from tensorflow import keras

class Processor:

    def __init__(self, x_in=None, batch_size=512, num2mask=10, t_axis=138, y_in=None, shuffle=True):
        # Initialization
        self.num2mask = num2mask
        self.t_axis = t_axis
        self.batch_size = batch_size
        self.shuffle = shuffle
        self.x = np.arange(1, 1000) #x_in
        self.y = y_in
        self.datalen = len(self.x)
        self.indexes = np.arange(self.datalen)
        if self.shuffle:
            np.random.shuffle(self.indexes)

    def create_mask(self, batch_shape):
        random = tf.random.normal(shape=(batch_shape, self.t_axis))
        point2mask, _ = tf.math.top_k(random, self.num2mask)
        mask = tf.where(random - tf.reduce_min(point2mask, axis=-1, keepdims=True) >= 0., 1., 0.)
        return mask

    def load_data(self, path2wav, path2label):
        wav_file = tf.io.read_file(path2wav)
        wav_file = tf.audio.decode_wav(wav_file)
        label = tf.io.read_file(path2label)
        mask = self.create_mask(wav_file)
        return [wav_file, mask], [label, mask]

# class Processor(keras.utils.Sequence):
#
#     def __init__(self, x_in=None, batch_size=512, num2mask=10, t_axis=138, y_in=None, shuffle=True):
#         # Initialization
#         self.num2mask = num2mask
#         self.t_axis = t_axis
#         self.batch_size = batch_size
#         self.shuffle = shuffle
#         self.x = np.arange(1, 1000) #x_in
#         self.y = y_in
#         self.datalen = len(self.x)
#         self.indexes = np.arange(self.datalen)
#         if self.shuffle:
#             np.random.shuffle(self.indexes)
#
#     def craete_mask(self, batch_shape):
#         random = tf.random.normal(shape=(batch_shape, self.t_axis))
#         point2mask, _ = tf.math.top_k(random, self.num2mask)
#         mask = tf.where(random - tf.reduce_min(point2mask, axis=-1, keepdims=True) >= 0., 1., 0.)
#         return mask
#
#     def __getitem__(self, index):
#         # get batch indexes from shuffled indexes
#         batch_indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]
#         x_batch = self.x[batch_indexes]
#         y_batch = self.craete_mask(x_batch[0].shape[0])
#         return x_batch, y_batch
#
#     def __len__(self):
#         # Denotes the number of batches per epoch
#         return self.datalen // self.batch_size
#
#     def on_epoch_end(self):
#         # Updates indexes after each epoch
#         self.indexes = np.arange(self.datalen)
#         if self.shuffle:
#             np.random.shuffle(self.indexes)
#
#     def __data_generation(self, list_IDs_temp):
#         'Generates data containing batch_size samples'  # X : (n_samples, *dim, n_channels)
#         # Initialization
#         X = np.empty((self.batch_size, *self.dim, self.n_channels))
#         y = np.empty((self.batch_size), dtype=int)
#
#         # Generate data
#         for i, ID in enumerate(list_IDs_temp):
#             # Store sample
#             X[i,] = np.load('data/' + ID + '.npy')
#
#             # Store class
#             y[i] = self.labels[ID]
#
#         return X, keras.utils.to_categorical(y, num_classes=self.n_classes)


from pyramid.httpexceptions import HTTPFound

from dace.processinstance.core import  Behavior

from pontus import _

class Cancel(Behavior):

    behavior_id = "cancel"
    title = _("Cancel")
    description = ""

    def start(self, context, request, appstruct, **kw):
        behaviors_to_cancel = list(appstruct.get('behaviors', []))
        if self in  behaviors_to_cancel:
            behaviors_to_cancel.remove(self)

        for behavio in behaviors_to_cancel:
            behavio.cancel_execution(context, request, **kw)

        return {}

    def redirect(self, context, request, **kw):
        return HTTPFound(request.resource_url(context, "@@index"))


import matplotlib.pyplot as plt

class BivariateChoroplethPlotter:
    """Bivariate choropleth plotter"""
    def __init__(self, percentile_limits):
        self.percentile_limits = percentile_limits
        self.num_groups = len(percentile_limits)
        self.alpha_value = 0.85

        self.light_gray, self.green, self.blue, self.dark_blue = self.define_corner_colors()
        self.color_list_hex = self.create_color_list()

    def hex_to_rgb_color(self, hex_code):
        rgb_values = [int(hex_code[i:i+2], 16) / 255.0 for i in (1, 3, 5)]
        return rgb_values

    def define_corner_colors(self):
        light_gray = self.hex_to_rgb_color('#e8e8e8')
        green = self.hex_to_rgb_color('#73ae80')
        blue = self.hex_to_rgb_color('#6c83b5')
        dark_blue = self.hex_to_rgb_color('#2a5a5b')
        return light_gray, green, blue, dark_blue

    def create_color_list(self):
        light_gray_to_green = []
        blue_to_dark_blue = []
        color_list = []

        for i in range(self.num_groups):
            light_gray_to_green.append([self.light_gray[j] + (self.green[j] - self.light_gray[j]) * i / (self.num_groups - 1) for j in range(3)])
            blue_to_dark_blue.append([self.blue[j] + (self.dark_blue[j] - self.blue[j]) * i / (self.num_groups - 1) for j in range(3)])

        for i in range(self.num_groups):
            for j in range(self.num_groups):
                color_list.append([light_gray_to_green[i][k] + (blue_to_dark_blue[i][k] - light_gray_to_green[i][k]) * j / (self.num_groups - 1) for k in range(3)])

        color_list_hex = ['#%02x%02x%02x' % tuple(int(c * 255) for c in color) for color in color_list]
        return color_list_hex

    def get_bivariate_color(self, p1, p2):
        if p1 >= 0 and p2 >= 0:
            i = next(i for i, pb in enumerate(self.percentile_limits) if p1 <= pb)
            j = next(j for j, pb in enumerate(self.percentile_limits) if p2 <= pb)
            return self.color_list_hex[i * self.num_groups + j]
        else:
            return '#cccccc'  # Gray for invalid percentiles

    def plot_bivariate_choropleth(self, geometry):
        fig, ax = plt.subplots(1, 1, figsize=(12, 12))
        geometry['color_bivariate'] = [self.get_bivariate_color(p1, p2) for p1, p2 in zip(geometry['column1'].values, geometry['column2'].values)]
        geometry.plot(ax=ax, color=geometry['color_bivariate'], alpha=self.alpha_value, legend=False)
        ax.set_xticks([])
        ax.set_yticks([])
        plt.show()

    def plot_inset_legend(self, ax):
        ax_inset = ax.inset_axes([0.6, 0.1, 0.33, 0.3])
        ax_inset.set_aspect('equal', adjustable='box')
        x_ticks = [0]
        y_ticks = [0]

        for i, percentile_bound_p1 in enumerate(self.percentile_limits):
            for j, percentile_bound_p2 in enumerate(self.percentile_limits):
                rect = plt.Rectangle((i, j), 1, 1, facecolor=self.color_list_hex[i * self.num_groups + j], alpha=self.alpha_value)
                ax_inset.add_patch(rect)
                if i == 0:
                    y_ticks.append(percentile_bound_p2)
            x_ticks.append(percentile_bound_p1)

        ax_inset.set_xlim([0, len(self.percentile_limits)])
        ax_inset.set_ylim([0, len(self.percentile_limits)])
        ax_inset.set_xticks(list(range(len(self.percentile_limits) + 1)), x_ticks)
        ax_inset.set_xlabel('Distribution Percentile')
        ax_inset.set_yticks(list(range(len(self.percentile_limits) + 1)), y_ticks)
        ax_inset.set_ylabel('Distribution Percentile')
        plt.show()

def main():
    # Define percentile bounds for color classes
    percentile_limits = [0.1, 0.3, 0.6, 1.0]
    plotter = BivariateChoroplethPlotter(percentile_limits)

    """
    Geometry dataframe represents GIS data, including geometry column and other relevant columns

    The format of the data frame is as follows:
    geometry<pandas.dataframe or geopandas>
    | geometry | column1 | column2 |
    |----------|---------|---------|
    | Polygon  | 0.1     | 0.2     |
    | Polygon  | 0.3     | 0.4     |
    | Polygon  | 0.5     | 0.6     |
        …        …         …
    | Polygon  | 0.7     | 0.8     |
    | Polygon  | 0.9     | 1.0     |

    ※This sample uses polygon data from the national spatial data information.
    ※The data is dummy data
    """

    # Plot bivariate choropleth
    plotter.plot_bivariate_choropleth(geometry)

    # Plot inset legend
    fig, ax = plt.subplots(1, 1, figsize=(12, 12))
    plotter.plot_inset_legend(ax)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
from conjuntos import *

# Capacidad de la bodega
CB = 475

# Trabajadores por maquina
W = {"skin": 1, "troqueladora": 2, "selladora": 2}

# Trabajadores :
#   g_k = t[k]['mujer'] ; rho_k = t[k]['chileno'] ; alpha_k = t[k]['sueldo']

t = {"chery": {"sueldo": 11784, "mujer": 1, "chileno": 0},
     "fontus": {"sueldo": 11673, "mujer": 0, "chileno": 0},
     "marcelin": {"sueldo": 11674, "mujer": 0, "chileno": 1},
     "miranda": {"sueldo": 15000, "mujer": 1, "chileno": 1},
     "pierre": {"sueldo": 11822, "mujer": 0, "chileno": 0},
     "philomene": {"sueldo": 11595, "mujer": 1, "chileno": 0},
     "patricia": {"sueldo": 9600, "mujer": 1, "chileno": 1},
     "bernarda": {"sueldo": 15000, "mujer": 1, "chileno": 1},
     "joselin": {"sueldo": 11152, "mujer": 1, "chileno": 1}}

# Capacidad del basurero
CBA = 3.3

# Capacidad camión recolector
# CC = None  # REVISAR!!
BIGM = pow(10, 6)

# Pedidos
delta = {("imp", "skin", 1): 1412, ("Imp", "skin", 2): 897,
         ("imp", "skin", 6): 876, ("Imp", "blister", 10): 876,
         ("imp", "regulador", 2): 980, ("imp", "regulador", 4): 945,
         ("viso", "blister", 4): 877, ("viso", "blister", 5): 915,
         ("viso", "blister", 15): 1877, ("viso", "regulador", 8): 944,
         ("viso", "regulador", 20): 867, ("sfr", "blister", 4): 875,
         ("sfr", "blister", 9): 850, ("sfr", "electronico", 17): 450,
         ("ball", "electronico", 1): 420, ("ball", "electronico", 16): 637,
         ("ball", "electronico", 18): 986}

for c in C:
    for i in I:
        for d in D:
            if (c, i, d) not in delta:
                delta[c, i, d] = 0

# Costo arriendo
gamma = 800000

# Costos proveedores
sigma = {"pv1": {"flexible 150": 101, "rigido 150": 205, "rigido 200": 300},
         "pv2": {"flexible 150": 105, "rigido 150": 200, "rigido 200": 301}
         }

# Volumen desechado
beta = 0.015

# Costo uso maquina
theta = {"skin": 84964, "troqueladora": 60525, "selladora": 70960}

# Precio venta productos
eta = {"skin": 178, "blister": 306, "electronico": 450, "regulador": 200}
# Costo extraccion basura
xi = 475

# Volumen producto
V = {"skin": 0.000045, "blister": 0.0001, "electronico": 0.0052,
     "regulador": 0.0047625}

# Volumen materia prima
v = {"flexible 150": 0.00014364, "rigido 150": 0.000216, "rigido 200": 0.0004}

# Materia prima por producto en unidades de plancha de plastico
MP = {("blister", "rigido 200"): 0.066667,
      ("skin", "flexible 150"): 0.0833,
      ("electronico", "rigido 150"): 1.66667}

for i in I:
    for j in J:
        if (i, j) not in MP:
            MP[i, j] = 0

# Costo materia prima
mu = {"pv1": {"rigido 200": 300, "rigido 150": 205, "flexible 150": 101},
      "pv2": {"rigido 200": 301, "rigido 150": 200, "flexible 150": 105}}

# Presupuesto inicial
PR = 4000000

# Compra minima que establece el proveedor p para el material j
cm = {("pv1", "rigido 200"): 100, ("pv1", "rigido 150"): 100, ("pv1", "flexible 150"): 100,
      ("pv2", "rigido 200"): 100, ("pv2", "rigido 150"): 100, ("pv2", "flexible 150"): 100
      }

A = {("blister", "skin"): (),
     ("blister", "troqueladora"): ("skin",),
     ("blister", "selladora"): ("skin", "troqueladora"),
     ("blister", "relleno"): ("skin", "troqueladora", "selladora"),
     ("blister", "etiquetado"): ("skin", "troqueladora", "selladora", "relleno"),
     ("blister", "envasado"): ("skin", "troqueladora", "selladora", "relleno",
                               "etiquetado"),
     ("skin", "skin"): (),
     ("skin", "troqueladora"): ("skin",),
     ("skin", "etiquetado"): ("skin", "troqueladora"),
     ("skin", "envasado"): ("skin", "troqueladora", "etiquetado"),
     ("electronico", "skin"): (),
     ("electronico", "selladora"): ("skin",),
     ("electronico", "desgajado"): ("skin", "selladora"),
     ("electronico", "etiquetado"): ("skin", "selladora", "desgajado"),
     ("electronico", "envasado"): ("skin", "selladora", "desgajado"),
     ("regulador", "skin"): (),
     ("regulador", "selladora"): ("skin",),
     ("regulador", "envasado"): ("skin", "selladora")}

# Uso de maquina en proceso
U = {("blister", "skin", "skin"): 1,
     ("blister", "troqueladora", "troqueladora"): 1,
     ("blister", "selladora", "selladora"): 1,
     ("skin", "skin", "skin"): 1,
     ("skin", "troqueladora", "troqueladora"): 1,
     ("electronico", "skin", "skin"): 1,
     ("electronico", "selladora", "selladora"): 1,
     ("regulador", "skin", "skin"): 1,
     ("regulador", "selladora", "selladora"): 1}

for i in I:
    for e in E:
        for m in M:
            if not (i, e, m) in U:
                U[i, e, m] = 0

r = {"blister": 0.6, "skin": 0.8, "electronico": 0.4, "regulador": 1}


""" #######################################################################
    Title: Construction of an FE model of the spinal cord to simulate the voltage distribution caused by a dipole
    Subtitle: Material Conductivity values
    Author: Markus E. Oberndorfer
####################################################################### """

dist_C7_Sp14 = 0.01                     # horiz. dist. between C7 & Sp14 --> (Notation according to (Wimmer, Kostoglou, Müller-Putz; 2022) )
rad_electrode = 0.009                   # radius electrode
ver_dist_elec = 0.018                   # meter, vertical distance between electrodes

params_elec = [dist_C7_Sp14, rad_electrode, ver_dist_elec]


#implementaion of merger sort

def merge_sort(arr):
    import math
    #merger func merges the splited arrays in asc order
    def merger(upperArr,lowerArr):
        i = 0
        j = 0
        arr = []
        #print(upperArr,lowerArr)
        while (i < len(upperArr)) & (j < len(lowerArr)):
            if upperArr[i] < lowerArr[j]:
                arr.append(upperArr[i])
                i+=1
            else:
                arr.append(lowerArr[j])
                j+=1
        arr = arr+upperArr[i:]+lowerArr[j:]
        #print(f"arr = {arr}")
        return arr
    #spliter func splits the arrays in half and calls merger func (in recursive order)
    def spliter(splitArr):
        mid = math.floor(len(splitArr)/2)
        #print(splitArr)
        if len(splitArr) == 2:
            splitArr = merger([splitArr[0]],[splitArr[1]])
        else:
            upper = spliter(splitArr[0:mid])
            lower = spliter(splitArr[mid:])
            splitArr = merger(upper,lower)
        return splitArr
    print(spliter(arr))

merge_sort([1,13,2,7,6,5,0,9])


from django.contrib.auth.models import User
from django.db import models
from rest_framework import serializers

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    label = models.CharField(max_length=12)

class Restaurant(models.Model):
    user = models.OneToOneField(User, on_delete=None, primary_key=True)
    rank = models.IntegerField()
    description = models.TextField()
    latitude = models.DecimalField(decimal_places=120, max_digits=128)
    longitude = models.DecimalField(decimal_places=120, max_digits=128)
    address = models.CharField(max_length=100)
    tag = models.ForeignKey(Tag, on_delete=None)

    class Meta:
        db_table = 'restaurant'

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['first_name']

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['label']

class RestaurantSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Restaurant
        fields = ['user_id', 'rank', 'latitude', 'longitude', 'address', 'tag', 'user', 'description']

class Item(models.Model):
    id = models.AutoField(primary_key=True)
    price = models.IntegerField()
    description = models.TextField()
    path = models.CharField(max_length=64)
    name = models.CharField(max_length=12)
    tag = models.ForeignKey(Tag, on_delete=None)
    restaurant = models.ForeignKey(Restaurant, on_delete=None, related_name='items')

class ItemSerializer(serializers.ModelSerializer):
    tag = TagSerializer()
    restaurant = RestaurantSerializer()

    class Meta:
        model = Item
        fields = ('id', 'price', 'description', 'path', 'name', 'tag', 'restaurant')


#import required library
import turtle
#creating a screen
w = turtle.Screen()
w.title("pong game")
w.setup(width = 1000, height = 600)
w.bgcolor("lightblue")

#left paddle
lp = turtle.Turtle()
lp.speed(0)
lp.shape("square")
lp.color("black")
lp.shapesize(stretch_wid=6,stretch_len=2)
lp.penup()
lp.goto(-400,0)

#right paddle
rp = turtle.Turtle()
rp.speed(0)
rp.shape("square")
rp.color("black")
rp.shapesize(stretch_wid=6,stretch_len=2)
rp.penup()
rp.goto(400,0)

#creating ball
b = turtle.Turtle()
b.speed(20)
b.shape("circle")
b.color("yellow")
b.penup()
b.goto(0,0)
b.dx = 5
b.dy = -5

#intilizing the score
left_player = 0
right_player = 0

#display the score
sketch = turtle.Turtle()
sketch.speed(0)
sketch.color("red")
sketch.penup()
sketch.hideturtle()
sketch.goto(0,260)
sketch.write("Left_Player : 0  Right_Player : 0", align = "center", font = ("Courier", 24, "normal"))

#functions to move paddle vertically
def rpup():
    y= rp.ycor()
    y = y +20
    rp.sety(y)
def rpdown():
    y = rp.ycor()
    y = y-20
    rp.sety(y)
def lpup():
    y = lp.ycor()
    y = y+20
    lp.sety(y)
def lpdown():
    y = lp.ycor()
    y = y-20
    lp.sety(y)
#keyboardbindings
w.listen()
w.onkeypress(rpup,"Up")
w.onkeypress(rpdown,"Down")
w.onkeypress(lpup,"w")
w.onkeypress(lpdown,"s")

while True:
    w.update()

    b.setx(b.xcor()+b.dx)
    b.sety(b.ycor()+b.dy)

    #checking borders
    if b.ycor()>280:
        b.sety(280)
        b.dy = b.dy* -1
    if b.ycor()<-280:
        b.sety(-280)
        b.dy = b.dy*-1
    if b.xcor()>500:
        b.goto(0,0)
        b.dy = b.dy*-1
        left_player += 1
        sketch.clear()
        sketch.write("Left_Player : {} Right_Player : {}".format(left_player, right_player), align = "center", font =("Courier", 24, "normal"))
    if b.xcor()<-500:
        b.goto(0,0)
        b.dy = b.dy*-1
        right_player += 1
        sketch.clear()
        sketch.write("Left_Player : {} Right_Player : {}".format(left_player, right_player), align = "center", font =("Courier", 24, "normal"))
        #checking for paddle and ball collision
    if (b.xcor()>360 and b.xcor()<370) and (b.ycor()<rp.ycor()+40 and b.ycor()> rp.ycor() - 40):
        b.setx(360)
        b.dx = b.dx*-1
    if (b.xcor()<-360 and b.xcor()>-370) and (b.ycor()<lp.ycor()+40 and b.ycor()>lp.ycor()-40):
        b.setx(-360)
        b.dx = b.dx*-1


from docx import Document
from docx.enum.section import WD_SECTION
import os
import win32com.client
import inspect
import time

from docx_package.layout import Layout
from docx_package.chapter import Chapter
from docx_package.effectiveness_analysis import EffectivenessAnalysis
from docx_package.definitions import Definitions
from docx_package.header_footer import Header, Footer
from docx_package.table_of_content import TableOfContent
from docx_package.time_on_tasks import TimeOnTasks
from docx_package.cover_page import CoverPage
from docx_package.dwell_times_revisits import DwellTimesAndRevisits
from docx_package.average_fixation import AverageFixation
from docx_package.transitions import Transitions
from docx_package.parameters import Parameters
from docx_package.picture import Picture
from docx_package.document_history import DocumentHistory
from docx_package.participants_characteristics import ParticipantsCharacteristics
from docx_package.dropdown_lists import DropDownLists
from docx_package.use_scenarios import UseScenarios

from eye_tracking_package.cGOM_data import cGOM
from eye_tracking_package.tobii_data import TobiiData

def update(report_file):
    """
    Update all fields of  the report, i.e. the table of content, the figure captions and the list of figures.

    Args:
        report_file: File name of the report.
    """

    # get the absolut path of the report
    script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    report_file_path = os.path.join(script_dir, report_file)

    # open the report through Word, update all fields, save and quit Word
    word = win32com.client.DispatchEx("Word.Application")
    doc = word.Documents.Open(report_file_path)
    word.ActiveDocument.Fields.Update()
    doc.Close(SaveChanges=True)
    word.Quit()

def main():

    main_start = time.time()

    # file name of the report
    report_file = 'Report.docx'

    # create the report document
    report = Document()

    # path of the input files
    text_input_path = 'Inputs/Text_input_form.docx'
    definitions_path = 'Inputs/Terms_definitions.docx'

    # load text input files with python-docx
    text_input = Document(text_input_path)
    definitions = Document(definitions_path)

    # path to the pictures that must be added to the report
    picture_paths = Picture.get_picture_paths()

    # soup of the text input form document
    text_input_soup = DropDownLists.get_soup(text_input_path)

    # list of all tables in the order they appear in the text input document,
    # this is used to get the index of a table in the document
    tables = [
        'Study table',
        'Title table',
        'Approval table',
        'Cover page caption table',
        'Header table',
        'Purpose text table',
        'Purpose parameter table',
        'Purpose caption table',
        'Background text table',
        'Background parameter table',
        'Background caption table',
        'Scope text table',
        'Scope parameter table',
        'Scope caption table',
        'EU Regulation 2017/745 definitions table',
        'IEC 62366-1 definitions table',
        'FDA Guidance definitions table',
        'Ethics statement text table',
        'Ethics statement parameter table',
        'Ethics statement caption table',
        'Device specifications text table',
        'Device specifications parameter table',
        'Device specifications caption table',
        'Goal text table',
        'Goal parameter table',
        'Goal caption table',
        'Participants text table',
        'Participants parameter table',
        'Participants caption table',
        'Use environment text table',
        'Use environment parameter table',
        'Use environment caption table',
        'Use scenarios text table',
        'Use scenarios parameter table',
        'Use scenarios caption table',
        'Setup text table',
        'Setup parameter table',
        'Setup caption table',
        'Critical tasks description table',
        'Effectiveness analysis decision table',
        'Effectiveness analysis tasks and problems table',
        'Effectiveness analysis problem type table',
        'Effectiveness analysis text table',
        'Effectiveness analysis parameter table',
        'Effectiveness analysis caption table',
        'Time on tasks decision table',
        'Time on tasks plot type table',
        'Time on tasks table',
        'Time on tasks text table',
        'Time on tasks parameter table',
        'Time on tasks caption table',
        'Dwell times and revisits decision table',
        'Dwell times and revisits text table',
        'Dwell times and revisits parameter table',
        'Dwell times and revisits caption table',
        'Average fixation decision table',
        'Average fixation plot type table',
        'Average fixation text table',
        'Average fixation parameter table',
        'Average fixation caption table',
        'Transitions decision table',
        'Transitions text table',
        'Transitions parameter table',
        'Transitions caption table',
        'Conclusion text table',
        'Conclusion parameter table',
        'Conclusion caption table',
        'Participants characteristics table'
    ]

    # parameters needed to write the report
    parameters = Parameters.get_all(text_input, text_input_soup, tables)

    # list of data frames that contain the cGOM data
    cGOM_dataframes = cGOM.make_dataframes_list()

    # data frame that contain the Tobii data
    tobii_data = TobiiData.make_main_dataframe(parameters)

    # define all styles used in the document
    Layout.define_all_styles(report)

    ######   COVER PAGE   ######

    section1 = report.sections[0]
    Layout.define_page_format(section1)

    cover_page_start = time.time()
    cover_page = CoverPage(report, text_input, tables, picture_paths, parameters)
    cover_page.create()

    '''
    cover_page_end = time.time()
    print('Cover page added in %.2f seconds' % (cover_page_end - cover_page_start))
    '''

    ######   TABLE OF CONTENT   ######

    report.add_page_break()

    TableOfContent.write(report)

    ######   CHAPTERS   ######

    section2 = report.add_section(WD_SECTION.NEW_PAGE)
    Layout.define_page_format(section2)

    footer = Footer(section2)
    footer.write()

    header = Header(section2, parameters)
    header.write()

    purpose = Chapter(report, text_input, text_input_soup, 'Purpose', tables, picture_paths, parameters)
    purpose.write_chapter()

    background = Chapter(report, text_input, text_input_soup, 'Background', tables, picture_paths, parameters)
    background.write_chapter()

    scope = Chapter(report, text_input, text_input_soup, 'Scope', tables, picture_paths, parameters)
    scope.write_chapter()

    Definitions.write_all_definitions(report, text_input, text_input_soup, definitions, tables)

    ethics = Chapter(report, text_input, text_input_soup, 'Ethics statement', tables, picture_paths, parameters)
    ethics.write_chapter()

    device = Chapter(report, text_input, text_input_soup, 'Device specifications', tables, picture_paths, parameters)
    device.write_chapter()

    report.add_paragraph('Test procedure', 'Heading 1')

    goal = Chapter(report, text_input, text_input_soup, 'Goal', tables, picture_paths, parameters)
    goal.write_chapter()

    participants = Chapter(report, text_input, text_input_soup, 'Participants', tables, picture_paths, parameters)
    participants.write_chapter()

    environment = Chapter(report, text_input, text_input_soup, 'Use environment', tables, picture_paths, parameters)
    environment.write_chapter()

    scenarios = UseScenarios(report, text_input, text_input_soup, 'Use scenarios', tables, picture_paths, parameters)
    scenarios.write_chapter()

    setup = Chapter(report, text_input, text_input_soup, 'Setup', tables, picture_paths, parameters)
    setup.write_chapter()

    report.add_paragraph('Results', 'Heading 1')

    start1 = time.time()
    effectiveness_analysis = EffectivenessAnalysis(report, text_input, text_input_soup, tables, picture_paths, parameters)
    effectiveness_analysis.write_chapter()
    end1 = time.time()
    print('Effectiveness analysis: ', end1-start1)

    start2 = time.time()
    time_on_tasks = TimeOnTasks(report, text_input, text_input_soup, tables, picture_paths, parameters, tobii_data)
    time_on_tasks.write_chapter()
    end2 = time.time()
    print('Time on tasks: ', end2-start2)

    start3 = time.time()
    dwell_times_and_revisits = DwellTimesAndRevisits(report, text_input, text_input_soup, tables, picture_paths, parameters, cGOM_dataframes)
    dwell_times_and_revisits.write_chapter()
    end3 = time.time()
    print('Dwell times: ', end3-start3)

    start4 = time.time()
    average_fixation = AverageFixation(report, text_input, text_input_soup, tables, picture_paths, parameters, cGOM_dataframes)
    average_fixation.write_chapter()
    end4 = time.time()
    print('Average fixation: ', end4-start4)

    start5 = time.time()
    transitions = Transitions(report, text_input, text_input_soup, tables, picture_paths, parameters, cGOM_dataframes)
    transitions.write_chapter()
    end5 = time.time()
    print('Transitions: ', end5-start5)

    conclusion = Chapter(report, text_input, text_input_soup, 'Conclusion', tables, picture_paths, parameters)
    conclusion.write_chapter()

    DocumentHistory.write(report)

    ######   APPENDIX   ######

    report.add_page_break()

    report.add_paragraph('Appendix', 'Heading 1')

    Definitions.write_references(report, text_input, text_input_soup, definitions, tables)

    report.add_page_break()

    Picture.add_figures_list(report)

    report.add_page_break()

    ParticipantsCharacteristics.write(report, text_input, tables, parameters)

    # save the report
    report.save(report_file)

    # error message for the image files that were not added to the report
    '''Picture.error_message(picture_paths)'''

    start6 = time.time()
    # update the table of content
    update(report_file)
    end6 = time.time()
    print('Update: ', end6 - start6)

    # open the report with the default application for .docx (Word)
    os.startfile(report_file)

    end = time.time()
    print(end - main_start)

if __name__ == '__main__':
    main()


from opensrane.Misc._NewClass import _NewClass
from .ObjManager import *
from opensrane.Misc.WarningRecorder import *
from ._GlobalParameters import _GlobalParameters
import math as _math

class Nodes(_NewClass,_GlobalParameters):
    '''
    This class create nodes according data that directly be specify by user

        Type: that defines content of the node: Social, Environmental , ...
        xGlobalList: Global xcoordinate of the nodes
        yGlobalList: Global ycoordinate of the nodes
        zGlobalList: Global zcoordinate of the nodes
        AreaList: Area of the defined nodes that considered as rectangular and along main axis
        IntensityList: Intensity of the node (Intendity per Area). If node is Social show the crowd per area, if environmental shows the plants per area

    '''
    Title="Nodes"

    def __init__(self,tag, xGlobalList, yGlobalList, zGlobalList, AreaList, IntensityList,
                     pressure_probit_tag=None, radiation_probit_tag=None, Toxic_probit_tag=None,Type='Social'):

        if type(xGlobalList)!=list or type(xGlobalList)!=list or type(xGlobalList)!=list or type(xGlobalList)!=list:
            warning(f'(Nodes) Nodes with tag={tag} has not been created because type of xGlobalList or yGlobalList or AreaList or IntensityList is not equal list')
            return None

        #---- Fix Part for each class __init__ ----
        ObjManager.Add(tag,self)
        _NewClass.__init__(self,tag)
        #------------------------------------------

        #Check Dimensions and modify them if needed
        lenmin=min(len(xGlobalList),len(yGlobalList),len(zGlobalList),len(AreaList),len(IntensityList))
        lenmax=max(len(xGlobalList),len(yGlobalList),len(zGlobalList),len(AreaList),len(IntensityList))

        if lenmin!=lenmax:
            warning(f'(Nodes) Nodes with tag {tag}, length of the lists are not equal and they considered as minimum length')
            xGlobalList=xGlobalList[0:lenmin]
            yGlobalList=yGlobalList[0:lenmin]
            zGlobalList=zGlobalList[0:lenmin]
            AreaList=AreaList[0:lenmin]
            IntensityList=IntensityList[0:lenmin]

        # Finilizing the Object and evluatig the values
        _GlobalParameters.__init__(self,Type=Type, xGlobalList=xGlobalList, yGlobalList=yGlobalList, zGlobalList=zGlobalList, AreaList=AreaList,
                                        IntensityList=IntensityList, pressure_probit_tag=pressure_probit_tag, radiation_probit_tag=radiation_probit_tag,
                                        Toxic_probit_tag=Toxic_probit_tag)

        self.name=f"Nodes with tag={tag} "

        self.wipeAnalysis()

    def wipeAnalysis(self):
        # properties that are defined in _GlobalParameters should also be reset
        self.wipeAnalysisGlobal()

        # properties that are not constant and among each analysis will change should be define here
        pass


import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
import matplotlib.pyplot as plt

class LinearRegression:
    def __init__(self, lr=0.001, n_iters=1000):
        self.lr = lr  # Learning rate for gradient descent
        self.n_iterations = n_iters  # Number of iterations of gradient descent
        self.weights = None  # W in  y = Wx + b
        self.bias = None  # b in y = Wx + b

    def fit(self, X, y):
        n_samples, n_features = X.shape
        self.weights = np.zeros((n_features, 1))  # Declaring the weights as zeros "can start as random"
        self.bias = 0  # Declaring the bias as zero

        for _ in range(self.n_iterations):  # Gradient descent loop for the number of iterations
            y_pred = np.dot(X, self.weights) + self.bias
            dw = (1 / n_samples) * np.dot(X.T, (y_pred - y))  # The derivative equation for the Mean Squared error loss
            db = (1 / n_samples) * np.sum(y_pred - y)  # The derivative equation for the Mean Squared error loss

            self.weights -= self.lr * dw  # Updating our weights
            self.bias -=  self.lr * db  # Updating our bias

    def predict(self, X):
        return np.dot(X, self.weights) + self.bias  # predicting the y for x

    def mse(self, y_test, predictions):
        return np.mean((y_test - predictions) ** 2)

X, y = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=4)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)

fig = plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], y, color="b", marker="o", s=30)
plt.show()

reg = LinearRegression(lr=0.01)
y_train = y_train.reshape(80, 1)
reg.fit(X_train, y_train)
predictions = reg.predict(X_test)

mse = reg.mse(y_test, predictions)
print(mse)

y_pred_line = reg.predict(X)
cmap = plt.get_cmap('viridis')
fig = plt.figure(figsize=(8, 6))
m1 = plt.scatter(X_train, y_train, color=cmap(0.9), s=10)
m2 = plt.scatter(X_test, y_test, color=cmap(0.5), s=10)
plt.plot(X, y_pred_line, color='black', linewidth=2, label='Prediction')
plt.show()


import base64

from touchdown.core import argument, resource, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.utils import force_str

from ..account import BaseAccount
from ..iam import InstanceProfile
from ..replacement import ReplacementApply, ReplacementDescribe, ReplacementDestroy
from ..vpc import SecurityGroup
from .keypair import KeyPair

class LaunchConfiguration(resource.Resource):

    resource_name = "launch_configuration"

    name = argument.String(max=255, field="LaunchConfigurationName", update=False)

    image = argument.String(max=255, field="ImageId")

    key_pair = argument.Resource(KeyPair, field="KeyName")

    security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroups")

    user_data = argument.String(field="UserData")

    json_user_data = argument.Dict(
        field="UserData", default=None, serializer=serializers.Json(serializers.Map())
    )

    instance_type = argument.String(max=255, field="InstanceType")

    kernel = argument.String(max=255, field="KernelId")

    ramdisk = argument.String(max=255, field="RamdiskId")

    # block_devices = argument.Dict(field='BlockDeviceMappings')

    instance_monitoring = argument.Boolean(
        default=False,
        field="InstanceMonitoring",
        serializer=serializers.Dict(Enabled=serializers.Identity()),
    )

    spot_price = argument.String(field="SpotPrice")

    instance_profile = argument.Resource(
        InstanceProfile,
        field="IamInstanceProfile",
        serializers=serializers.Property("Arn"),
    )

    ebs_optimized = argument.Boolean(field="EbsOptimized")

    associate_public_ip_address = argument.Boolean(field="AssociatePublicIpAddress")

    placement_tenancy = argument.String(
        max=64, choices=["default", "dedicated"], field="PlacementTenancy"
    )

    account = argument.Resource(BaseAccount)

class Describe(ReplacementDescribe, Plan):

    resource = LaunchConfiguration
    service_name = "autoscaling"
    api_version = "2011-01-01"
    describe_action = "describe_launch_configurations"
    describe_envelope = "LaunchConfigurations"
    describe_filters = {}
    key = "LaunchConfigurationName"

    _active_launch_configs = None

    @property
    def active_launch_configs(self):
        if not self._active_launch_configs:
            active = self._active_launch_configs = set()
            dasg = self.client.get_paginator("describe_auto_scaling_groups")
            for page in dasg.paginate():
                for asg in page.get("AutoScalingGroups", []):
                    active.add(asg["LaunchConfigurationName"])
        return self._active_launch_configs

    def get_possible_objects(self):
        for obj in super(Describe, self).get_possible_objects():
            if "UserData" in obj and obj["UserData"]:
                obj["UserData"] = force_str(base64.b64decode(obj["UserData"]))
            yield obj

class Apply(ReplacementApply, Describe):

    create_action = "create_launch_configuration"
    create_response = "not-that-useful"
    destroy_action = "delete_launch_configuration"

    signature = (Present("image"), Present("instance_type"))

    def is_stale(self, launch_config):
        # Don't try and delete launch configuration that are still in use
        if launch_config["LaunchConfigurationName"] in self.active_launch_configs:
            return False
        return super(Apply, self).is_stale(launch_config)

class Destroy(ReplacementDestroy, Describe):

    destroy_action = "delete_launch_configuration"


import Teams
import csv
import datetime as dt
import matplotlib.pyplot as plt
from collections import OrderedDict
import numpy as np
from constants import _Const
import dataLoader

CONST = _Const()

# Inputs
input_team = input("Team: ")
input_date = input("Date (dd/mm/yy format): ")
stop_date = dt.datetime.strptime(input_date, '%d/%m/%y')

# Load the data
fixtures = dataLoader.LoadTeamData(dt.datetime.now(), input_team)

# Sort it
sorted_teams = sorted(fixtures.values(), reverse=False, key=lambda t: t.fixture_date)
last_10_items = sorted_teams[-10:]

# Build the graph
colors = []
dates=[]

y = np.asarray([o.winner for o in last_10_items] )
dates = np.asarray([o.fixture_date for o in last_10_items])
idx = np.asarray([i for i in range(len(dates))])

# Sort the colours out
for h in last_10_items:
    if h.winner == 2:
        colors.append('g')
    elif h.winner == 1:
        colors.append('b')
    else:
        colors.append('r')

fig, ax = plt.subplots(figsize = (10,4))

plt.tick_params(
    axis='y',          # changes apply to the y-axis
    which='both',      # both major and minor ticks are affected
    left='off',
    top='off',
    right='off',
    bottom='off',
    labelleft='off',
    labeltop='off',
    labelright='off',
    labelbottom='off'
    )

width = 1

ax.bar(idx, y, width=width, color=colors )
ax.set_xticks(idx)
ax.set_xticklabels(dates, rotation=65)
ax.set_xlabel('Fixture date')
ax.set_ylabel('Result')
fig.tight_layout()

plt.savefig(CONST.OUTPUT_PATH + input_team + '_last10_bar.jpg')


import turtle
turtle.bgcolor("skyblue")
turtle.setup(500,500)

# setup pen
pen = turtle.Turtle()
pen.color("black")
pen.fillcolor("white")
pen.hideturtle()
pen.speed(0)

# turtle.numinput("Title", "Prompt", ""default", "min", "max")
size = turtle.numinput("Snowman", "Size (1-4): " ,3,1,4)
lgRadius = size * 20
medRadius = size * 15
smRadius = size * 10
eyeRadius = size * 2
noseSize = size * 4

# draw the bottom circle
pen.up()
pen.setpos(0, -2*lgRadius)
pen.down()
pen.begin_fill()
pen.circle(lgRadius)
pen.end_fill()

# draw medium circle
pen.up()
pen.setpos(0,0)
pen.down()
pen.begin_fill()
pen.circle(medRadius)
pen.end_fill()

# draw small circle
pen.up()
pen.setpos(0, medRadius*2)
pen.down()
pen.begin_fill()
pen.circle(smRadius)
pen.end_fill()

# draw right eye
pen.up()
pen.setpos(smRadius/3, (medRadius*2)+smRadius)
pen.fillcolor("black")
pen.down()
pen.begin_fill()
pen.circle(eyeRadius)
pen.end_fill()

# draw left eye
pen.up()
pen.setpos(-smRadius/3, (medRadius*2)+smRadius)
pen.fillcolor("black")
pen.down()
pen.begin_fill()
pen.circle(eyeRadius)
pen.end_fill()

# draw nose
pen.up()
pen.setpos(0, (2*medRadius)+0.5*smRadius)
pen.fillcolor("orange")
pen.down()
pen.begin_fill()

# nose first line
pen.setheading(60)
pen.forward(noseSize)

# nose second line
pen.left(120)
pen.forward(noseSize)

# nost third line
pen.left(120)
pen.forward(noseSize)

pen.end_fill()

turtle.done()


import itertools as iter
import logging
import numpy as np
import random
from scipy import special
from functools import lru_cache
import warnings
import time
import matplotlib.pyplot as plt

logging.info("Started program.")
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)
logging.basicConfig(format='%(asctime)s - %(levelname)s:%(message)s', filename='log{}.log'.format(int(time.time())), level=logging.INFO)

@lru_cache(maxsize=10000)
def binc(n, k):
    return special.binom(n,k)

def randomIntGaussian(lb, ub):
    g = random.gauss((lb+ub)/2, (lb-(lb+ub)/2)/4)
    i = int(g)
    return min(max(lb,i),ub)

def generateSplitSet(conditionals, totalSize, condDuplets, condTriplets):
    logging.debug("Called generateSplitSet.")
    remainingSize = totalSize - conditionals
    if 2 * condDuplets + 3 * condTriplets > conditionals:
        logging.error(f"Stone set of size {totalSize} with {conditionals} conditionals is too small for {condDuplets} duplets and {condTriplets} triplets.")
    else:
        set = []
        condChars = []
        numberOfSingleStones = conditionals - (2 * condDuplets + 3 * condTriplets)
        n = 0
        for m in range(condDuplets):
            condChars.append(chr(n+65))
            set.append(chr(n+65)+"1")
            set.append(chr(n+65)+"2")
            n +=1
        for m in range(condTriplets):
            condChars.append(chr(n+65))
            set.append(chr(n+65)+"1")
            set.append(chr(n+65)+"2")
            set.append(chr(n+65)+"3")
            n +=1
        for m in range(numberOfSingleStones):
            condChars.append(chr(n+65))
            set.append(chr(n+65)+"1")
            n += 1
        for m in range(remainingSize):
            set.append(chr(n+65)+"1")
            n += 1
        logging.debug(f"Generated stone set. (set:{set}, condChars:{condChars})")
        return (set, condChars)

def countUniqueStonesInList(list):
    length = len(set([n[0] for n in list]))
    return length

def listContainsNUniqueConditionals(list, condChars):
    tempList = [n for n in list if n[0] in condChars]
    return countUniqueStonesInList(tempList)

def checkListsForContainingNUnique(size, sizeOfConditionals, sizeOfDraw, duplets, triplets):
    logging.debug("Called checkListsForContainingNUnique.")
    sourceSet, condChars= generateSplitSet(sizeOfConditionals, size, duplets, triplets)
    possibleHands = iter.combinations(sourceSet, sizeOfDraw)
    matching = [0,0,0,0,0,0,0]
    logging.debug(f"Check {binc(len(sourceSet), sizeOfDraw)} hand.")
    for hand in possibleHands:
        uniq = listContainsNUniqueConditionals(hand, condChars)
        if uniq < 0 or uniq > 6: logging.error(f"False uniq in hand {hand}")
        matching[uniq] += 1
    return matching

def M(k2, b, i, j, e, f, g):
    logging.debug("Called M.")
    logging.debug(f"Parameters - k: {k2}, b: {b}, i: {i}, j: {j}, e(T3): {e}, f(T2): {f}, g(D2): {g}.")
    if (k2 < 0) or (b < 0) or (i < 0) or (j < 0):
        logging.warning(f"Function called with negative arguments. Returning 0.")
        return 0
    if (e + f > j) or (g > i):
        logging.warn(f"(e, f, g) - ({e}, {f}, {g}) not compatible with (i, j) - ({i}, {j}). Returning 0.")
        return 0
    if (b-(2*g+3*f+3*e)-(i-g)-(j-(e+f))*2<k2-(2*g+2*f+3*e)):
        logging.debug("Impossible combination of e,f,g and i,j. Returning 0.")
        return 0

    b_c = b  - (2*g+3*f+3*e)
    k_c = k2 - (2*g+2*f+3*e)
    i_c = i  - g
    j_c = j  - (e+f)

    mz = sum([binc(i_c,l)*binc(j_c,h)*binc(b_c-2*i_c-3*j_c, k_c-l-h)*2**l*3**h for l in range(0,i_c+1) for h in range(0,j_c+1)])

    d2 = binc(i,g)
    t3 = binc(j,e)
    t2 = binc(j-e, f)*3**f
    logging.debug(f"Calculated following components - d2: {d2}, t2: {t2}, t3: {t3}, mz: {mz}")

    number = d2*t3*t2*mz
    return number

def generateEFG(noOfDraw, noOfUniques, noOfDuplets, noOfTriplets):
    logging.debug("Called generateEFG.")
    logging.debug(f"Parameters - noOfDraw: {noOfDraw}, noOfUniques: {noOfUniques}, i: {noOfDuplets}, j: {noOfTriplets}.")
    sets = [(e,f,g) for e in range(0,noOfTriplets+1) for f in range(0,noOfTriplets+1) for g in range(0, noOfDuplets+1)]
    valid = []
    for s in sets:
        e,f,g = s[0], s[1], s[2]
        if (noOfDraw-(2*e+f+g)==noOfUniques) and (e+f <= noOfTriplets) and (g <= noOfDuplets):
            valid.append(s)
    logging.debug(f"Generated following sets {sets}.")
    return valid

def NUnique(noOfDraw, noOfStones, noOfDuplets, noOfTriplets, noOfUniques):
    logging.debug("Called NUnique.")
    logging.debug(f"Parameters - noOfDraw: {noOfDraw}, noOfStones: {noOfStones}, noOfUniques: {noOfUniques}, i: {noOfDuplets}, j: {noOfTriplets}.")
    efgs = generateEFG(noOfDraw, noOfUniques, noOfDuplets, noOfTriplets)
    no = 0
    for s in efgs:
        e,f,g = s[0], s[1], s[2]
        local = M(noOfDraw, noOfStones, noOfDuplets, noOfTriplets, e, f, g)
        no += local
    return no

def N(sizeOfDraw, availableStones, conditionalsAmongStones, numberOfDuplets, numberOfTriplets, wishedNumber):
    logging.debug("Called N.")
    logging.debug(f"Parameters - conds: {conditionalsAmongStones}, k: {sizeOfDraw}, noOfStones: {availableStones}, noOfUniques: {wishedNumber}, i: {numberOfDuplets}, j: {numberOfTriplets}.")
    n = 0
    for firstHalfSize in range(wishedNumber, min(sizeOfDraw+1, conditionalsAmongStones+1)):
        firstHalfN = NUnique(firstHalfSize, conditionalsAmongStones, numberOfDuplets, numberOfTriplets, wishedNumber)
        local = firstHalfN*binc(availableStones-conditionalsAmongStones, sizeOfDraw-firstHalfSize)
        n += local
    logging.debug(f"Calculated {n} as result.")
    return n

@lru_cache(maxsize=20)
def generateTripDup(conds):
    return [(n,m,k) for n in range(0,7) for m in range(0,7-n) for k in range(0,7-n-m) if n+2*m+3*k == conds]

def main():
    n = 0
    no = 5000
    while n<no:
        logging.info(f"Iteration {n} started.")
        availableStones = random.randint(10,25)
        conditionalsAmongStones = randomIntGaussian(0,min(availableStones,19))
        sizeOfDraw = randomIntGaussian(0,availableStones)
        opts = generateTripDup(conditionalsAmongStones)
        parms = random.choice(opts)
        numberOfDuplets, numberOfTriplets = parms[1], parms[2]
        logging.info(f"Generated following random parameters - available: {availableStones}, conditionals: {conditionalsAmongStones}, draw: {sizeOfDraw}, i: {numberOfDuplets}, j: {numberOfTriplets}")

        sums = [0,0]
        exacts = checkListsForContainingNUnique(availableStones, conditionalsAmongStones, sizeOfDraw, numberOfDuplets, numberOfTriplets)
        for wishedNumber in range(0,7):
            logging.debug(f"Calculation for wished {wishedNumber} started.")
            exact = exacts[wishedNumber]
            predicted = N(sizeOfDraw, availableStones, conditionalsAmongStones, numberOfDuplets, numberOfTriplets, wishedNumber)
            sums[0] += exact
            sums[1] += predicted
            logging.debug(f"exact vs. predicted :{int(exact)}|{int(predicted)}")
        logging.info(f"Sum of exact is {sums[0]}, of predicted is {sums[1]} - required is {binc(availableStones, sizeOfDraw)}")
        if [n/binc(availableStones, sizeOfDraw) for n in sums] != [1.0, 1.0]:
            logging.error("N not sum 1.")
        if int(exact) != int(predicted):
            logging.error(f"N not correct.")
        n += 1
        print(round(n/no,5))
    return 0

if __name__ == "__main__":
    main()


import pandas as pd
sal_data = pd.read_csv("/Users/johnkabler/gadsdata/salary/train.csv")

# ###Vowpal Wabbit Input Format
#
#     1 1.0 |MetricFeatures:3.28 height:1.5 length:2.0 |Says black with white stripes |OtherFeatures NumberOfLegs:4.0 HasStripes
#
#
#     1 1.0 zebra|MetricFeatures:3.28 height:1.5 length:2.0 |Says black with white stripes |OtherFeatures NumberOfLegs:4.0 HasStripes
#     1 2 'tag| a:2 b:3
#     1 2 'tag | a:2 b:3

sal_dict = sal_data.T.to_dict()
# 25000 |Category Engineering Jobs |Company Gregory Martin |ContractTime permanent |Id:1266677 '\n'
for row in sal_dict:
    sal_norm = str(sal_dict[row].pop('SalaryNormalized'))
    sal_row = ""
    for key in sal_dict[row].keys():
        sal_row += sal_norm
        sal_row += " "
        try:
            sal_row += "|" + key + " " + sal_dict[row][key] + " "
        except:
            sal_row += "|" + key + ":" + str(sal_dict[row][key]) + " "
    print(sal_row + '\n')


import pathlib
import unittest
from tempfile import TemporaryDirectory
from unittest.mock import patch

THUMBNAIL_URL = (
    'http://books.google.com/books/content'
    '?id=OgtBw760Y5EC&printsec=frontcover'
    '&img=1&zoom=1&edge=curl&source=gbs_api'
)

class SaveThumbnailsTest(unittest.TestCase):
    def setUp(self):
        # 임시 디렉터리 작성
        self.tmp = TemporaryDirectory()

    def tearDown(self):
        # 임시 디렉터리 정리
        self.tmp.cleanup()

    def test_save_thumbnails(self):
        from booksearch.core import Book
        book = Book({'id':'', 'volumeInfo':{
            'imageLinks':{
                'thumbnail' : THUMBNAIL_URL
            }}})

        filename = book.save_thumbnails(self.tmp.name)[0]
        self.assertTrue(pathlib.Path(filename).exists())

    @patch ('booksearch.core.get_data')
    def test_save_thumbnails(self, mock_get_data):
        from booksearch.core import Book
        data_path = pathlib.Path(__file__).with_name('data')
        mock_get_data.return_value = (
            data_path / 'puFBDwAAQBAJ_thumbnail.jpeg').read_bytes()

        book = Book({'id': '', 'volumeInfo' : {
            'imageLinks': {
                'thumbnail': THUMBNAIL_URL
            }}})

        filename = book.save_thumbnails(self.tmp.name)[0]
        mock_get_data.assert_called_with(THUMBNAIL_URL)

        self.assertEqual( mock_get_data.return_value, filename.read_bytes())

if __name__ == '__main__' :
    unittest.main()