import sys
import unittest
import sqlite3
import os

from masarclient import masarClient
from pymasarsqlite.service.serviceconfig import (saveServiceConfig, retrieveServiceConfigs, retrieveServiceConfigPVs, saveServicePvGroup, retrieveServicePvGroups)
from pymasarsqlite.pvgroup.pvgroup import (savePvGroup, retrievePvGroups)
from pymasarsqlite.pvgroup.pv import (saveGroupPvs, retrieveGroupPvs)
from pymasarsqlite.service.service import (saveService)
from unittest_utils import SQLITE_DB_TEST_SETUP, SQLITE_DROP_ALL_TABLES

'''

Unittests for masarService/python/masarclient/masarClient.py

'''

class TestMasarClient(unittest.TestCase):

    def setUp(self):
        channel = 'sqliteMasarTestService'
        self.mc = masarClient.client(channelname=channel)
        SQLITE_DB_TEST_SETUP()

    def tearDown(self):
        SQLITE_DROP_ALL_TABLES()

    def testRetrieveSystemList(self):
        result = self.mc.retrieveSystemList()
        self.assertNotEqual(result, None)  # Can not be assertTrue because there is no case where it returns True
        self.assertNotEqual(result, False)  # Instead asserting both not None and not False
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0], 'SR')  # expected result

    def testRetrieveServiceConfigs(self):
        params = {'system': 'SR'}
        # Test should return empty data set as 'bad system' does not exist
        bad_params = {'system': 'bad system'}
        bad_res = self.mc.retrieveServiceConfigs(bad_params)
        self.assertEqual((), bad_res[0])
        self.assertEqual((), bad_res[1])
        self.assertEqual((), bad_res[2])
        self.assertEqual((), bad_res[3])
        self.assertEqual((), bad_res[4])
        self.assertEqual((), bad_res[5])
        # Remaining tests are for expected results
        result = self.mc.retrieveServiceConfigs(params)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)
        self.assertEqual(len(result), 6)  # expected results
        self.assertEqual(1, result[0][0])
        self.assertEqual('SR_All_20140421', result[1][0])
        self.assertEqual('test desc', result[2][0])
        self.assertNotEqual(None, result[3][0])
        self.assertEqual('', result[4][0])
        self.assertEqual('active', result[5][0])

    def testRetrieveServiceEvents(self):
        params = {'configid': '1'}
        result = self.mc.retrieveServiceEvents(params)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)

    def testSaveSnapshot(self):
        bad_params = {'configname': 'SR_All_20140421',
                  'servicename': 'bad_servicename'}
        params = {'configname': 'SR_All_20140421',
                  'servicename': 'masar'}
        bad_res = self.mc.saveSnapshot(bad_params)
        self.assertEqual(False, bad_res)
        result = self.mc.saveSnapshot(params)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)
        # The following tests are for expected outputs
        expected_result = (1, ('masarExample0000',  # ChannelName 0
                                'masarExample0001',  # ChannelName 1
                                'masarExampleBoUninit',  # ChannelName 2
                                'masarExampleMbboUninit',  # ChannelName 3
                                'masarExample0002',  # ChannelName 4
                                'masarExample0003',  # ChannelName 5
                                'masarExample0004',  # ChannelName 6
                                'masarExampleCharArray',  # ChannelName 7
                                'masarExampleShortArray',  # ChannelName 8
                                'masarExampleLongArray',  # ChannelName 9
                                'masarExampleStringArray',  # ChannelName 10
                                'masarExampleFloatArray',  # ChannelName 11
                                'masarExampleDoubleArray',  # ChannelName 12
                                'masarExampleMbboUninitTest'),  # ChannelName 13
                                (10,  # 0000 Value
                                'string value',  # 0001 Value
                                0,  # BoUninit Value
                                1,  # MbboUninit Value
                                'zero',  # 0002 Value
                                'one',  # 0003 Value
                                1.9,  # 0004 Value
                                (),  # CharArray Value
                                (),  # ShortArray Value
                                (),  # LongArray Value
                                (),  # StringArray Value
                                (),  # FloatArrayValue
                                (),  # DoubleArray Value
                                1),  # MbboUninitTest Value
                                (5, 0, 0, 5, 0, 0, 6, 4, 1, 5, 0, 2, 6, 5),  # DBR type
                                (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),  # isConnected
                                (631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000),  # SecondsPastEpoch
                                (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # NanoSeconds
                                (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # UserTag
                                (0, 0, 3, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0),  # Severity
                                (3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3),  # Status
                                ('UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM'))  # Message
        self.assertSequenceEqual(result, expected_result)

    def testRetrieveSnapshot(self):
        save_params = {'configname': 'SR_All_20140421',
                  'servicename': 'masar'}
        res1 = self.mc.saveSnapshot(save_params)
        self.assertNotEqual(res1, None)
        self.assertNotEqual(res1, False)
        event_id = res1[0]
        retrieve_params = {'eventid': str(event_id)}
        result = self.mc.retrieveSnapshot(retrieve_params)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)
        # The following tests are for expected outputs
        expected_result = (('masarExample0000',  # ChannelName 0
                               'masarExample0001',  # ChannelName 1
                               'masarExampleBoUninit',  # ChannelName 2
                               'masarExampleMbboUninit',  # ChannelName 3
                               'masarExample0002',  # ChannelName 4
                               'masarExample0003',  # ChannelName 5
                               'masarExample0004',  # ChannelName 6
                               'masarExampleCharArray',  # ChannelName 7
                               'masarExampleShortArray',  # ChannelName 8
                               'masarExampleLongArray',  # ChannelName 9
                               'masarExampleStringArray',  # ChannelName 10
                               'masarExampleFloatArray',  # ChannelName 11
                               'masarExampleDoubleArray',  # ChannelName 12
                               'masarExampleMbboUninitTest'),  # ChannelName 13
                           (10,  # 0000 Value
                            'string value',  # 0001 Value
                            '0',  # BoUninit Value
                            1,  # MbboUninit Value
                            'zero',  # 0002 Value
                            'one',  # 0003 Value
                            1.9,  # 0004 Value
                            (),  # CharArray Value
                            (),  # ShortArray Value
                            (),  # LongArray Value
                            (),  # StringArray Value
                            (),  # FloatArrayValue
                            (),  # DoubleArray Value
                            1),  # MbboUninitTest Value
                           (5, 0, 0, 5, 0, 0, 6, 4, 1, 5, 0, 2, 6, 5),  # DBR type
                           (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),  # isConnected
                           (631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000,
                            631152000, 631152000, 631152000, 631152000, 631152000, 631152000),  # SecondsPastEpoch
                           (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # NanoSeconds
                           (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # UserTag
                           (0, 0, 3, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0),  # Severity
                           (3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3),  # Status
                           ('UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM',
                            'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM',
                            'UDF_ALARM'))  # Message
        self.assertSequenceEqual(result, expected_result)

    def testApproveSnapshot(self):
        save_params = {'configname': 'SR_All_20140421',
                       'servicename': 'masar'}

        res1 = self.mc.saveSnapshot(save_params)
        self.assertNotEqual(res1, None)
        self.assertNotEqual(res1, False)  # Can not be assertTrue because there is no case where it returns True
        event_id = res1[0]
        approve_params = {'eventid': str(event_id),
                  'configname': 'SR_All_20140421',
                  'user': 'test',
                  'desc': 'this is a good snapshot, and I approved it.'}
        result = self.mc.updateSnapshotEvent(approve_params)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)
        self.assertEqual(result, True)  # Expected Output

    def testGetLiveMachine(self):
        pvlist = {"masarExample0000": "masarExample0000",
                  "masarExample0001": "masarExample0001",
                  "masarExampleBoUninit": "masarExampleBoUninit",
                  "masarExampleMbboUninit": "masarExampleMbboUninit",
                  "masarExample0002": "masarExample0002",
                  "masarExample0003": "masarExample0003",
                  "masarExample0004": "masarExample0004",
                  "masarExampleCharArray": "masarExampleCharArray",
                  "masarExampleShortArray": "masarExampleShortArray",
                  "masarExampleLongArray": "masarExampleLongArray",
                  "masarExampleStringArray": "masarExampleStringArray",
                  "masarExampleFloatArray": "masarExampleFloatArray",
                  "masarExampleDoubleArray": "masarExampleDoubleArray",
                  "masarExampleMbboUninitTest": "masarExampleMbboUninitTest"}
        result = self.mc.getLiveMachine(pvlist)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)
        # The following tests are for expected outputs
        expected_result = (('masarExampleCharArray',  # ChannelName 0
                             'masarExample0004',  # ChannelName 1
                             'masarExampleDoubleArray',  # ChannelName 2
                             'masarExample0002',  # ChannelName 3
                             'masarExample0003',  # ChannelName 4
                             'masarExample0000',  # ChannelName 5
                             'masarExample0001',  # ChannelName 6
                             'masarExampleStringArray',  # ChannelName 7
                             'masarExampleLongArray',  # ChannelName 8
                             'masarExampleShortArray',  # ChannelName 9
                             'masarExampleMbboUninitTest',  # ChannelName 10
                             'masarExampleMbboUninit',  # ChannelName 10
                             'masarExampleFloatArray',  # ChannelName 11
                             'masarExampleBoUninit'),  # ChannelName 12
                             ((),  # CharArray Value
                             1.9,  # 0004 Value
                             (),  # DoubleArray Value
                             'zero',  # 0002 Value
                             'one',  # 0003 Value
                             10,  # 0000 Value
                             'string value',  # 0001 Value
                             (),  # StringArray Value
                             (),  # LongArray Value
                             (),  # ShortArray Value
                             1,  # MbboUninitTest Value
                             1,  # MbboUninit Value
                             (),  # FloatArray Value
                             0),  # BoUninit Value
                             (4, 6, 6, 0, 0, 5, 0, 0, 5, 1, 5, 5, 2, 0),  # DBR type
                             (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),  # isConnected
                             (631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000),  # SecondsPastEpoch
                             (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # NanoSeconds
                             (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # UserTag
                             (3, 0, 3, 3, 0, 0, 0, 3, 3, 3, 0, 0, 3, 3),  # Severity
                             (3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3),  # Status
                             ('UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM'))  # Message
        self.assertSequenceEqual(result, expected_result)

    def testMultiGroup(self):
        # DB SETUP
        __sqlitedb__ = os.environ["MASAR_SQLITE_DB"]
        try:
            conn = sqlite3.connect(__sqlitedb__)
            pvgname1 = 'masarpvgroup1'
            pvgdesc1 = 'this is my new pv group for masar service with same group name'
            pvs1 = ["masarExample0000",
                    "masarExample0001",
                    "masarExampleBoUninit",
                    "masarExampleMbboUninit",
                    "masarExample0002",
                    "masarExample0003",
                    "masarExampleFloatArray",
                    "masarExample0004"]
            res1 = savePvGroup(conn, pvgname1, func=pvgdesc1)
            res1 = saveGroupPvs(conn, pvgname1, pvs1)
            pvgname2 = 'masarpvgroup2'
            pvgdesc2 = 'this is my new pv group for masar service with same group name'
            pvs2 = ["masarExample0000",
                    "masarExample0001",
                    "masarExample0002",
                    "masarExample0004",
                    "masarExampleCharArray",
                    "masarExampleShortArray",
                    "masarExampleLongArray",
                    "masarExampleStringArray",
                    "masarExampleFloatArray",
                    "masarExampleDoubleArray",
                    "masarExampleMbboUninitTest"]
            res2 = savePvGroup(conn, pvgname2, func=pvgdesc2)
            res2 = saveGroupPvs(conn, pvgname2, pvs2)
            pvgroups = retrievePvGroups(conn)
            self.assertEqual(pvgroups[0][1], "masarpvgroup")
            self.assertEqual(pvgroups[1][1], "masarpvgroup1")
            self.assertEqual(pvgroups[2][1], "masarpvgroup2")
            pvgroups = retrieveGroupPvs(conn, 2)
            self.assertEqual(pvgroups[0][0], "masarExample0000")
            self.assertEqual(pvgroups[1][0], "masarExample0001")
            self.assertEqual(pvgroups[2][0], "masarExampleBoUninit")
            self.assertEqual(pvgroups[3][0], "masarExampleMbboUninit")
            self.assertEqual(pvgroups[4][0], "masarExample0002")
            self.assertEqual(pvgroups[5][0], "masarExample0003")
            self.assertEqual(pvgroups[6][0], "masarExample0004")
            self.assertEqual(pvgroups[7][0], "masarExampleFloatArray")
            pvgroups = retrieveGroupPvs(conn, 3)
            self.assertEqual(pvgroups[0][0], "masarExample0000")
            self.assertEqual(pvgroups[1][0], "masarExample0001")
            self.assertEqual(pvgroups[2][0], "masarExample0002")
            self.assertEqual(pvgroups[3][0], "masarExample0004")
            self.assertEqual(pvgroups[4][0], "masarExampleCharArray")
            self.assertEqual(pvgroups[5][0], "masarExampleShortArray")
            self.assertEqual(pvgroups[6][0], "masarExampleLongArray")
            self.assertEqual(pvgroups[7][0], "masarExampleStringArray")
            self.assertEqual(pvgroups[8][0], "masarExampleFloatArray")
            self.assertEqual(pvgroups[9][0], "masarExampleDoubleArray")
            self.assertEqual(pvgroups[10][0], "masarExampleMbboUninitTest")
            servicename = "masar"
            masarconf = "testconf"
            saveService(conn, servicename, desc='test desc')
            saveServiceConfig(conn, servicename, masarconf, system='SR', status='active',
                              configversion=20140420, configdesc='test desc')

            res = saveServicePvGroup(conn, masarconf, [pvgname1, pvgname2])
            conn.commit()
            conn.close()
        except:
            raise
        save_params = {'configname': 'testconf',
                       'servicename': 'masar'}
        res1 = self.mc.saveSnapshot(save_params)
        self.assertNotEqual(res1, None)
        self.assertNotEqual(res1, False)
        event_id = res1[0]
        retrieve_params = {'eventid': str(event_id)}
        result = self.mc.retrieveSnapshot(retrieve_params)
        self.assertNotEqual(result, None)
        self.assertNotEqual(result, False)

        expected_results = (('masarExample0000',  # ChannelName 0
                            'masarExample0001',  # ChannelName 1
                            'masarExampleBoUninit',  # ChannelName 2
                            'masarExampleMbboUninit',  # ChannelName 3
                            'masarExample0002',  # ChannelName 4
                            'masarExample0003',  # ChannelName 5
                            'masarExample0004',  # ChannelName 6
                            'masarExampleCharArray',  # ChannelName 7
                            'masarExampleShortArray',  # ChannelName 8
                            'masarExampleLongArray',  # ChannelName 9
                            'masarExampleStringArray',  # ChannelName 10
                            'masarExampleFloatArray',  # ChannelName 11
                            'masarExampleDoubleArray',  # ChannelName 12
                            'masarExampleMbboUninitTest'),  # ChannelName 13
                            (10,  # 0000 Value
                            'string value',  # 0001 Value
                            '0',  # BoUninit Value (appropriately returned as string,
                            1,  # MbboUninit Value
                            'zero',  # 0002 Value
                            'one',  # 0003 Value
                            1.9,  # 0004 Value
                            (),  # CharArray Value
                            (),  # ShortArray Value
                            (),  # LongArray Value
                            (),  # StringArray Value
                            (),  # FloatArrayValue
                            (),  # DoubleArray Value
                            1),  # MbboUninitTest Value
                            (5, 0, 0, 5, 0, 0, 6, 4, 1, 5, 0, 2, 6, 5),  # DBR type
                            (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),  # isConnected
                            (631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000, 631152000,
                            631152000, 631152000, 631152000, 631152000),  # SecondsPastEpoch
                            (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # NanoSeconds
                            (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # UserTag
                            (0, 0, 3, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0),  # Severity
                            (3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3),  # Status
                            ('UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM',
                             'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM', 'UDF_ALARM'))  # Message
        self.assertSequenceEqual(result, expected_results)

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


import pygame
from pygame.locals import *
import sys
import random
from player import Player
from platform import Platform
from math import atan2, sin, cos

pygame.init()
pygame.display.set_caption('Platformer')
screen_info = pygame.display.Info()
size = (width, height) = (screen_info.current_w, screen_info.current_h)
font = pygame.font.SysFont(None, 70)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
color = (255, 224, 179)
sprites = pygame.sprite.Group()
platforms = pygame.sprite.Group()
player = ''

def get_player_actions():
    p1_actions = {
        'player': pygame.image.load('images/player.png').convert(),
        'fire': pygame.image.load('images/fire.png').convert()
    }
    p1_actions['player'].set_colorkey((0, 0, 0))
    p1_actions['fire'].set_colorkey((0, 0, 0))

    return p1_actions

def init(p1_actions):
    platforms.empty()
    global player
    for i in range(height // 100):
        for j in range(width // 420):
            platform = Platform((random.randint(5, (width - 50) // 10) * 10,
                                 120 * j + random.randint(0, 4) * 100), 'images/platform.png', 70, 40)
            platforms.add(platform)
    player = Player((platforms.sprites()[-1].rect.centerx, platforms.sprites()[-1].rect.centery - 300), p1_actions)
    sprites.add(player)

def main():
    global player
    game_over = False
    p1_actions = get_player_actions()
    init(p1_actions)
    while True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == K_f:
                    pygame.display.toggle_fullscreen()
                if event.key == K_ESCAPE:
                    sys.exit()
                if game_over and event.key == K_r:
                    player.kill()
                    init(p1_actions)
                    game_over = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = event.pos
                xd = (mouse_pos[0] - player.rect.centerx)
                yd = (mouse_pos[1] - player.rect.centery)
                dir = atan2(xd, yd)
                xv = sin(dir) * 50
                yv = cos(dir) * 20
                player.xy_speed[0] += xv
                player.xy_speed[1] += yv
            keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            player.left()
        if keys[pygame.K_RIGHT]:
            player.right()

        if player.update(platforms):
            game_over = True

        screen.fill(color)
        text = font.render(('Score: %s' % player.progress), True, (255, 0, 0))
        text_rect = text.get_rect()
        sprites.draw(screen)
        sprites.update(platforms)
        platforms.update()
        platforms.draw(screen)
        screen.blit(text, text_rect)
        pygame.display.flip()

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Filipe Laíns <lains@riseup.net>

from __future__ import annotations

import argparse
import functools
import os
import shutil
import subprocess
import sys
import traceback
import warnings

from typing import Any, Dict, List, MutableMapping, Optional, Set, TextIO, Type, Union

_MIN_PYTHON_VERSION = (3, 9)

# disable colors if we're not in a TTY
if sys.stdout.isatty():
    _RESET = '\33[0m'
    _DIM = '\33[2m'
    _RED = '\33[91m'
    _CYAN = '\33[96m'
else:
    _RESET = ''
    _DIM = ''
    _RED = ''
    _CYAN = ''

def _error(msg: str, code: int = 1) -> None:
    '''
    Prints an error message and exit with code
    '''
    print(f'{_RED}ERROR{_RESET} {msg}')
    exit(code)

if sys.version_info < _MIN_PYTHON_VERSION:
    _error(
        f'Unsupported Python version: {".".join(map(str, sys.version_info[:3]))}... '
        f'You need at least Python {".".join(map(str, _MIN_PYTHON_VERSION))}.'
    )

# external imports with nice error messages for better UX

try:
    import toml
except ImportError:
    _error(
        'Missing toml dependency!\n'
        'You can install it with: pip install toml'
    )

try:
    import ninja_syntax  # noqa: F401
except ImportError:
    _error(
        'Missing ninja_syntax dependency!\n'
        'You can install it with: pip install ninja_syntax'
    )
else:
    import build_system.dependencies
    import build_system.ninja

# overide default warning handler for a nice CLI

def _showwarning(
    message: Union[Warning, str],
    category: Type[Warning],
    filename: str,
    lineno: int,
    file: Optional[TextIO] = None,
    line: Optional[str] = None,
) -> None:
    '''
    Show warning to the console

    We override warnings.showwarning with this to match our CLI
    '''
    prefix = 'WARNING'
    if sys.stdout.isatty():
        prefix = '\33[93m' + prefix + '\33[0m'
    print('{} {}'.format(prefix, str(message)))

warnings.showwarning = _showwarning

# find available targets
_root = os.path.abspath(os.path.dirname(__file__))
_configs = os.path.join(_root, 'config')
_configs_targets = os.path.join(_configs, 'targets')
_configs_families = os.path.join(_configs, 'families')
TARGETS = [
    # look for targets in config/targets
    target.split('.')[0] for target in os.listdir(_configs_targets)
    if target.endswith('.toml')
]

# find target config options, for the ones that support configs
TARGET_CONFIGS: Dict[str, List[str]] = {}
for _target in TARGETS:
    # find the targets that have `has-config` in their config, and populate the
    # possible config choices with the options available in src/targets/{_target}/config
    _target_config = toml.load(os.path.join(_configs_targets, f'{_target}.toml'))
    if 'has-config' in _target_config:
        _configs_dir = os.path.join(_root, 'src', 'targets', _target, 'config')
        TARGET_CONFIGS[_target] = [
            config.split('.')[0] for config in os.listdir(_configs_dir)
            if config.endswith('.h')
        ]

class BuildError(Exception):
    pass

class BuildSystemBuilder():
    _REQUIRED_TOOLS = (
        'ar',
        'gcc',
        'objcopy',
        'size',
    )

    _target_config: MutableMapping[str, Any]
    _family_config: MutableMapping[str, Any]

    def __init__(
        self,
        target: str,
        *,
        builddir: str = 'build',
        debug: bool = False,
        toolchain: Optional[str] = None,
        vendor: str = 'openinput-git',
        config: Optional[str] = None,
        no_fetch: bool = False,
    ) -> None:
        self._target = target
        self._toolchain = toolchain
        self._vendor = vendor
        self._config = config
        self._no_fetch = no_fetch

        self._build_mode = 'debug' if debug else 'release'

        self._this_file_name = os.path.basename(__file__)
        self._linker: Optional[str] = None

        self._calculate_root(builddir)
        self._load_target_config()
        self._load_family_config()
        self._load_base_config()

        self._populate_source()
        self._populate_linker()
        self._populate_options()
        self._populate_vendor_options()

        self._validate_toolchain()
        self._calculate_extensions()

        self._populate_dependencies()

    def _calculate_root(self, builddir: str) -> None:
        self._root = _root
        if self._root == os.getcwd():  # use relative path if we are building in the current directory
            self._root = os.curdir

        self._builddir = os.path.join(builddir, self._target)

    def _load_target_config(self) -> None:
        if not self._target:
            raise ValueError('Invalid target: empty target')
        if self._target == 'linux-uhid' and sys.platform != 'linux':
            raise ValueError('linux-uhid target is only available on Linux')

        config_path = os.path.join(_configs_targets, f'{self._target}.toml')
        if not os.path.isfile(config_path):
            raise ValueError(f'Target not found: {self._target} ({config_path})')

        self._target_config = toml.load(config_path)

    def _load_family_config(self) -> None:
        if 'family' not in self._target_config:
            if not self._target_config['family']:
                raise ValueError('Target family was specified but is empty')
            self._family_config = {}
            return

        self._family = self._target_config['family']
        config_path = os.path.join(_configs_families, f'{self._family}.toml')
        if not os.path.isfile(config_path):
            raise ValueError(f'Family not found: {self._target_config[self._family]} ({config_path})')

        self._family_config = toml.load(config_path)

    def _load_base_config(self) -> None:
        config_path = os.path.join(_configs, 'base.toml')
        if not os.path.isfile(config_path):
            raise ValueError(f'Base config not found ({config_path})')

        self._base_config = toml.load(config_path)

    def _populate_source(self) -> None:
        self._source: Set[str] = set()

        # common
        base_src = self._base_config.get('source', [])

        # family
        family_src = self._family_config.get('source', [])
        try:
            family_src += self._family_config[self._build_mode]['source']
        except KeyError:
            pass

        # target
        target_src = self._target_config.get('source', [])
        try:
            target_src += self._target_config[self._build_mode]['source']
        except KeyError:
            pass

        # TODO: select between main.c and bootloader.c
        target_src.append('main.c')

        self._source.update([
            file.replace('/', os.path.sep) for file in base_src
        ] + [
            os.path.join('platform', self._family, file) for file in family_src
        ] + [
            os.path.join('targets', self._target, file) for file in target_src
        ])

    def _populate_linker(self) -> None:
        if self._family_config.get('has-linker', True) is False:  # default to true
            return  # does not need linker

        self._linker_dir = os.path.join('config', 'linker')

        # if the target has config, each config gets it own linker
        if self._target_config.get('has-config', False) is True:
            self._linker = '{}.ld'.format(os.path.join(self._target, self._config))
        else:  # otherwise, it has a single linker in the common directory
            self._linker = f'{self._target}.ld'

        linker_path = os.path.abspath(os.path.join(__file__, '..', self._linker_dir, self._linker))
        if not os.path.isfile(linker_path):
            raise FileNotFoundError(f'Linker script not found: {linker_path}')

    def _populate_options(self) -> None:
        self._options: Dict[str, List[str]] = {
            'c_flags': [],
            'ld_flags': [],
            'include_files': [],
        }

        # populate c_flags and ld_flags
        for config in (self._target_config, self._family_config):
            for option in ('c_flags', 'ld_flags'):
                self._options[option] += config.get(option, [])
                try:
                    self._options[option] += config[self._build_mode][option]
                except KeyError:
                    pass

        # target has a config
        if self._target_config.get('has-config', False) is True:
            if not self._config:
                raise ValueError('Was expecting a target config but none specified')
            self._options['include_files'] += [
                os.path.join('targets', self._target, 'config', f'{self._config}.h')
            ]

    def _populate_vendor_options(self) -> None:
        self._options['c_flags'] += [
            fr'-DOI_VENDOR=\"{self._vendor}\"',
            r'-DOI_VERSION=\"{}\"'.format(
                f'{self.version}.dirty' if self._is_git_dirty() else self.version
            ),
        ]

    def _validate_toolchain(self) -> None:
        if self._toolchain is not None:  # override toolchain
            warnings.warn('Overriding target toolchain, may not be compatible!')
        else:  # use the toolchain defined by the target
            self._toolchain = self._target_config.get(
                'toolchain',
                self._family_config.get('toolchain'),
            )

        if self._toolchain and self._toolchain.endswith('-'):
            warnings.warn(
                f'Specified `{self._toolchain}` as the cross toolchain, '
                f'did you mean `{self._toolchain[:-1]}`?'
            )
        for tool in self._REQUIRED_TOOLS:
            name = '-'.join(filter(None, [self._toolchain, tool]))
            if shutil.which(name) is None:
                _error(f'Invalid toolchain: {name} not found')

    def _calculate_extensions(self) -> None:
        if not self._toolchain:  # native
            self._bin_extension = 'exe' if os.name == 'nt' else ''
            self._generate_bin = False
            self._generate_hex = False
        else:
            self._bin_extension = 'elf'
            self._generate_bin = True
            self._generate_hex = True

    def _populate_dependencies(self) -> None:
        self._dependencies: Dict[str, build_system.dependencies.Dependency] = {}

        dependencies = self._family_config.get('dependencies', {})
        dependencies.update(
            self._target_config.get('dependencies', {})
        )

        try:
            for name, kwargs in dependencies.items():
                cls = build_system.dependencies.Dependency.class_from_name(name)
                if not self._no_fetch:
                    cls.fetch_submodule()
                self._dependencies[name] = cls(**kwargs)
        except TypeError as e:
            raise BuildError(f'Failed to initialize depedency `{name}`: {str(e)}')

    def _ninja_write_header(self, nw: build_system.ninja.Writer) -> None:
        nw.comment(f'build file automatically generated by {self._this_file_name}, do not edit manually!')
        nw.newline()
        nw.variable('ninja_required_version', '1.3')
        nw.newline()

    def _ninja_write_variables(self, nw: build_system.ninja.Writer) -> None:
        linker_args = [
            '-L{}'.format(os.path.join('$root', self._linker_dir)),
            f'-T{self._linker}',
        ] if self._linker else []

        nw.comment('variables')
        nw.newline()
        nw.variable('root', self._root)
        nw.variable('builddir', self._builddir)
        nw.variable('cc', nw.tool('gcc'))
        nw.variable('ar', nw.tool('ar'))
        nw.variable('objcopy', nw.tool('objcopy'))
        nw.variable('size', nw.tool('size'))
        nw.variable('c_flags', self._options['c_flags'])
        nw.variable('c_include_flags', ' '.join([
            f'-I{nw.src_dir}',
        ] + [
            f'-include {nw.src(path)}' for path in self._options['include_files']
        ] + [
            f'-I{nw.root(path)}'
            for dependency in self._dependencies.values()
            for path in dependency.external_include
        ]))
        nw.variable('ld_flags', self._options['ld_flags'] + linker_args)
        nw.newline()

    def _ninja_write_rules(self, nw: build_system.ninja.Writer) -> None:
        nw.comment('rules')
        nw.newline()
        nw.rule(
            'cc',
            command='$cc -MMD -MT $out -MF $out.d $c_flags $c_include_flags -c $in -o $out',
            depfile='$out.d',
            deps='gcc',
            description='CC $out',
        )
        nw.newline()
        nw.rule(
            'ar',
            command='rm -f $out && $ar crs $out $in',
            description='AR $out',
        )
        nw.newline()
        nw.rule(
            'link',
            command='$cc -o $out $in $ld_flags',
            description='LINK $out',
        )
        nw.newline()

        if self._generate_bin:
            nw.rule(
                'bin',
                command='$objcopy -O binary $in $out',
                description='BIN $out',
            )
            nw.newline()

        if self._generate_hex:
            nw.rule(
                'hex',
                command='$objcopy -O ihex $in $out',
                description='HEX $out',
            )
            nw.newline()

    def write_ninja(self, file: str = 'build.ninja') -> None:  # noqa: C901
        with open(file, 'w') as f:
            nw = build_system.ninja.Writer(f, toolchain=self._toolchain, width=160)

            self._ninja_write_header(nw)
            self._ninja_write_variables(nw)
            self._ninja_write_rules(nw)

            objs: List[str] = []

            # optional config argument
            config: Optional[str] = None
            if self._config:
                config = nw.src('targets', self._target, 'config', f'{self._config}.h')

            # build dependencies
            for name, dep in self._dependencies.items():
                objs += dep.write_ninja(
                    nw,
                    self._dependencies,
                    nw.src('targets', self._target),
                    config,
                )

            # build our source
            nw.comment('target objects')
            nw.newline()
            for file in self._source:
                objs += nw.cc(file)
            nw.newline()

            # build output objects
            nw.comment('target')
            nw.newline()
            out_name = '-'.join(filter(None, [
                'openinput',
                self._target,
                self.version.replace('.', '-'),
                'dirty' if self._is_git_dirty else None,
            ]))
            out = nw.extension(out_name, self._bin_extension)
            nw.build(out, 'link', objs)
            nw.newline()

            if self._generate_bin:
                nw.build(nw.extension(out_name, 'bin'), 'bin', out)
                nw.newline()
            if self._generate_hex:
                nw.build(nw.extension(out_name, 'hex'), 'hex', out)
                nw.newline()

    def _is_git_dirty(self) -> Optional[bool]:
        try:
            return bool(subprocess.check_output(['git', 'diff', '--stat']).decode().strip())
        except FileNotFoundError:
            return None

    @functools.cached_property
    def version(self) -> str:
        try:
            tag_commit = subprocess.check_output(['git', 'rev-list', '--tags', '--max-count=1']).decode().strip()
            if tag_commit:
                # if there is a tag, use git describe
                return subprocess.check_output(['git', 'describe']).decode().strip()
            # fallback to r{commit count}.{shortened commit id}
            return 'r{}.{}'.format(
                subprocess.check_output(['git', 'rev-list', '--count', 'HEAD']).decode().strip(),
                subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode().strip(),
            )
        except FileNotFoundError:
            return 'UNKNOWN'

    def print_summary(self) -> None:
        print(
            f'openinput {_CYAN}{self.version}{_RESET}' +
            (f' {_RED}(dirty){_RESET}' if self._is_git_dirty() else ''),
            end='\n\n'
        )

        for name, var in {
            'target': self._target,
            'toolchain': self._toolchain or 'native',
            'c_flags': ' '.join(self._options['c_flags']) or '(empty)',
            'ld_flags': ' '.join(self._options['ld_flags']) or '(empty)',
            'dependencies': ' '.join([dep for dep in self._dependencies]) or None
        }.items():
            if var:
                print('{:>24}: {}'.format(name, var))

        for name, entries in {
            'source': self._source,
            'include_files': self._options['include_files'],
        }.items():
            print('{:>24}:'.format(name))
            if not entries:
                print(' ' * 26 + '(empty)')
            for entry in entries:
                print(' ' * 26 + entry)

def _ask_target() -> str:
    print('Available targets:')
    for i, available_target in enumerate(TARGETS):
        print(f'{available_target:>32} ({i})')
    while True:
        select = input('Select target (default=linux-uhid): ')
        if not select:
            target = 'linux-uhid'
            break
        try:
            target = TARGETS[int(select)]
            break
        except (ValueError, IndexError):
            print('Invalid option!')
    print()
    return target

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--builddir',
        '-b',
        type=str,
        default='build',
        help='build directory',
    )
    parser.add_argument(
        '--toolchain',
        '-t',
        type=str,
        help='override toolchain prefix (eg. arm-none-eabi)',
    )
    parser.add_argument(
        '--debug',
        '-d',
        action='store_true',
        help='output extra debug information',
    )
    parser.add_argument(
        '--no-fetch',
        '-n',
        action='store_true',
        help="don't fetch dependency git submodules",
    )
    target_subparsers = parser.add_subparsers(
        dest='target',
        help='target firmware',
        metavar='TARGET',
    )

    # register targets and thier arguments
    for target in TARGETS:
        target_parser = target_subparsers.add_parser(target)
        if target in TARGET_CONFIGS:
            target_parser.add_argument(
                '--config',
                '-c',
                type=str,
                metavar='CONFIG',
                choices=TARGET_CONFIGS[target],
                help='device configuration name',
                required=True,
            )

    args = parser.parse_args()

    if not args.target:
        # ask for target if it was not specified
        args = parser.parse_args([_ask_target()])

    try:
        builder = BuildSystemBuilder(**vars(args))
        builder.print_summary()
        builder.write_ninja()
        print("\nbuild.ninja written! Call 'ninja' to compile...")
    except Exception as e:
        print()
        print(_DIM + traceback.format_exc() + _RESET)
        _error(str(e))


import pandas as pd
columns=['SepalLength','SepalWidth', 'PetalLength', 'PetalWidth' , 'Species']
iris=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", names=columns)

df=iris.copy()

# print(df.head)

# df.columns=['SepalLength','SepalWidth', 'PetalLength', 'PetalWidth' , 'Species']

# print(df.head)

df_virginica=df[df['Species']=='Iris-virginica']
df_virginica=df_virginica[df_virginica['PetalLength']>1.5]
rows,col=(df_virginica.shape)
#a will print list of values
# a=df_virginica.values

for i in range(rows):
    output=(df_virginica.iloc[i])
    # print(type(output))
    print(output.iloc[0],output.iloc[1],output.iloc[2],output.iloc[3],output.iloc[4])


# -*- coding: utf-8 -*-
#Modulos para la segunda parte del proyecto de programación

import opciones_menu
import robusta_entrega

class Cuerpo:

	def __init__(self, nom, mas, x , y, img, fijo, vx, vy):

		self.nombre = nom
		self.masa = mas
		self.px = x
		self.py = y
		self.imagen = img
		self.fijo = fijo
		self.velocidad_x = vx
		self.velocidad_y = vy

	def imprimir(self):

		print("Nombre : %s , Masa: %s , Posición X: %s , Posición Y: %s , Imagen: %s , Cuerpo Fijo: %s , Velocidad X: %s , Velocidad Y: %s " %(self.nombre, self.masa, self.px, self.py, self.imagen, self.fijo, self.velocidad_x, self.velocidad_y))

	def imprimir_nombre(self):
		print(str(self.nombre))

def leer(Cuerpo):

	fichero = robusta_fichero()
	lista_cuerpos = cargar_cuerpos(fichero, Cuerpo)
	return lista_cuerpos

def robusta_fichero():

	dato_valido = False

	while not dato_valido:

		try:
			direccion = input("Introduce la dirección del fichero:\n")
			fichero = open(direccion)
			dato_valido = True

		except FileNotFoundError:
			print("### ERROR ### La dirección introducida no es correcta.")

		except PermissionError:
			print("### ERROR ### No tienes permiso para abrir este fichero.")

	return fichero

def cargar_cuerpos(fichero,Cuerpo):

	lista_cuerpos = []
	palabra_actual = ""

	for linea in fichero:

		for c in linea:

			if c == "," or c == ".":
				valor = palabra_actual
				palabra_actual = ""

				if etiqueta == "nombre" or etiqueta == "Nombre":
					nombre = valor
				if etiqueta == "masa" or etiqueta == "Masa":
					masa = valor
				if etiqueta == "x":
					px = valor
				if etiqueta == "y":
					py = valor
				if etiqueta == "imagen" or etiqueta == "Imagen":
					imagen = valor
				if etiqueta == "fijo" or etiqueta == "Fijo":
					fijo = valor
				if etiqueta == "vx":
					velocidad_x = valor
				if etiqueta == "vy":
					velocidad_y = valor

			elif c ==":":
				etiqueta = palabra_actual
				palabra_actual = ""

			elif c == " ":
				pass

			else:
				palabra_actual += c

		cuerpo_actual = Cuerpo(nombre, masa, px, py, imagen, fijo, velocidad_x, velocidad_y)
		lista_cuerpos.append(cuerpo_actual)
		palabra_actual = ""

	return lista_cuerpos

def agregar_cuerpos(lista_cuerpos, Cuerpo):
	mas_cuerpos = True
	while mas_cuerpos:
		num_cuerpos = robusta_entrega.entrada_cuerpos()
		print("")

		for n in range(num_cuerpos):

			nombre = robusta_entrega.norepetirnombre(lista_cuerpos)

			masa = robusta_entrega.entrada_enteros("masa")
			px = robusta_entrega.entrada_enteros("posición x")
			py = robusta_entrega.entrada_enteros("posición y")
			imagen = input("Introduce la ruta de la imagen: ")
			fijo = robusta_entrega.entrada_sino()
			vx = robusta_entrega.entrada_enteros("velocidad x")
			vy = robusta_entrega.entrada_enteros("velocidad y")

			cuerpo_nuevo = Cuerpo(nombre, masa, px, py, imagen, fijo, vx, vy)
			lista_cuerpos.append(cuerpo_nuevo)

		entrada_valida = False

		while not entrada_valida:

			respuesta = input("\n\n¿Deseas añadir más cuerpos? (si/no): ")
			print("\n")
			respuesta= respuesta.lower()

			if respuesta == "no" or respuesta  == "si":

				if respuesta == "no":
					mas_cuerpos = False

				entrada_valida = True

			else:
				print("La respuesta introducida no es valida.")

	return lista_cuerpos

def eliminar_cuerpo(lista_cuerpos, Cuerpo):

	salir = False
	contador = 1

	print("\n")
	while not salir:

		for c in lista_cuerpos:

			try:
				print("\t", end="")
				print(contador, end="")
				print(". ", end="")

				c.imprimir_nombre()
				contador += 1

			except:
				pass

		print("\n\tQ/q - salir")
		print("--------------------------------------")
		respuesta = input(" Selecciona el cuerpo a eliminar[1-%d]: " %(len(lista_cuerpos)))
		print("--------------------------------------")

		try:
			respuesta = int(respuesta)

			if respuesta>=1 and respuesta<=len(lista_cuerpos):
				salir = True
				del lista_cuerpos[(respuesta-1)]
				print("\n\t# Cuerpo eliminado con exito. #")

			else:
				print("\n### ERROR ### Seleccione un cuerpo de la lista o introduzca \"Q\" para salir.\n")
				contador=1

		except ValueError:
			if respuesta == "q" or respuesta == "Q":
				salir = True

			else:
				print("\n### ERROR ### Seleccione un cuerpo de la lista o introduzca \"Q\" para salir.\n")
				contador=1

def seleccionar_modificacion(lista_cuerpos, Cuerpo):

	if lista_cuerpos == []:
		print("\n# ERROR # No hay ningun cuerpo cargado.")

	else:
		fin = False

		while not fin:
			salir = False
			contador = 1

			print("\n")
			while not salir:

				for c in lista_cuerpos:

					try:
						print("\t", end="")
						print(contador, end="")
						print(". ", end="")

						c.imprimir_nombre()
						contador += 1

					except:
						pass

				print("\n\tQ/q - salir")
				print("--------------------------------------")
				respuesta = input(" Selecciona el cuerpo a modificar[1-%d]: " %(len(lista_cuerpos)))
				print("--------------------------------------")

				try:
					respuesta = int(respuesta)

					if respuesta>=1 and respuesta<=len(lista_cuerpos):
						salir = True
						c = lista_cuerpos[(respuesta-1)]
						c = modificar(c)

						print("\n\t# Cuerpo modificado con exito #")
						print("--------------------------------------")

					else:
						print("\n### ERROR ### Seleccione un cuerpo de la lista o introduzca \"Q\" para salir.\n")
						contador=1

				except ValueError:
					if respuesta == "q" or respuesta == "Q":
						salir = True
						fin = True

					else:
						print("\n### ERROR ### Seleccione un cuerpo de la lista o introduzca \"Q\" para salir.\n")
						contador=1

def modificar(c):

	dato_valido = False
	while not dato_valido:

		c.imprimir()
		dato_viejo = input("Selecione el parametroa modificar:  ")
		dato_viejo = dato_viejo.lower()

		if dato_viejo == "nombre":
			dato_nuevo = input("Introduce el nuevo nombre:  ")
			c.nombre = dato_nuevo
			dato_valido = True

		elif dato_viejo == "masa":
			while not dato_valido:
				dato_nuevo = input("Introduce la nueva masa:  ")
				dato_valido = robusta_entrega.robusta_modificaciones_int(dato_nuevo)
				c.masa = dato_nuevo

		elif dato_viejo == "posicion x" or dato_viejo == "posicionx":
			while not dato_valido:
				dato_nuevo = input("Introduce la nueva posicion en el eje x:  ")
				dato_valido = robusta_entrega.robusta_modificaciones_int(dato_nuevo)
				c.px = dato_nuevo

		elif dato_viejo == "posicion y" or dato_viejo == "posiciony":
			while not dato_valido:
				dato_nuevo = input("Introduce la nueva posicion en el eje y:  ")
				dato_valido = robusta_entrega.robusta_modificaciones_int(dato_nuevo)
				c.py = dato_nuevo

		elif dato_viejo == "imagen":
				dato_nuevo = input("Introduce la ruta de nueva imagen:  ")
				c.imagen = dato_nuevo
				dato_valido = True

		elif dato_viejo == "cuerpo fijo":
				dato_nuevo = input("Introduce el nuevo estado[si/no]:  ")
				c.nombre = dato_nuevo
				dato_valido = True

		elif dato_viejo == "velocidad x" or dato_viejo == "velocidadx":
			while not dato_valido:
				dato_nuevo = input("Introduce la nueva velocidad en el eje x:  ")
				dato_valido = robusta_entrega.robusta_modificaciones_int(dato_nuevo)
				c.velocidad_x = dato_nuevo

		elif dato_viejo == "velocida y" or dato_viejo == "velociday":
			while not dato_valido:
				dato_nuevo = input("Introduce la nueva velocidad en el eje y:  ")
				dato_valido = robusta_entrega.robusta_modificaciones_int(dato_nuevo)
				c.velocidad_y = dato_nuevo

		else:
			print("\n# ERROR # El parametro introducido no es correcto.\n ")

	return c

def guardar(lista_cuerpos):

	if lista_cuerpos == []:
		print("\n# ERROR # No hay ningun cuerpo cargado.")

	else:

		fichero = robusta_entrega.fichero_w()

		datos_salida = ""
		n = 0

		for e in lista_cuerpos:

			datos_salida = datos_salida + "Nombre: " + e.nombre +", Masa: " + str(e.masa) + ", x: " + str(e.px) + ", y: " + str(e.py) + ", imagen: " + str(e.imagen) + ", fijo: " + str(e.fijo) + ", vx: " + str(e.velocidad_x) + ", vy: " + str(e.velocidad_y) + ".\n"

		fichero.write(datos_salida)
		print("\n\t# Fichero guardado con exito #")
		fichero.close()


import traceback
import queue
from pathlib import Path
import cv2

import sys
import argparse
import os

import numpy as np
import depthai as dai
import time
from threading import Thread

depthAiImg = None

debug=True

useOAKDCam=False
threadStarted = False
t = None

unconsumedFrameCount = 0

from pynput.keyboard import Key, Listener

diff = 0

def on_press(k):
    global diff,t
    if str(k)[1] == '=':
         if diff <= -10:
              diff=diff+10
    elif str(k)[1] == '-':
         diff=diff-10
    elif str(k)[1] == 'q':
         t.stop()
    print('key', k, 'diff', diff)

listener = Listener(
    on_press=on_press)
listener.start()

def create_rgb_cam_pipeline():
    print("Creating pipeline: RGB CAM -> XLINK OUT")
    pipeline = dai.Pipeline()

    cam          = pipeline.createColorCamera()
    # xout_preview = pipeline.createXLinkOut()
    xout_video   = pipeline.createXLinkOut()

    # cam.setPreviewSize(540, 540)
    cam.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)
    cam.setInterleaved(False)
    cam.setBoardSocket(dai.CameraBoardSocket.RGB)

    # xout_preview.setStreamName('rgb_preview')
    xout_video  .setStreamName('rgb')

    # cam.preview.link(xout_preview.input)
    cam.video  .link(xout_video.input)

    streams = ['rgb'] #['rgb_preview', 'rgb_video']

    return pipeline, streams

def create_mono_cam_pipeline():
    print("Creating pipeline: MONO CAMS -> XLINK OUT")
    pipeline = dai.Pipeline()

    cam_left   = pipeline.createMonoCamera()
    cam_right  = pipeline.createMonoCamera()
    xout_left  = pipeline.createXLinkOut()
    xout_right = pipeline.createXLinkOut()

    cam_left .setBoardSocket(dai.CameraBoardSocket.LEFT)
    cam_right.setBoardSocket(dai.CameraBoardSocket.RIGHT)
    for cam in [cam_left, cam_right]: # Common config
        cam.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)
        #cam.setFps(20.0)

    xout_left .setStreamName('left')
    xout_right.setStreamName('right')

    cam_left .out.link(xout_left.input)
    cam_right.out.link(xout_right.input)

    streams = ['left', 'right']

    return pipeline, streams

def test_pipeline(a,b,c):
    global depthAiImg, diff, unconsumedFrameCount
    # global clientsocket
    # print("a,b,transform",a,b,transform)
    transform=a+b+c
    if transform == 'rgb':
        pipeline, streams = create_rgb_cam_pipeline()
    else:
        pipeline, streams = create_mono_cam_pipeline()
    # pipeline, streams = create_stereo_depth_pipeline(source_camera)

    print("Creating DepthAI device")
    with dai.Device(pipeline) as device:
        print("Starting pipeline")
        device.startPipeline()

        in_streams = []
        # if not source_camera:
        #     # Reversed order trick:
        #     # The sync stage on device side has a timeout between receiving left
        #     # and right frames. In case a delay would occur on host between sending
        #     # left and right, the timeout will get triggered.
        #     # We make sure to send first the right frame, then left.
        #     in_streams.extend(['in_right', 'in_left'])
        in_q_list = []
        inStreamsCameraID = []
        for s in in_streams:
            q = device.getInputQueue(s)
            in_q_list.append(q)
            inStreamsCameraID = [dai.CameraBoardSocket.RIGHT, dai.CameraBoardSocket.LEFT]

        # Create a receive queue for each stream
        q_list = []
        for s in streams:
            print("stream found",s)
            #if s in ['disparity']:
                #print("stream added",s)
            q = device.getOutputQueue(s, 8, blocking=True)
            q_list.append(q)

        # Need to set a timestamp for input frames, for the sync stage in Stereo node
        timestamp_ms = 0
        index = 0

        img = None
        frameCount=0
        prevFrameCount=0
        prevTime = time.time()

        imgs = {}
        imgs['rgb'] = None
        imgs['left'] = None
        imgs['right'] = None
        imgs['disparity'] = None

        black = np.zeros((960,2560), dtype = "uint8")
        h,w = black.shape
        #diff = 0
        while True:
            if unconsumedFrameCount>120: #stop if no client consuming
                break
            for q in q_list:
                name  = q.getName()
                if name in ['rgb']:
                    image = q.get()
                    frame = image.getCvFrame()
                    depthAiImg = frame
                    # depthAiImg = cv2.resize(depthAiImg,(1440,))
                    # depthAiImg = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

                elif name in ['left', 'right']:
                    image = q.get()
                    frame = image.getCvFrame()
                    imgs[name] = frame
                    if imgs['left'] is not None and imgs['right'] is not None:
                        # temp = np.concatenate((imgs['left'], imgs['right']), axis = 1)
                        # black[119:(h-120-1), 0:w] = temp
                        # depthAiImg = black
                        # depthAiImg = cv2.cvtColor(depthAiImg,cv2.COLOR_GRAY2RGB)

                        green_channel = imgs['left']
                        red_channel = imgs['right']
                        #red_channel = imgs['left']
                        #green_channel = imgs['right']

                        ih,iw = red_channel.shape
                        # print(h,w, ih,iw)
                        # temp = np.concatenate((green_channel,red_channel), axis = 1)
                        # h,w = black.shape

                        #diff = -40 #change this to fit your Phone and VR headset size

                        black[h//2-ih//2 : h//2 + ih//2, w//2 - iw - diff : w//2 - diff] = green_channel #red_channel #green_channel
                        black[h//2-ih//2 : h//2 + ih//2, w//2 + diff : w//2 + iw + diff] = red_channel
                        # black[119:(h-121), 119:w-121] = temp
                        depthAiImg = black
                        # depthAiImg = cv2.resize(depthAiImg,(iw//2,ih//2))
                        depthAiImg = cv2.cvtColor(depthAiImg,cv2.COLOR_GRAY2RGB)

                        imgs['left'] = None
                        imgs['right'] = None

            k = cv2.waitKey(1)
            if k == ord('q'):
                break
            frameCount+=1
            unconsumedFrameCount=unconsumedFrameCount+1
            delta = time.time() - prevTime
            if delta > 1:
                realFPS = (frameCount-prevFrameCount)/delta
                print("realFps",realFPS,'diff',diff)
                if depthAiImg is not None:
                    # cv2.imshow('depthAiImg', depthAiImg)
                    print("depthAiImg.shape",depthAiImg.shape)
                prevFrameCount = frameCount
                prevTime = time.time()

def init_model(transform):
    global newTransform
    # print('init_model',transform)
    if transform in ['rgb', 'sbs']:
        return None, None
    return None, None

def process_image(transform,processing_model,img):
    global useOAKDCam, depthAiImg, threadStarted, t, unconsumedFrameCount
    # print('process_image',transform)
    tracks = []
    try:
        frame = img
        if depthAiImg is not None and transform in ['rgb', 'sbs']:
            unconsumedFrameCount=unconsumedFrameCount-1
            img = depthAiImg
        if not threadStarted:
            threadStarted = True
            try:
                t = Thread(target=test_pipeline, args=(str(transform)))
                t.start()
            except Exception as e:
                print(e)

    except Exception as e:
        track = traceback.format_exc()
        print(track)
        print("DepthAI Exception",e)
        pass

    return tracks,img


import numpy as np

class ID3Algorithm:
    eps = np.finfo(float).eps
    tree = None
    unknown = 0

    '''
    @:param target: the name of the csv field we want to classify. Ex: 'Accident Level'
    '''
    def __init__(self, target):
        self.target = target

    def entropy(self, data):
        entropy_calc = 0
        values = data[self.target].unique()
        for item in values:
            frac = data[self.target].value_counts()[item] / len(data[self.target])
            entropy_calc -= frac * np.log(frac)

        return entropy_calc

    def entropy_of_attribute(self, attribute, data):
        target_unique = data[self.target].unique()
        variables_unique = data[attribute].unique()
        entropy_calc = 0

        for item in variables_unique:
            entropy_aux = 0
            denominator = 0
            for target_item in target_unique:
                numerator = len(data[attribute][data[attribute] == item][data[self.target] == target_item])
                denominator = len(data[attribute][data[attribute] == item])

                frac = numerator / (denominator + self.eps)
                entropy_aux -= frac * np.log(frac + self.eps)

            frac_aux = denominator / len(data)
            entropy_calc -= frac_aux * entropy_aux

        return abs(entropy_calc)

    def gain_of_attribute(self, attribute, data):
        return self.entropy(data) - self.entropy_of_attribute(attribute, data)

    def gain_list(self, data):
        gain_dict = {}
        for key in data.keys():
            if key != self.target:
                information_gain = self.gain_of_attribute(key, data)
                gain_dict[key] = information_gain

        return sorted(gain_dict.items(), key=lambda x: x[1], reverse=False)

    def _predict(self, input, tree):
        if isinstance(tree, str):
            return tree
        attr = list(tree.keys())[0]
        val = input[attr]
        tree = tree[attr]
        if val not in tree:
            self.unknown += 1
            return tree['unknown']
        tree = tree[val]
        return self._predict(input, tree)

    def predict(self, input):
        return self._predict(input, self.tree)

    def find_best(self, data):
        best = -float("inf")
        best_key = None

        for key in data.keys():
            if key != self.target:
                information_gain = self.gain_of_attribute(key, data)
                if best < information_gain:
                    best = information_gain
                    best_key = key

        return best_key

    def drop_attribute(self, attr, value, data):
        return data[data[attr] == value].reset_index(drop=True).drop(columns=[attr])

    def _build_tree(self, data):

        node = self.find_best(data)
        if node is None:
            return data[self.target].mode()[0]

        attrs = np.unique(data[node])
        rtree = {node: {}}
        rtree[node]['unknown'] = data.mode()[self.target][0]

        for item in attrs:
            sub_set = self.drop_attribute(node, item, data)
            values, count = np.unique(sub_set[self.target], return_counts=True)

            if len(count) == 1:
                rtree[node][item] = values[0]
            else:
                rtree[node][item] = self._build_tree(sub_set)

        return rtree

    def build_tree(self, data):
        self.tree = self._build_tree(data)


from tkinter import messagebox
from tkinter import *

from view.base_frame import BaseFrame
from controller.admin_controller import AdminController
from exceptions import Error

class EmailAdminFrame(BaseFrame) :

	def __init__(self, admin_controller : AdminController, main_frame : Frame):
		super().__init__(main_frame)
		self._admin_controller = admin_controller
		self.create_widgets()

	def create_widgets(self):
		self.title=Label(self, text="Send email to adminstrators", height=3)
		self.mail_content = self.create_entry("Mail content : ", row=4, columnspan=10, cursor="arrow", justify="center", selectborderwidth=10)
		self.validate = Button(self, bg="green", fg="white", text="Validate", width=14, height=1, pady=4, padx=10, command=self.validate)

		#If we get all the emails without any problem, it will be possible to then validate and "send an email", else, you can not validate
		try :
			emails = self._admin_controller.get_mail()

			self.list_emails = Text(self, width=40, height=10)

			for i in emails:
				self.list_emails.insert(END, i[0]+'\n')

			self.list_emails.grid(row=2, column=2)

		except Error as e:
			self.validate.config(state=DISABLED)
			messagebox.showerror("Error", str(e))

		self.title.grid(row=1, column=2)
		self.mail_content.grid(row=4, column=2)
		self.validate.grid(row=5, column=3)

	def validate(self):

		mail_content = self.mail_content.get()

		try:
			#SEND EMAIL... (Easter Egg). This part was created to list admins only because send emails to unknown addresses is forbidden (cf. phising next)

			messagebox.showinfo("Success", "Email sent to administrators !")

		except Error as e:
			messagebox.showerror("Error", str(e))
			return

		self.show_menu()


import torch
import torch.nn.functional as F
# torch.backends.cudnn.bencmark = True

import cv2
import numpy as np

from SFD_pytorch.net_s3fd import s3fd
from SFD_pytorch.bbox import nms, decode

net = s3fd()
net.load_state_dict(torch.load('SFD_pytorch/data/s3fd_convert.pth'))
if torch.cuda.is_available():
    net.cuda()
net.eval()

def detect(net,img):
    img = img - np.array([104,117,123])
    img = img.transpose(2, 0, 1)
    img = img.reshape((1,)+img.shape)

    img = torch.from_numpy(img).float().cuda()
    olist = net(img)

    bboxlist = []
    for i in range(len(olist)//2):
        #print(olist[i*2])
        olist[i*2] = F.softmax(olist[i*2], dim=1)
    for i in range(len(olist)//2):
        ocls,oreg = olist[i*2].data.cpu(),olist[i*2+1].data.cpu()
        _, _, FH, FW = ocls.size() # feature map size
        stride = 2**(i+2)    # 4,8,16,32,64,128
        for Findex in range(FH*FW):
            windex,hindex = Findex%FW,Findex//FW
            axc,ayc = stride/2+windex*stride,stride/2+hindex*stride
            score = ocls[0,1,hindex,windex]
            loc = oreg[0,:,hindex,windex].contiguous().view(1,4)
            if score<0.05: continue
            priors = torch.Tensor([[axc/1.0,ayc/1.0,stride*4/1.0,stride*4/1.0]])
            variances = [0.1,0.2]
            box = decode(loc,priors,variances)
            x1,y1,x2,y2 = box[0]*1.0
            # cv2.rectangle(imgshow,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1)
            bboxlist.append([x1,y1,x2,y2,score])
    bboxlist = np.array(bboxlist)
    if 0==len(bboxlist): bboxlist=np.zeros((1, 5))
    return bboxlist

def flip_detect(net,img):
    img = cv2.flip(img, 1)
    b = detect(net,img)

    bboxlist = np.zeros(b.shape)
    bboxlist[:, 0] = img.shape[1] - b[:, 2]
    bboxlist[:, 1] = b[:, 1]
    bboxlist[:, 2] = img.shape[1] - b[:, 0]
    bboxlist[:, 3] = b[:, 3]
    bboxlist[:, 4] = b[:, 4]
    return bboxlist

def scale_detect(net,img,scale=2.0,facesize=None):
    img = cv2.resize(img,(0,0),fx=scale,fy=scale)
    b = detect(net,img)

    bboxlist = np.zeros(b.shape)
    bboxlist[:, 0] = b[:, 0]/scale
    bboxlist[:, 1] = b[:, 1]/scale
    bboxlist[:, 2] = b[:, 2]/scale
    bboxlist[:, 3] = b[:, 3]/scale
    bboxlist[:, 4] = b[:, 4]
    b = bboxlist
    if scale>1: index = np.where(np.minimum(b[:,2]-b[:,0]+1,b[:,3]-b[:,1]+1)<facesize)[0] # only detect small face
    else: index = np.where(np.maximum(b[:,2]-b[:,0]+1,b[:,3]-b[:,1]+1)>facesize)[0] # only detect large face
    bboxlist = b[index,:]
    if 0==len(bboxlist): bboxlist=np.zeros((1, 5))
    return bboxlist

def detect_and_supress(img):
    resize_ratio = 1.0
    if max(img.shape) > 1080:
        resize_ratio = 1080 / max(img.shape)
        img = cv2.resize(img, (0,0), fx=resize_ratio, fy=resize_ratio)
    bbox1 = detect(net, img)
    bbox2 = flip_detect(net, img)
    bbox3 = np.zeros((1, 5))
    if img.shape[0]*img.shape[1]*4 <= 3000*3000:
        bbox3 = scale_detect(net, img, scale=2, facesize=100)
    bbox4 = scale_detect(net, img, scale=0.5, facesize=100)
    bboxes = np.concatenate((bbox1, bbox2, bbox3, bbox4))
    keep = nms(bboxes, 0.3)[:750]
    bboxes = bboxes[keep]
    bboxes = bboxes[bboxes[:, 4] >= 0.5] # Remove small faces

    bboxes /= resize_ratio

    #im = img.copy()
    #for b in bboxes:
    #    x1,y1,x2,y2,_ = b
    #    cv2.rectangle(im,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1)
    scores = bboxes[:, 4]
    sorted_ix = np.argsort(scores)[::-1]
    bboxes = bboxes[sorted_ix]
    bboxes = bboxes.astype("int")
    return bboxes[:, :4]

if __name__ == "__main__":
    img = cv2.imread("maxresdefault.jpg")
    detect_and_supress(img)


import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

CASES = pd.read_csv('../datasets/cases_2015_2017.csv', header=None)

CASES.columns = ['open', 'type', 'short', 'case', 'subtype']

CASES.loc[CASES.short == 'AGGR UNLIC OP 3', 'type'] = 'UM'
CASES.type = CASES.type.str.strip()
CASES = CASES.loc[CASES.type != '00']
CASES = CASES.loc[CASES.type != '']

# Categorize cases
CASES['case_type'] = ''
CASES.loc[CASES.type.str.contains('[^F]V$'), 'case_type'] = 'Violation'
CASES.loc[CASES.type.str.contains('I$'), 'case_type'] = 'Violation'
CASES.loc[CASES.type.str.contains('M$'), 'case_type'] = 'Misdemeanor'
CASES.loc[CASES.type.str.contains('F[VL]*$'), 'case_type'] = 'Felony'

# Group by case type and date, then count
nb_cases = CASES.groupby(['open', 'case_type']) \
                .agg('size') \
                .unstack() \
                .fillna(0) \
                .reset_index()

nb_cases.columns.name = None
nb_cases['open'] = pd.to_datetime(nb_cases['open'])
nb_cases.set_index('open', inplace=True)

# Set matplotlib style
matplotlib.style.use('bmh')

# Initial plot
# ax variable captures the plot and allows us to manipulate parts of it
ax = nb_cases.groupby(pd.Grouper(freq='Q')) \
             .agg({'Misdemeanor': 'sum',
                   'Felony': 'sum',
                   'Violation': 'sum'}) \
             .plot()

# Adjust the legend by creating a new legend with a frame around it,
# then setting the background color and title
legend = ax.legend(frameon=True)
legend.get_frame().set_facecolor('#FFFFFF')
legend.set_title('Case Type', prop={'size': 12})

# Set more descriptive labels
ax.set_xlabel('Quarter')
ax.set_ylabel('Number of Cases Opened')
ax.set_title('Cases Assigned to NYCDS')

# Add some padding under the title
ttl = ax.title
ttl.set_position([0.5, 1.05])


# coding=utf-8
from xml.etree import ElementTree
from win32com.client import Dispatch
import win32com.client
import os

class easy_excel:
    def __init__(self, filename=None):
        self.xlApp = win32com.client.Dispatch('Excel.Application')
        if filename:
            self.filename = os.getcwd() + "\\" + filename
            print(self.filename)
            self.xlBook = self.xlApp.Workbooks.Open(self.filename)
        else:
            self.xlBook = self.xlApp.Workbooks.Open(filename)
            self.filename = ''

    def save(self, newfilename=None):
        if newfilename:
            self.filename = newfilename
            self.xlBook.SaveAs(newfilename)
        else:
            self.xlBook.Save()

    def close(self):
        self.xlBook.Close(SaveChanges=0)

    def getCell(self, sheet, row, col):
        sht = self.xlBook.Worksheets(sheet)
        return sht.Cell(row, col).Value

    def setCell(self, sheet, row, col, value):
        sht = self.xlBook.Worksheets(sheet)
        sht.Cells(row, col).Value = value
        sht.Cells(row, col).HorizontalAlignment = 3
        sht.Rows(row).WrapText = True

    def mergeCells(self, sheet, row1, col1, row2, col2):
        sht = self.xlBook.Worksheets(sheet)
        sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Merge()

    def setBorder(self, sheet, row, col):
        sht = self.xlBook.Worksheets(sheet)
        sht.Cells(row, col).Borders.LineStyle = 1

    def set_col_width(self, sheet):
        sht = self.xlBook.Worksheets(sheet)
        sht.Columns("D:F").ColumnWidth = 30

xls = easy_excel('resultPrint.xlsx')
xls.setCell('Sheet1', 2, 2, u"编号")
xls.setCell('Sheet1', 2, 3, u"用例名称")
xls.setCell('Sheet1', 2, 4, u"操作步骤")
xls.setCell('Sheet1', 2, 5, u"预期结果")
xls.setCell('Sheet1', 2, 6, u"实际结果")
xls.set_col_width('Sheet1')
dic_temp = {}
root = ElementTree.parse("./resultPrint.xml")
abc = root.getiterator("testsuite")
aa = len(abc)

row_flag = 3
step_num = 0
for nn in abc:
    if nn is not None:
        lst_node = nn.findall("testcase")
        if lst_node is not None:
            num = len(lst_node)
            for case in range(0, num):
                steps = lst_node[case].find("steps")
                if steps is not None:
                    step_num = len(steps)
                else:
                    step_num = 0
                dic_temp['keyword'] = lst_node[case].get("name")
                # if keywords is not None:
                #     dic_temp['keyword'] = keywords[0].attrib["name"]
                # else:
                #     dic_temp['keyword'] = 0
                if step_num != 0:
                    for step in steps:
                        list_temp = []
                        list_temp.append(step[1].text)
                        list_temp.append(step[2].text)
                        dic_temp[step[0].text] = list_temp
                row_start = row_flag
                xls.setCell('Sheet1', row_flag, 2, case + 1)
                xls.setCell('Sheet1', row_flag, 3, dic_temp['keyword'])
                for j in range(1, step_num + 1):
                    xls.setCell('Sheet1', row_flag, 4, dic_temp[str(j)][0])
                    xls.setCell('Sheet1', row_flag, 5, dic_temp[str(j)][1])
                    row_flag += 1
                xls.mergeCells('Sheet1', row_start, 3, row_flag - 1, 3)
                xls.mergeCells('Sheet1', row_start, 2, row_flag - 1, 2)
for row in range(2, row_flag):
    for col in range(2, 7):
        xls.setBorder('Sheet1', row, col)
xls.save()
xls.close()
print('success!')
input("Press any key to continue...")


from tkinter import *
from dipy.viz import fvtk
from dipy.tracking.distances import bundles_distances_mam
from nibabel import trackvis
from dipy.tracking.utils import length
import numpy as np
import nibabel
import os
import vtk.util.colors as colors
import _tkinter
import matplotlib.pyplot as plt
from dipy.tracking.vox2track import streamline_mapping
from dipy.tracking import utils

def loadtrkfile(T_filename, threshold_short_streamlines=10.0):
    """Load tractogram from TRK file and remove short streamlines with
    length below threshold.
    """
    print("Loading %s" % T_filename)
    T, hdr = trackvis.read(T_filename, as_generator=False)
    T = np.array([s[0] for s in T], dtype=np.object)

    return T, hdr

def show_tract(segmented_tract, color):
    ren = fvtk.ren()
    fvtk.add(ren, fvtk.line(segmented_tract.tolist(),colors=color, linewidth=2,opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)

def countstreamlines():
    print("total %s streamlines" % ( len(T_A)))

def showhistogram():
    lengths = list(length(T_A))
    fig_hist, ax = plt.subplots()
    ax.hist(lengths, color='burlywood')
    ax.set_xlabel('Length')
    ax.set_ylabel('Count')
    plt.savefig("F:\Thesis\ss\\201111_uf.right.png")
    plt.show()

def load():
    T_A, hdr = loadtrkfile(T_A_filename, threshold_short_streamlines=threshold_short_streamlines)

if __name__ == '__main__':

    print(__doc__)
    np.random.seed(0)

    T_A_filename = 'F:\Thesis\Resources\\alldata\\201111_uf.right.trk'

    threshold_short_streamlines = 0.0

    color=colors.red
    T_A, hdr = loadtrkfile(T_A_filename, threshold_short_streamlines=threshold_short_streamlines)

    countstreamlines()
    showhistogram()

    tractography,header=trackvis.read(T_A_filename)

    tractography = [streamline[0] for streamline in tractography]

    affine=utils.affine_for_trackvis(voxel_size=np.array([2,2,2]))

    print ("---Number of voxel---")

    print (len(streamline_mapping(T_A,affine=affine).keys()))
    show_tract(T_A, color)


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

import os
import sys
import glob
import json
import linecache
import shutil

import click

base_name = '{0:0{w}d}{1}.{ext}'
dataDir = os.path.join(os.path.dirname(__file__), 'data')

class Problem(object):
    def __init__(self, problem_number):
        self.num = problem_number

    @property
    def filename(self, width=3, extension='py'):
        """Returns filename padded with leading zeros"""
        return base_name.format(self.num, '', w=width, ext=extension)

    def suf_name(self, suffix, width=3, extension='py'):
        """Similar to filename property but takes a suffix argument"""
        suffix = '-' + suffix
        return base_name.format(self.num, suffix, w=width, ext=extension)

    @property
    def glob(self):
        """Returns a sorted glob of files belonging to a given problem"""
        file_glob = glob.glob('{0:03d}*.py'.format(self.num))

        # Sort by filename (excluding the file extension)
        return sorted(file_glob, key=lambda f: os.path.splitext(f)[0])

    @property
    def resources(self):
        """Returns a list of resources related to the problem (or None)"""
        with open(os.path.join(dataDir, 'resources.json')) as data_file:
            data = json.load(data_file)

        problemNum = str(self.num)

        if problemNum in data:
            files = data[problemNum]

            # Ensure a list of files is returned
            return files if isinstance(files, list) else [files]
        else:
            return None

    def copy_resources(self):
        """Copies the relevant resources to a resources subdirectory"""
        if not os.path.isdir('resources'):
            os.mkdir('resources')

        resourcesDir = os.path.join(os.getcwd(), 'resources', '')
        copiedResources = []

        for resource in self.resources:
            src = os.path.join(dataDir, 'resources', resource)
            if os.path.isfile(src):
                shutil.copy(src, resourcesDir)
                copiedResources.append(resource)

        if copiedResources:
            msg = "Copied {0} to {1}.".format(
                ', '.join(copiedResources),
                os.path.relpath(resourcesDir, os.pardir)
            )

            click.secho(msg, fg='green')

    @property
    def solution(self):
        """Returns the answer to a given problem"""
        num = self.num

        solutionFile = os.path.join(dataDir, 'solutions.txt')
        solutionLine = linecache.getline(solutionFile, num)

        try:
            answer = solutionLine.split('. ')[1].strip()
        except IndexError:
            answer = None

        if answer:
            return answer
        else:
            msg = 'Answer for problem %i not found in solutions.txt.' % num
            click.secho(msg, fg='red')
            click.echo('If you have an answer, consider submitting a pull '
                       'request to EulerPy on GitHub.')
            sys.exit(1)

    @property
    def text(self):
        """Parses problems.txt and returns problem text"""
        def _problem_iter(problem_num):
            problemFile = os.path.join(dataDir, 'problems.txt')

            with open(problemFile) as file:
                problemText = False
                lastLine = ''

                for line in file:
                    if line.strip() == 'Problem %i' % problem_num:
                        problemText = True

                    if problemText:
                        if line == lastLine == '\n':
                            break
                        else:
                            yield line[:-1]
                            lastLine = line

        problemLines = [line for line in _problem_iter(self.num)]

        if problemLines:
            # First three lines are the problem number, the divider line,
            # and a newline, so don't include them in the returned string
            return '\n'.join(problemLines[3:])
        else:
            msg = 'Problem %i not found in problems.txt.' % self.num
            click.secho(msg, fg='red')
            click.echo('If this problem exists on Project Euler, consider '
                       'submitting a pull request to EulerPy on GitHub.')
            sys.exit(1)


from ovito.modifiers import CoordinationAnalysisModifier
from ovito.io import import_file, export_file

Beads_range=[x for x in range(10,50,4) if x not in (38,46)] # # # #    monomer's range
Dens_range=[x/100 for x in range(0,81,5) if x>0] # # # #    dens' range
Frac_range=[x/100 for x in range(0,100,25) if x!=0] # # # #    frac' range
inters = ('chain_cm', 'blocos_filicos', 'blocos_fobicos')

def Mods(Fracs, Beads, Denss, Inters):

    for Frac in Fracs:

        frac = int((1-Frac)*10%10)

        print(frac)
        print('')

        for Bead in Beads:

            print(Bead)
            print('')

            for Dens in Denss:
                print(Dens)
                print('')

                for Inter in Inters:
                    print(Inter)
                    print('')

                    File = f'centros_de_massas/{Inter}/f_{frac}-b_{Bead}-d_{Dens}.xyz'
                    path = f'centros_de_massas/{Inter}/rdfs/f-'

                    data = import_file(File)

                    co = ((Bead*1000)/Dens)**(1/3)

                    modifier = CoordinationAnalysisModifier(cutoff = co/2, number_of_bins = 60)

                    data.modifiers.append(modifier)

                    export_file(data, path+str(frac)+"_b-"+str(Bead)+"_d-"+str(Dens)+".txt", "txt/table")

                    print('Done. Next Inter')

                print('Done. Next Dens')

            print('Done. Next Bead')

        print('Done. Next Frac')

    print('')
    print('that\'s all, folks!')

    exit()

Mods(Frac_range, Beads_range, Dens_range, inters)


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3,4]].values

'''
import scipy.cluster.hierarchy as sch

dendrogram = sch.dendrogram(sch.linkage(X,method = 'ward'))
plt.title('Dendrogram')
plt.show()
'''
GreaterClusters = 5

from sklearn.cluster import AgglomerativeClustering

hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')
y_hc = hc.fit_predict(X)

colors = ['g','b','r','c','m','y','k','w']
for i in range(0,GreaterClusters):
	plt.scatter(X[y_hc==i,0],X[y_hc==i,1],s = 15,c = colors[i],label = 'Cluster '+str(i))

plt.title('Clusters of clients')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()


from django.urls import path, re_path

from . import views

app_name = "GuardiasAsignadas_app"

urlpatterns = [
    re_path(r'^asignadas/(?P<userid>[\w]+)/$', views.indexView.as_view(), name = "asignadas"),
    path("meAsignaron", views.meAsignaron, name="meAsignaron")
]


# DLL_test.py

from DLL import DoubleLinkedList

ll = DoubleLinkedList()
ll.add(1)
assert(ll.get(0).data == 1)
ll.add(2)
assert(ll.get(1).data == 2)
ll.add(3)
ll.add(4)

print(str(ll))


from xai.brain.wordbase.nouns._queen import _QUEEN

#calss header
class _QUEENS(_QUEEN, ):
	def __init__(self,):
		_QUEEN.__init__(self)
		self.name = "QUEENS"
		self.specie = 'nouns'
		self.basic = "queen"
		self.jsondata = {}


import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, Mapping, NamedTuple, Sequence, Tuple

from snuba.consumers.types import KafkaMessageMetadata
from snuba.datasets.spans_processor import SpansMessageProcessor
from snuba.processor import InsertBatch

class SpanData(NamedTuple):
    trace_id: str
    span_id: str
    parent_span_id: str
    op: str
    start_timestamp: float
    timestamp: float

    def serialize(self) -> Mapping[str, Any]:
        return {
            "sampled": True,
            "start_timestamp": self.start_timestamp,
            "same_process_as_parent": None,
            "description": "GET /api/0/organizations/sentry/tags/?project=1",
            "timestamp": self.timestamp,
            "parent_span_id": self.parent_span_id,
            "trace_id": self.trace_id,
            "span_id": self.span_id,
            "op": self.op,
            "tags": [["some_tag", "some_val"]],
        }

@dataclass
class SpanEvent:
    event_id: str
    trace_id: str
    span_id: str
    parent_span_id: str
    transaction_name: str
    op: str
    start_timestamp: float
    timestamp: float
    spans: Sequence[SpanData]

    def serialize(self) -> Tuple[int, str, Mapping[str, Any]]:
        return (
            2,
            "insert",
            {
                "datetime": "2019-08-08T22:29:53.917000Z",
                "organization_id": 1,
                "platform": "python",
                "project_id": 1,
                "event_id": self.event_id,
                "message": "/organizations/:orgId/issues/",
                "group_id": None,
                "data": {
                    "event_id": self.event_id,
                    "environment": "prod",
                    "project_id": 1,
                    "release": "34a554c14b68285d8a8eb6c5c4c56dfc1db9a83a",
                    "dist": "",
                    "sdk": {
                        "version": "0.9.0",
                        "name": "sentry-sdk",
                        "packages": [{"version": "0.9.0", "name": "pypi:sentry-sdk"}],
                    },
                    "spans": [s.serialize() for s in self.spans],
                    "platform": "python",
                    "version": "7",
                    "type": "transaction",
                    "retention_days": None,
                    "datetime": "2019-08-08T22:29:53.917000Z",
                    "timestamp": self.timestamp,
                    "start_timestamp": self.start_timestamp,
                    "contexts": {
                        "trace": {
                            "sampled": True,
                            "trace_id": self.trace_id,
                            "op": self.op,
                            "type": "trace",
                            "span_id": self.span_id,
                            "status": "ok",
                            "parent_span_id": self.parent_span_id,
                        },
                    },
                    "tags": [
                        ["sentry:release", "34a554c14b68285d8a8eb6c5c4c56dfc1db9a83a"],
                    ],
                    "user": {"username": "me"},
                    "transaction": self.transaction_name,
                },
            },
        )

    def build_result(self, meta: KafkaMessageMetadata) -> Sequence[Mapping[str, Any]]:
        start_timestamp = datetime.utcfromtimestamp(self.start_timestamp)
        finish_timestamp = datetime.utcfromtimestamp(self.timestamp)
        ret = [
            {
                "deleted": 0,
                "project_id": 1,
                "transaction_id": str(uuid.UUID(self.event_id)),
                "trace_id": str(uuid.UUID(self.trace_id)),
                "transaction_span_id": int(self.span_id, 16),
                "span_id": int(self.span_id, 16),
                "parent_span_id": int(self.parent_span_id, 16),
                "transaction_name": self.transaction_name,
                "op": self.op,
                "status": 0,
                "start_ts": start_timestamp,
                "start_ns": int(start_timestamp.microsecond * 1000),
                "finish_ts": finish_timestamp,
                "finish_ns": int(finish_timestamp.microsecond * 1000),
                "duration_ms": int(
                    (finish_timestamp - start_timestamp).total_seconds() * 1000
                ),
                "retention_days": 90,
            }
        ]

        for s in self.spans:
            span_start_ts = datetime.utcfromtimestamp(s.start_timestamp)
            span_finish_ts = datetime.utcfromtimestamp(s.timestamp)
            ret.append(
                {
                    "deleted": 0,
                    "project_id": 1,
                    "transaction_id": str(uuid.UUID(self.event_id)),
                    "trace_id": str(uuid.UUID(self.trace_id)),
                    "transaction_span_id": int(self.span_id, 16),
                    "span_id": int(s.span_id, 16),
                    "parent_span_id": int(s.parent_span_id, 16),
                    "transaction_name": self.transaction_name,
                    "op": s.op,
                    "status": 2,
                    "start_ts": span_start_ts,
                    "start_ns": int(span_start_ts.microsecond * 1000),
                    "finish_ts": span_finish_ts,
                    "finish_ns": int(span_finish_ts.microsecond * 1000),
                    "duration_ms": int(
                        (span_finish_ts - span_start_ts).total_seconds() * 1000
                    ),
                    "tags.key": ["some_tag"],
                    "tags.value": ["some_val"],
                    "retention_days": 90,
                }
            )
        return ret

def test_span_process() -> None:
    timestamp = datetime.now(tz=timezone.utc) - timedelta(seconds=5)
    start_timestamp = timestamp - timedelta(seconds=4)
    message = SpanEvent(
        event_id="e5e062bf2e1d4afd96fd2f90b6770431",
        trace_id="7400045b25c443b885914600aa83ad04",
        span_id="8841662216cc598b",
        parent_span_id="b76a8ca0b0908a15",
        transaction_name="/organizations/:orgId/issues/",
        op="navigation",
        timestamp=timestamp.timestamp(),
        start_timestamp=start_timestamp.timestamp(),
        spans=[
            SpanData(
                trace_id="7400045b25c443b885914600aa83ad04",
                span_id="b95eff64930fef25",
                parent_span_id="8841662216cc598b",
                op="db",
                start_timestamp=(start_timestamp + timedelta(seconds=1)).timestamp(),
                timestamp=(start_timestamp + timedelta(seconds=2)).timestamp(),
            ),
            SpanData(
                trace_id="7400045b25c443b885914600aa83ad04",
                span_id="9f8e7bbe7bf22e09",
                parent_span_id="b95eff64930fef25",
                op="web",
                start_timestamp=(start_timestamp + timedelta(seconds=2)).timestamp(),
                timestamp=(start_timestamp + timedelta(seconds=3)).timestamp(),
            ),
        ],
    )
    meta = KafkaMessageMetadata(offset=1, partition=2, timestamp=datetime(1970, 1, 1))
    processed = SpansMessageProcessor().process_message(message.serialize(), meta)
    assert isinstance(processed, InsertBatch)
    expected_rows = message.build_result(meta)

    for span, expected in zip(processed.rows, expected_rows):
        assert span == expected


#Nama   : Yusuf anwar
#NIM    : L200170086
#Kelas  : C
#Modul  : 6
#----------------------------------------------------------------------------------------------------------------------

#from Modul_2 import Mahasiswa as Mhs

#kode merge sort
def mergesort(a):
    print("belah ",a)
    length=len(a)
    if length>1:
       mid=length//2
       separuhkiri=a[:mid]
       separuhkanan=a[mid:]

       mergesort(separuhkiri)
       mergesort(separuhkanan)

       i=0
       j=0
       k=0
       while i<len(separuhkiri) and j<len(separuhkanan):
           if separuhkiri[i]<separuhkanan[j]:
               a[k]=separuhkiri[i]
               i+=1
           else:
               a[k]=separuhkanan[j]
               j+=1
           k+=1
       while i<len(separuhkiri):
           a[k]=separuhkiri[i]
           i+=1
           k+=1
       while j<len(separuhkanan):
           a[k]=separuhkanan[j]
           j+=1
           k+=1
    print("gabung ",a)

a=[30,20,10,100,5,2,1,67,43]
mergesort(a)
print(a)