import pygame
from pygame.locals import *
from audio_mixer import *
from background import *
from grid import *
from base import *
from tower import *
from projectile import *
from impact import *
from magic_effects import *
from ennemy import *
from dead_body import *
from game_mouse import *
from menu import *
from selected_object import *
from gold import *
from error_message import *
from spawning_mode import *
from utilitaries import *

#############################
## Main functions
#############################

class Game():
      def __init__(self):

            self.timestep = 0.0
            self.timer = 0.0
            self.best_score = 0.0
            self.previous_best_score = self.best_score

            self.is_running = True

            self.all_mixers = All_mixers()

            self.background = Background()

            loading_progress.value += 10

            self.grid = Grid(self)

            self.show_grid = False

            self.menu = Menu(self)

            self.selected_object = Selected_object()

            loading_progress.value += 10

            self.gold = Gold()

            self.mouse = Game_mouse()

            self.spawning_mode = Spawning_mode(self)

            self.base = Base(self)

            loading_progress.value += 10

            self.all_towers = All_towers()

            loading_progress.value += 10

            self.all_projectiles = All_projectiles()

            loading_progress.value += 10

            self.all_impacts = All_impacts()

            self.all_magic_effects = All_magic_effects(self)

            loading_progress.value += 10

            self.all_ennemies = All_ennemies()

            loading_progress.value += 10

            self.all_dead_bodies = All_dead_bodies()

            loading_progress.value += 10

            self.all_gold_anim = All_gold_anim()

            loading_progress.value += 10

            self.all_error_messages = All_error_message_anim()

            self.object_to_render = []

      def deal_with_mouse(self):
            self.mouse.doing_stuff(self)

      def spawning_ennemies(self):
            self.spawning_mode.spawning_ennemies(self)

      def fight(self):
            for tower in self.all_towers:
                  tower.check_ennemies(self)
                  tower.attack_and_reload(self)
            for ennemy in self.all_ennemies:
                  ennemy.attack(self)
                  ennemy.use_power(self)

      def move_objects(self):
            for ennemy in self.all_ennemies:
                  ennemy.move(self)

            for projectile in self.all_projectiles:
                  projectile.move(self)
                  projectile.check_impact(self)

            for impact in self.all_impacts:
                  impact.explode(self)
                  impact.check_impact(self)

            for effect in self.all_magic_effects:
                  effect.advance(self)
                  effect.check_impact(self)

            for gold_gain in self.all_gold_anim.list:
                  gold_gain.move(self)

            for error_message in self.all_error_messages.list:
                  error_message.move(self)

            self.check_game_over()

      def check_game_over(self):
            for ennemy in self.all_ennemies:
                  if (ennemy.posX>WINDOW_WIDTH):
                        global_status.status = "Game Over"
                        break

      def die(self):
            for ennemy in self.all_ennemies:
                  ennemy.die(self)
            for dead_body in self.all_dead_bodies:
                  dead_body.fall(self)
            for tower in self.all_towers:
                  tower.die()
            for gate in self.base.all_gates:
                  gate.open()

      def render(self,update=True):
            self.object_to_render.append(self.background)
            self.object_to_render.append(self.menu)
            self.object_to_render.append(self.spawning_mode)

            for button in self.menu.all_buttons:
                  self.object_to_render.append(button)

            for button in self.menu.all_options_buttons:
                  self.object_to_render.append(button)

            for asset_background in self.background.all_assets:
                  self.object_to_render.append(asset_background)

            for gate in self.base.all_gates:
                  self.object_to_render.append(gate)

            for tower in self.all_towers:
                  self.object_to_render.append(tower)

            for projectile in self.all_projectiles:
                  self.object_to_render.append(projectile)

            for ennemy in self.all_ennemies:
                  self.object_to_render.append(ennemy)

            for dead_body in self.all_dead_bodies:
                  self.object_to_render.append(dead_body)

            for impact in self.all_impacts:
                  self.object_to_render.append(impact)

            for effect in self.all_magic_effects:
                  self.object_to_render.append(effect)

            for gold_gain in self.all_gold_anim.list:
                  self.object_to_render.append(gold_gain)

            for error_message in self.all_error_messages.list:
                  self.object_to_render.append(error_message)

            self.object_to_render.append(self.gold)

            self.object_to_render.append(self.selected_object)

            if (self.show_grid):
                  for box in self.grid.all_boxes:
                        self.object_to_render.append(box)

            if (global_status.status == "In game"):
                  self.object_to_render.append(self.mouse)

            self.object_to_render.sort(key =lambda object : object.rendering_layer)

            for object in self.object_to_render:
                  object.render()

            if update:
                  pygame.display.update()

            self.object_to_render.clear()

      def advance_time(self):
            self.timer += self.timestep

            self.gold.gold_earn(self)

            #print(CLOCK.get_fps())

      def reset(self):

            self.spawning_mode.reset()

            self.gold.reset()

            self.menu.reset()

            self.base.reset()

            self.all_towers.empty()

            self.all_towers.all_siege_engines.empty()

            self.all_projectiles.empty()

            self.all_impacts.empty()

            self.all_magic_effects.empty()

            self.all_ennemies.empty()

            self.all_dead_bodies.empty()

            self.all_gold_anim.list.clear()

            self.all_error_messages.list.clear()

            for box in self.grid.all_boxes:
                  box.occupied = False

            self.timer = 0.0

            self.previous_best_score = self.best_score

      def get_event(self):
            CLOCK.tick(FPS)
            self.timestep = CLOCK.get_time()

            self.all_events = pygame.event.get()
            for event in self.all_events:
                  if event.type == QUIT:
                        global_status.status = "Quitting"
                  if event.type == KEYDOWN:
                        if ((event.key == K_ESCAPE) or (event.key == K_p)):
                              if (global_status.status == "In game"):
                                    global_status.status = "In pause"
                              elif (global_status.status == "In pause"):
                                    global_status.status = "In game"
                        if ((event.key == K_DELETE) or (event.key == K_x)):
                              if self.selected_object.destroyable:
                                    self.selected_object.obj.destroy(self)
                        if DEV_MODE:
                              if (event.key == K_g):
                                    global_status.status = "Game Over"
                              if (event.key == K_n):
                                    self.gold.amount *= 2
                              if (event.key == K_k):
                                    self.all_ennemies.empty()
                              if (event.key == K_h):
                                    for emy in self.all_ennemies:
                                          emy.hp = 0.0

                              if (event.key == K_1):
                                    self.spawning_mode.spawn(self,GOBLIN_TAG,1)
                              if (event.key == K_2):
                                    self.spawning_mode.spawn(self,OGRE_TAG,1)
                              if (event.key == K_3):
                                    self.spawning_mode.spawn(self,BLUE_NEC_TAG,1)
                              if (event.key == K_4):
                                    self.spawning_mode.spawn(self,RED_NEC_TAG,1)
                              if (event.key == K_5):
                                    self.spawning_mode.spawn(self,GREEN_NEC_TAG,1)
                              if (event.key == K_6):
                                    self.spawning_mode.spawn(self,BLUE_SKEL_TAG,1)
                              if (event.key == K_7):
                                    self.spawning_mode.spawn(self,RED_SKEL_TAG,1)
                              if (event.key == K_8):
                                    self.spawning_mode.spawn(self,GREEN_SKEL_TAG,1)
                              if (event.key == K_9):
                                    self.spawning_mode.spawn(self,KAMIKAZE_TAG,1)
                              if (event.key == K_0):
                                    self.spawning_mode.spawn(self,DRAGON_TAG,1)


import nuevaSolucion as n
from datetime import datetime
# El director de un hotel desea implementar una sistema de administración para saber la disponibilidad y asignación de habitaciones. Para asignar, registra el número de cédula y el nombre de cada cliente a medida que llega al hotel, junto con el número de habitación que ocupa (el antiguo libro de entradas).

# Igualmente cuando un huésped se retira del hotel se actualiza la disponibilidad de las habitaciones, el libro de entradas y el libro de salida.

# El director desea en un momento dado contar con la siguiente información:
# Consultas vigentes por huésped: (1) Individual y (2) total. Las consultas (2) totales pueden ser: (1) Por cédula y (2) por orden de llegada.
# Para cualquiera de las consultas entregar toda la información asociada al huésped.
# Consulta de habitaciones: (1) Lista de habitaciones disponibles y (2) Lista de habitaciones ocupadas.

def guia():
    print("""
    Bienvenido:
    ¿Qué desea realizar?
    1. Añadir huesped
    2. Despedir huesped
    3. Consulta de habitaciones
    4. Salir
    """)
    respuesta = int(
        input("¿ Que desea realizar el dia de hoy ? [Digite un numero entre 1 y 3] "))
    return respuesta

def opcion1():
    print("Okey vamos a añadir huesped")
    nombre = input('Ingrese el nombre del huesped: ')
    cedula = int(input('Ingrese la cedula del huesped: '))
    # Solicitar fecha al usuario
    fecha_str = input("Ingrese una fecha (formato: dd/mm/aaaa): ")
    # Convertir la cadena a un objeto datetime
    fecha = datetime.strptime(fecha_str, "%d/%m/%Y")
    hotel.ingreso_huesped(nombre, cedula, fecha)

def opcion2():
    print('Okey Vamos a despedir huesped')
    nombre = input('Ingrese el nombre del huesped: ')
    cedula = int(input('Ingrese la cedula del huesped: '))
    hotel.salida_huesped(nombre, cedula)

def opcion3():
    print("Situacion actual del Hotel: ")
    hotel.situacion_actual()
hotel = n.Hotel()

opciones = [opcion1, opcion2, opcion3]
opcion = 10
key = True
while key == True:
    opcion = guia()
    if opcion >= 1 and opcion <= 3:
        opciones[opcion - 1]()
    elif opcion == 4:
        key = False
    else:
        print("Opción inválida")


"""Damda Weather's sensor entity."""
from homeassistant.core import callback

from .const import (
    SENSOR_DOMAIN,
    DEVICE_CLASS,
    DEVICE_ICON,
    DEVICE_UNIQUE,
    DEVICE_UNIT,
    NAME,
)
from homeassistant.components.sensor import SensorEntity
from .dweather_device import DWeatherDevice
from .api_dweather import get_api
import logging

_LOGGER = logging.getLogger(__name__)

def log(flag, val):
    """0:debug, 1:info, 2:warning, 3:error."""
    if flag == 0:
        _LOGGER.debug(f"[{NAME}] Sensor > {val}")
    elif flag == 1:
        _LOGGER.info(f"[{NAME}] Sensor > {val}")
    elif flag == 2:
        _LOGGER.warning(f"[{NAME}] Sensor > {val}")
    elif flag == 3:
        _LOGGER.error(f"[{NAME}] Sensor > {val}")

def isfloat(value):
    """Determine string is float."""
    try:
        float(value)
        return True
    except ValueError:
        return False

def isnumber(value):
    """Determine string is number."""
    return (
        value is not None
        and isinstance(value, (str, int, float))
        and (
            isinstance(value, str)
            and (value.isnumeric() or value.isdigit())
            or isfloat(value)
        )
    )

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up sensor for Damda Waether component."""

    @callback
    def async_add_entity(devices=[]):
        """Add sensor from api_dweather."""
        entities = []
        api = get_api(hass, config_entry)
        if api:
            try:
                if len(devices) == 0:
                    devices = api.sensors()
            except Exception:
                devices = []
            for device in devices:
                if DEVICE_UNIQUE not in device:
                    continue
                if not api.search_entity(SENSOR_DOMAIN, device[DEVICE_UNIQUE]):
                    entities.append(DWeatherSensor(device, api))

        if entities:
            async_add_entities(entities)

    api = get_api(hass, config_entry)
    if api:
        api.load(SENSOR_DOMAIN, async_add_entity)

    async_add_entity()

class DWeatherSensor(DWeatherDevice, SensorEntity):
    """Representation of a DamdaWeather sensor."""

    TYPE = SENSOR_DOMAIN

    @property
    def state(self):
        """Return the state of the sensor."""
        state = self.api.get_state(self.unique_id)
        return state

    @property
    def icon(self):
        """Return the icon of the sensor."""
        value = self.api.get_state(self.unique_id, DEVICE_ICON)
        return value

    @property
    def device_class(self):
        """Return the class of the sensor."""
        value = self.api.get_state(self.unique_id, DEVICE_CLASS)
        return value

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this sensor."""
        value = self.api.get_state(self.unique_id, DEVICE_UNIT)
        return value

    @property
    def state_class(self):
        """Type of this sensor state."""
        return "measurement" if isnumber(self.state) else None


import numpy as np
from sklearn.svm import SVC
import pandas as pd
from sklearn.grid_search import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.externals import joblib
import json
from collections import Counter

def getWords(topWordsFile):
    topwords = json.load(topWordsFile)
    wordCounter = Counter()
    for key in topwords.keys():
        for word in topwords[key]:
            wordCounter.update([word[0]])
    return list(wordCounter.keys())

def create_train():
  df = pd.read_csv('data/pre_train.csv')
  X = df.iloc[:, :-1]
  y = df.iloc[:, -1]
  X = X.values
  X = [element[0] for element in X]

  sentiment_encoder = LabelEncoder()
  y = sentiment_encoder.fit_transform(y)
  print(sentiment_encoder.classes_)
  with open('./newTopWords.json') as topWordsFile:
    vocabulary = getWords(topWordsFile)
  tfidf = TfidfVectorizer()

  X = tfidf.fit_transform(X)

  X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.3, random_state=1)

  svm_model = SVC(probability=True, kernel='linear', C=1, class_weight='balanced')

  search_parameters = {
      'degree': [2, 3, 4], 'gamma': (np.arange(0.1, 1.1, 0.1)), 'C': (np.arange(0.1, 1.1, 0.1)), 'kernel': ['linear']
  }
  # model_svm = GridSearchCV(
  #     svm_model, search_parameters, cv=5, scoring='accuracy', n_jobs=8)
  svm_model.fit(X_train, y_train)
  # print(model_svm.best_score_)
  # print(model_svm.best_params_)
  y_pred = svm_model.predict(X_test)
  print(metrics.accuracy_score(y_pred, y_test))
  print("model trained")

  # gnb = MultinomialNB()
  # gnb.fit(X_train, y_train)
  # y_pred = gnb.predict(X_test)
  # print(metrics.accuracy_score(y_pred, y_test))
  joblib.dump(svm_model, 'model_linear_svm_tfidf_w.pkl')

def main():
  create_train()

if __name__ == '__main__':
  main()


import os
import argparse
import subprocess
import shutil
from pathlib import Path

# additional CSS from system locations, we use it if available
EXTRA_CSS = [['/usr/share/javascript/highlight.js/styles/routeros.css', 'highlight.css']]

def daps_build(src_dir, project_name, daps_exe):
    print('Creating HTML with DAPS...')
    sys.stdout.flush()

    build_dir = os.path.join(src_dir, '_docbuild')
    cmd = [daps_exe, 'html', '--clean']
    if project_name:
        cmd.extend(['--name', project_name])

    if os.path.exists(build_dir):
        shutil.rmtree(build_dir)
    os.makedirs(build_dir, exist_ok=True)

    ret = subprocess.call(cmd, cwd=src_dir)
    if ret != 0:
        print('Documentation HTML build failed!')
        sys.exit(6)

    html_out_dir = os.path.join(build_dir, project_name, 'html', project_name)

    # copy the (usually missing) plain SVG project icon
    shutil.copy(
        os.path.join(src_dir, 'images', 'src', 'svg', 'appstream-logo.svg'),
        os.path.join(html_out_dir, 'images'),
    )

    # copy extra CSS if it is available
    for css_fname in EXTRA_CSS:
        if os.path.exists(css_fname[0]):
            shutil.copy(css_fname[0], os.path.join(html_out_dir, 'static', 'css', css_fname[1]))

    return build_dir

def copy_result(build_dir, project_name, dest_dir):
    print('Copying HTML documentation...')
    if os.path.exists(dest_dir):
        shutil.rmtree(dest_dir)

    shutil.copytree(
        os.path.join(build_dir, project_name, 'html', project_name), dest_dir, symlinks=True
    )

def cleanup_build_dir(build_dir):
    print('Cleaning up.')
    if os.path.exists(build_dir):
        shutil.rmtree(build_dir)

def daps_validate(src_dir, daps_exe):
    print('Validating documentation with DAPS...')

    build_dir = os.path.join(src_dir, '_docbuild')
    if os.path.exists(build_dir):
        shutil.rmtree(build_dir)
    os.makedirs(build_dir, exist_ok=True)

    ret = subprocess.call([daps_exe, 'validate'], cwd=src_dir)
    if ret != 0:
        print('Validation failed!')
    cleanup_build_dir(build_dir)
    return ret == 0

def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('--build', action='store_true')
    parser.add_argument('--validate', action='store_true')

    parser.add_argument('--src', action='store')
    parser.add_argument('--builddir', action='store')
    parser.add_argument('--daps', action='store', default='daps')
    parser.add_argument('project', action='store', default='AppStream', nargs='?')

    options = parser.parse_args(args)

    if not options.validate and not options.build:
        print('No action was specified.')
        return 1

    if not options.src:
        print('Source root directory is not defined!')
        return 1

    os.chdir(options.src)

    if options.build:
        # build the HTML files
        build_dir = daps_build(options.src, options.project, options.daps)

        # copy to output HTML folder, overriding all previous contents
        copy_result(build_dir, options.project, os.path.join(options.src, 'html'))

        # remove temporary directory
        cleanup_build_dir(build_dir)

        # make a dummy file so Meson can rebuild documentation on demand
        if options.builddir:
            Path(os.path.join(options.builddir, 'docs_built.stamp')).touch()

        print('Documentation built.')

    elif options.validate:
        # validate the XML
        ret = daps_validate(options.src, options.daps)
        if not ret:
            sys.exit(6)

    return 0

if __name__ == '__main__':
    import sys

    sys.exit(main(sys.argv[1:]))


from azure.cli.testsdk.reverse_dependency import get_dummy_cli
from azext_iot.dps.providers.discovery import DPSDiscovery
from azext_iot.tests.settings import Setting

def test_dps_discovery(provisioned_iot_dps_no_hub_module):
    dps_name = provisioned_iot_dps_no_hub_module["name"]
    dps_rg = provisioned_iot_dps_no_hub_module["resourceGroup"]
    cmd_shell = Setting()
    setattr(cmd_shell, "cli_ctx", get_dummy_cli())
    desired_policy_name = "provisioningserviceowner"
    discovery = DPSDiscovery(cmd_shell)

    resource = discovery.find_resource(resource_name=dps_name)
    assert resource.name == dps_name

    auto_policy = discovery.find_policy(resource_name=dps_name, rg=dps_rg).as_dict()
    assert auto_policy

    # Assumption - Test DPS includes the vanilla provisioningserviceowner policy
    desired_policy = discovery.find_policy(
        resource_name=dps_name, rg=dps_rg, policy_name=desired_policy_name
    ).as_dict()
    assert desired_policy["key_name"] == desired_policy_name

    policies = discovery.get_policies(resource_name=dps_name, rg=dps_rg)
    assert len(policies)

    # Example for leveraging discovery to build cstring for every policy on target DPS
    cstrings = [discovery._build_target(resource=resource, policy=p)["cs"] for p in policies]
    assert len(cstrings)

    sub_dps = discovery.get_resources()
    assert sub_dps

    filtered_sub_dps = [
        dps for dps in sub_dps if dps.as_dict()["name"] == dps_name
    ]
    assert filtered_sub_dps

    rg_dpss = discovery.get_resources(rg=dps_rg)
    assert rg_dpss

    filtered_rg_dpss = [dps for dps in rg_dpss if dps.as_dict()["name"] == dps_name]
    assert filtered_rg_dpss

    assert len(rg_dpss) <= len(sub_dps)

def test_dps_targets(provisioned_iot_dps_no_hub_module):
    dps_name = provisioned_iot_dps_no_hub_module["name"]
    dps_rg = provisioned_iot_dps_no_hub_module["resourceGroup"]
    dps_host_name = provisioned_iot_dps_no_hub_module['dps']['properties']['serviceOperationsHostName']
    cmd_shell = Setting()
    setattr(cmd_shell, "cli_ctx", get_dummy_cli())
    discovery = DPSDiscovery(cmd_shell)

    auto_target = discovery.get_target(resource_name=dps_name)
    assert_target(auto_target, rg=dps_rg)
    connection_string = auto_target["cs"]

    cs_target1 = discovery.get_target_by_cstring(connection_string)
    assert_target(cs_target1, True)

    cs_target2 = discovery.get_target(resource_name=None, login=connection_string)
    assert_target(cs_target2, True)

    cs_target2 = discovery.get_target(resource_name=dps_host_name)
    assert_target(cs_target2, True)

    auto_target = discovery.get_target(resource_name=dps_name, resource_group_name=dps_rg)
    assert_target(auto_target, rg=dps_rg)

    sub_targets = discovery.get_targets()
    [assert_target(tar) for tar in sub_targets]

    rg_targets = discovery.get_targets(resource_group_name=dps_rg)
    [assert_target(tar, rg=dps_rg) for tar in rg_targets]

    assert len(rg_targets) <= len(sub_targets)

def assert_target(target: dict, by_cstring=False, **kwargs):
    assert target["cs"]
    assert target["policy"]
    assert target["primarykey"]
    assert target["entity"]

    if not by_cstring:
        assert target["secondarykey"]
        assert target["subscription"] and target["subscription"] != "unknown"


from __future__ import absolute_import
import os.path
import pytest
from pytest import fixture, yield_fixture
from core.archive import Archive
from core.permission import get_or_add_everybody_rule
from core.database.postgres.permission import AccessRulesetToRule
from core import httpstatus
from web.frontend.filehandlers import fetch_archived, send_image, send_from_webroot
from utils.testing import make_node_public

def test_fetch_archived(req, session, fake_archive, content_node):
    node = content_node
    node.system_attrs[u"archive_path"] = u"testpath"
    node.system_attrs[u"archive_type"] = u"test"
    session.flush()
    req.path = u"/archive/{}".format(node.id)
    assert fake_archive.get_state(node) == Archive.NOT_PRESENT
    fetch_archived(req)
    assert fake_archive.get_state(node) == Archive.PRESENT

@yield_fixture
def req_for_png_image(session, image_png, req):
    req.request_headers["Accept"] = "image/png"
    session.flush()
    req.path = "/image/" + unicode(image_png.id)
    yield req

@yield_fixture
def req_for_svg_image(session, image_svg, req):
    req.request_headers["Accept"] = "image/svg+xml"
    session.flush()
    req.path = "/image/" + unicode(image_svg.id)
    yield req

@fixture
def public_image_png(image_png):
    image = image_png
    make_node_public(image)
    image._generate_image_formats()
    return image

@pytest.mark.slow
@fixture
def public_image_svg(image_svg):
    image = image_svg
    make_node_public(image)
    image._generate_image_formats()
    return image

def assert_image_file_sent(image, mimetype, request, error=None):
    assert error is None
    image_file = image.files.filter_by(filetype=u"image", mimetype=mimetype).scalar()
    assert image_file, u"error in fixture, image file not present: " + mimetype
    assert (image_file.abspath, mimetype) in request.sent_files_with_mimetype

def test_send_image_accept_anything(public_image_png, req_for_png_image):
    image = public_image_png
    req = req_for_png_image
    req.request_headers["Accept"] = "*/*"
    error = send_image(req)
    assert_image_file_sent(image, u"image/png", req, error)

def test_send_image_png(public_image_png, req_for_png_image):
    image = public_image_png
    req = req_for_png_image
    error = send_image(req)
    assert_image_file_sent(image, u"image/png", req, error)

def test_send_image_png_nothing_preferred_by_client(public_image_png, req_for_png_image):
    image = public_image_png
    req = req_for_png_image
    del req.request_headers["Accept"]
    error = send_image(req)
    assert_image_file_sent(image, u"image/png", req, error)

def test_send_image_extension_png(public_image_png, req_for_png_image):
    image = public_image_png
    req = req_for_png_image
    req.path = "/image/" + unicode(image.id) + ".png"
    error = send_image(req)
    assert_image_file_sent(image, u"image/png", req, error)

@pytest.mark.slow
def test_send_image_svg(public_image_svg, req_for_svg_image):
    image = public_image_svg
    req = req_for_svg_image
    error = send_image(req)
    assert_image_file_sent(image, u"image/svg+xml", req, error)

@pytest.mark.slow
def test_send_image_svg_client_anything(public_image_svg, req_for_svg_image):
    image = public_image_svg
    req = req_for_svg_image
    # client accepts everything, Chrome does this, for example
    req.request_headers["Accept"] = "*/*"
    error = send_image(req)
    assert_image_file_sent(image, u"image/png", req, error)

@pytest.mark.slow
def test_send_image_svg_client_anything_server_prefers_png(public_image_svg, req_for_svg_image):
    image = public_image_svg
    req = req_for_svg_image
    req.request_headers["Accept"] = "*/*"
    image.system_attrs["preferred_mimetype"] = u"image/png"
    error = send_image(req)
    assert_image_file_sent(image, u"image/png", req, error)

@pytest.mark.slow
def test_send_image_svg_server_prefers_png(public_image_svg, req_for_svg_image):
    image = public_image_svg
    req = req_for_svg_image
    image.system_attrs["preferred_mimetype"] = u"image/png"
    error = send_image(req)
    # client wants svg, client gets svg, regardless of server's preferred_mimetype setting
    assert_image_file_sent(image, u"image/svg+xml", req, error)

### failure cases

def test_send_image_no_data_access(req_for_png_image):
    req = req_for_png_image
    error = send_image(req)
    assert error == 404

def test_send_image_no_file(image_png, req_for_png_image):
    req = req_for_png_image
    node = image_png
    error = send_image(req)
    make_node_public(node)
    assert error == 404

def test_send_image_accept_wrong(public_image_png, req_for_png_image):
    req = req_for_png_image
    req.request_headers["Accept"] = "animal/lizard"
    error = send_image(req)
    assert error == httpstatus.HTTP_NOT_ACCEPTABLE

def test_send_image_path_wrong(req_for_png_image):
    req = req_for_png_image
    req.path = "/lizard/"
    error = send_image(req)
    assert error == httpstatus.HTTP_BAD_REQUEST

def test_send_image_extension_wrong(public_image_png, req_for_png_image):
    node = public_image_png
    req = req_for_png_image
    req.path = "/image/" + unicode(node.id) + ".cow"
    error = send_image(req)
    assert error == httpstatus.HTTP_NOT_ACCEPTABLE

def test_send_from_webroot(req):
    req.path = "/favicon.ico"
    send_from_webroot(req)
    from core import config
    assert (os.path.join(config.basedir, "web/root", "favicon.ico"), "other") in req.sent_files_with_mimetype


from CameraAndDetector import *
import cv2
import apis
import time

def distance_duck(s):
    return 2421.692084 / s - 8.566887384

def theta_duck(u):
    return -0.00172753493 * u + 0.5294127344

def blob_to_optitrack(blob, x_t, angle):
    u = blob[0]
    s = blob[2]

    dist_to_camera = 0.16 # meters

    dist_to_duck = distance_duck(s) / 100.0 # cm to m
    angle_to_duck = theta_duck(u)

    #print("Duck dist", dist_to_duck)
    #print("Duck angle", angle_to_duck)

    p_duck = np.array([dist_to_duck * np.cos(angle_to_duck) + dist_to_camera, dist_to_duck * np.sin(angle_to_duck)])

    #print("Pos duck in robot frame", pos_duck_in_robot_frame)

    #print(x_t)

    theta = angle

    T = np.array([[np.cos(theta), -np.sin(theta), x_t[0]],
                  [np.sin(theta), np.cos(theta), x_t[1]],
                  [0., 0., 1.]])

    vec = np.array([p_duck[0], p_duck[1], 1.])

    res = np.dot(T, vec)

    return np.array([res[0], res[1]])

class CirclePath:

    def __init__(self, position, factor, radius):
        self.start = time.time()
        self.init, _ = position.get()
        self.factor = factor
        self.radius = radius

    def get_next(self):
        t = time.time() - self.start
        if t / self.factor >= 2. * np.pi:
            return self.init
        return self.radius * np.array([np.sin(t/self.factor) + self.init[0], np.cos(t/self.factor) - 1.0 + self.init[1]])

if __name__ == "__main__":

    camera = Camera(raspberrypi = True)
    robot = apis.LocalRobot()
    position = apis.Position("192.168.0.207", "192.168.0.4", 207)

    try:

        path = CirclePath(position, 3.0, 1.0)

        while True:
            blobs = camera.get_blobs()

            x_t, angle = position.get()

            if blobs is not None:
                for blob in blobs[0, :]:
                    p_d = blob_to_optitrack(blob, x_t, angle)
                    print(p_d[0], p_d[1] ,sep=",")

            x_d = path.get_next()

            K1 = 1000
            K2 = 2000

            dist, desired_angle = apis.dist_and_angle(x_d, x_t)

            v = K1 * dist
            omega = K2 * apis.angle_diff(desired_angle, angle)

            u = np.array([v - omega, v + omega])

            robot.set_motor(u[0], u[0], u[1], u[1])

            time.sleep(0.1)

    except KeyboardInterrupt:
        pass

    robot.shutdown()
    camera.close()
    cv2.destroyAllWindows()


from collections import Mapping
import posixpath

from api_schema_graph import APISchemaGraph
from branch_utility import BranchUtility
from extensions_paths import API, JSON_TEMPLATES
from third_party.json_schema_compiler.model import UnixName

_EXTENSION_API = 'extension_api.json'

# The version where api_features.json is first available.
_API_FEATURES_MIN_VERSION = 28
# The version where permission_ and manifest_features.json are available and
# presented in the current format.
_ORIGINAL_FEATURES_MIN_VERSION = 20
# API schemas are aggregated in extension_api.json up to this version.
_EXTENSION_API_MAX_VERSION = 17
# The earliest version for which we have SVN data.
_SVN_MIN_VERSION = 5

def _GetChannelFromFeatures(api_name, json_fs, filename):
  '''Finds API channel information from the features |filename| within the the
  given |json_fs|. Returns None if channel information for the API cannot be
  located.
  '''
  feature = json_fs.GetFromFile(API + filename).Get().get(api_name)
  if feature is None:
    return None
  if isinstance(feature, Mapping):
    # The channel information exists as a solitary dict.
    return feature.get('channel')
  # The channel information dict is nested within a list for whitelisting
  # purposes. Take the newest channel out of all of the entries.
  return BranchUtility.NewestChannel(entry.get('channel') for entry in feature)

def _GetChannelFromApiFeatures(api_name, json_fs):
  return _GetChannelFromFeatures(api_name, json_fs, '_api_features.json')

def _GetChannelFromManifestFeatures(api_name, json_fs):
  # _manifest_features.json uses unix_style API names.
  api_name = UnixName(api_name)
  return _GetChannelFromFeatures(api_name, json_fs, '_manifest_features.json')

def _GetChannelFromPermissionFeatures(api_name, json_fs):
  return _GetChannelFromFeatures(api_name, json_fs, '_permission_features.json')

class AvailabilityFinder(object):
  '''Generates availability information for APIs by looking at API schemas and
  _features files over multiple release versions of Chrome.
  '''

  def __init__(self,
               branch_utility,
               compiled_fs_factory,
               file_system_iterator,
               host_file_system,
               object_store_creator):
    self._branch_utility = branch_utility
    self._compiled_fs_factory = compiled_fs_factory
    self._file_system_iterator = file_system_iterator
    self._host_file_system = host_file_system
    self._object_store_creator = object_store_creator
    def create_object_store(category):
      return object_store_creator.Create(AvailabilityFinder, category=category)
    self._top_level_object_store = create_object_store('top_level')
    self._node_level_object_store = create_object_store('node_level')
    self._json_fs = compiled_fs_factory.ForJson(self._host_file_system)

  def _GetPredeterminedAvailability(self, api_name):
    '''Checks a configuration file for hardcoded (i.e. predetermined)
    availability information for an API.
    '''
    api_info = self._json_fs.GetFromFile(
        JSON_TEMPLATES + 'api_availabilities.json').Get().get(api_name)
    if api_info is None:
      return None
    if api_info['channel'] == 'stable':
      return self._branch_utility.GetStableChannelInfo(api_info['version'])
    else:
      return self._branch_utility.GetChannelInfo(api_info['channel'])

  def _GetApiSchemaFilename(self, api_name, file_system, version):
    '''Gets the name of the file which may contain the schema for |api_name| in
    |file_system|, or None if the API is not found. Note that this may be the
    single _EXTENSION_API file which all APIs share in older versions of Chrome,
    in which case it is unknown whether the API actually exists there.
    '''
    def under_api_path(path):
      return API + path

    if version == 'trunk' or version > _ORIGINAL_FEATURES_MIN_VERSION:
      # API schema filenames switch format to unix_hacker_style.
      api_name = UnixName(api_name)

    # |file_system| will cache the results from the ReadSingle() call.
    filenames = file_system.ReadSingle(API).Get()

    for ext in ('json', 'idl'):
      filename = '%s.%s' % (api_name, ext)
      if filename in filenames:
        return under_api_path(filename)
    if _EXTENSION_API in filenames:
      return under_api_path(_EXTENSION_API)
    # API schema data could not be found in any .json or .idl file.
    return None

  def _GetApiSchema(self, api_name, file_system, version):
    '''Searches |file_system| for |api_name|'s API schema data, and processes
    and returns it if found.
    '''
    api_filename = self._GetApiSchemaFilename(api_name, file_system, version)
    if api_filename is None:
      # No file for the API could be found in the given |file_system|.
      return None

    schema_fs = self._compiled_fs_factory.ForApiSchema(file_system)
    api_schemas = schema_fs.GetFromFile(api_filename).Get()
    matching_schemas = [api for api in api_schemas
                        if api['namespace'] == api_name]
    # There should only be a single matching schema per file, or zero in the
    # case of no API data being found in _EXTENSION_API.
    assert len(matching_schemas) <= 1
    return matching_schemas or None

  def _HasApiSchema(self, api_name, file_system, version):
    '''Whether or not an API schema for |api_name|exists in the given
    |file_system|.
    '''
    filename = self._GetApiSchemaFilename(api_name, file_system, version)
    if filename is None:
      return False
    if filename.endswith(_EXTENSION_API):
      return self._GetApiSchema(api_name, file_system, version) is not None
    return True

  def _CheckStableAvailability(self, api_name, file_system, version):
    '''Checks for availability of an API, |api_name|, on the stable channel.
    Considers several _features.json files, file system existence, and
    extension_api.json depending on the given |version|.
    '''
    if version < _SVN_MIN_VERSION:
      # SVN data isn't available below this version.
      return False
    available_channel = None
    json_fs = self._compiled_fs_factory.ForJson(file_system)
    if version >= _API_FEATURES_MIN_VERSION:
      # The _api_features.json file first appears in version 28 and should be
      # the most reliable for finding API availability.
      available_channel = _GetChannelFromApiFeatures(api_name, json_fs)
    if version >= _ORIGINAL_FEATURES_MIN_VERSION:
      # The _permission_features.json and _manifest_features.json files are
      # present in Chrome 20 and onwards. Use these if no information could be
      # found using _api_features.json.
      available_channel = available_channel or (
          _GetChannelFromPermissionFeatures(api_name, json_fs)
          or _GetChannelFromManifestFeatures(api_name, json_fs))
      if available_channel is not None:
        return available_channel == 'stable'
    if version >= _SVN_MIN_VERSION:
      # Fall back to a check for file system existence if the API is not
      # stable in any of the _features.json files, or if the _features files
      # do not exist (version 19 and earlier).
      return self._HasApiSchema(api_name, file_system, version)

  def _CheckChannelAvailability(self, api_name, file_system, channel_info):
    '''Searches through the _features files in a given |file_system|, falling
    back to checking the file system for API schema existence, to determine
    whether or not an API is available on the given channel, |channel_info|.
    '''
    json_fs = self._compiled_fs_factory.ForJson(file_system)
    available_channel = (_GetChannelFromApiFeatures(api_name, json_fs)
        or _GetChannelFromPermissionFeatures(api_name, json_fs)
        or _GetChannelFromManifestFeatures(api_name, json_fs))
    if (available_channel is None and
        self._HasApiSchema(api_name, file_system, channel_info.version)):
      # If an API is not represented in any of the _features files, but exists
      # in the filesystem, then assume it is available in this version.
      # The chrome.windows API is an example of this.
      available_channel = channel_info.channel
    # If the channel we're checking is the same as or newer than the
    # |available_channel| then the API is available at this channel.
    newest = BranchUtility.NewestChannel((available_channel,
                                          channel_info.channel))
    return available_channel is not None and newest == channel_info.channel

  def _CheckApiAvailability(self, api_name, file_system, channel_info):
    '''Determines the availability for an API at a certain version of Chrome.
    Two branches of logic are used depending on whether or not the API is
    determined to be 'stable' at the given version.
    '''
    if channel_info.channel == 'stable':
      return self._CheckStableAvailability(api_name,
                                           file_system,
                                           channel_info.version)
    return self._CheckChannelAvailability(api_name,
                                          file_system,
                                          channel_info)

  def GetApiAvailability(self, api_name):
    '''Performs a search for an API's top-level availability by using a
    HostFileSystemIterator instance to traverse multiple version of the
    SVN filesystem.
    '''
    availability = self._top_level_object_store.Get(api_name).Get()
    if availability is not None:
      return availability

    # Check for predetermined availability and cache this information if found.
    availability = self._GetPredeterminedAvailability(api_name)
    if availability is not None:
      self._top_level_object_store.Set(api_name, availability)
      return availability

    def check_api_availability(file_system, channel_info):
      return self._CheckApiAvailability(api_name, file_system, channel_info)

    availability = self._file_system_iterator.Descending(
        self._branch_utility.GetChannelInfo('dev'),
        check_api_availability)
    if availability is None:
      # The API wasn't available on 'dev', so it must be a 'trunk'-only API.
      availability = self._branch_utility.GetChannelInfo('trunk')
    self._top_level_object_store.Set(api_name, availability)
    return availability

  def GetApiNodeAvailability(self, api_name):
    '''Returns an APISchemaGraph annotated with each node's availability (the
    ChannelInfo at the oldest channel it's available in).
    '''
    availability_graph = self._node_level_object_store.Get(api_name).Get()
    if availability_graph is not None:
      return availability_graph

    def assert_not_none(value):
      assert value is not None
      return value

    availability_graph = APISchemaGraph()

    host_fs = self._host_file_system
    trunk_stat = assert_not_none(host_fs.Stat(self._GetApiSchemaFilename(
        api_name, host_fs, 'trunk')))

    # Weird object thing here because nonlocal is Python 3.
    previous = type('previous', (object,), {'stat': None, 'graph': None})

    def update_availability_graph(file_system, channel_info):
      version_filename = assert_not_none(self._GetApiSchemaFilename(
          api_name, file_system, channel_info.version))
      version_stat = assert_not_none(file_system.Stat(version_filename))

      # Important optimisation: only re-parse the graph if the file changed in
      # the last revision. Parsing the same schema and forming a graph on every
      # iteration is really expensive.
      if version_stat == previous.stat:
        version_graph = previous.graph
      else:
        # Keep track of any new schema elements from this version by adding
        # them to |availability_graph|.
        #
        # Calling |availability_graph|.Lookup() on the nodes being updated
        # will return the |annotation| object -- the current |channel_info|.
        version_graph = APISchemaGraph(self._GetApiSchema(
            api_name, file_system, channel_info.version))
        availability_graph.Update(version_graph.Subtract(availability_graph),
                                  annotation=channel_info)

      previous.stat = version_stat
      previous.graph = version_graph

      # Continue looping until there are no longer differences between this
      # version and trunk.
      return version_stat != trunk_stat

    self._file_system_iterator.Ascending(self.GetApiAvailability(api_name),
                                         update_availability_graph)

    self._node_level_object_store.Set(api_name, availability_graph)
    return availability_graph


import logging
import importlib
import copy
import pkgutil
import pkg_resources
import yaml

from pathlib import Path

import hyperspy.misc.config_dir

_logger = logging.getLogger(__name__)

_ext_f = Path(__file__).resolve().parent.joinpath("hyperspy_extension.yaml")
with open(_ext_f, 'r') as stream:
    EXTENSIONS = yaml.safe_load(stream)
EXTENSIONS["GUI"]["widgets"] = {}

# External extensions are not integrated into the API and not
# import unless needed
ALL_EXTENSIONS = copy.deepcopy(EXTENSIONS)

_external_extensions = [
    entry_point.module_name
    for entry_point in pkg_resources.iter_entry_points('hyperspy.extensions')]

for _external_extension_mod in _external_extensions:
    _logger.info("Enabling extension %s" % _external_extension_mod)
    _path = Path(
        pkgutil.get_loader(_external_extension_mod).get_filename()
    ).resolve().parent.joinpath("hyperspy_extension.yaml")

    if _path.is_file():
        with open(_path, 'r') as stream:
            _external_extension = yaml.safe_load(stream)
            if "signals" in _external_extension:
                ALL_EXTENSIONS["signals"].update(_external_extension["signals"])
            if "components1D" in _external_extension:
                ALL_EXTENSIONS["components1D"].update(
                    _external_extension["components1D"])
            if "components2D" in _external_extension:
                ALL_EXTENSIONS["components2D"].update(
                    _external_extension["components2D"])
            if "GUI" in _external_extension:
                if "toolkeys" in _external_extension["GUI"]:
                    ALL_EXTENSIONS["GUI"]["toolkeys"].extend(
                        _external_extension["GUI"]["toolkeys"])
                if "widgets" in _external_extension["GUI"]:
                    for toolkit, specs in _external_extension["GUI"]["widgets"].items():
                        if toolkit not in ALL_EXTENSIONS["GUI"]["widgets"]:
                            ALL_EXTENSIONS["GUI"]["widgets"][toolkit] = {}
                        ALL_EXTENSIONS["GUI"]["widgets"][toolkit].update(specs)

    else:
        _logger.error(
            "Failed to load hyperspy extension from {0}. Please report this issue to the {0} developers".format(_external_extension_mod))