from __future__ import absolute_import

import json
import pytest

from decimal import Decimal
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase

from silver.tests.factories import (AdminUserFactory, MeteredFeatureFactory,
                                    ProductCodeFactory)
from silver.tests.utils import build_absolute_test_url

class TestMeteredFeatureEndpoint(APITestCase):

    def setUp(self):
        admin_user = AdminUserFactory.create()
        self.client.force_authenticate(user=admin_user)
        ProductCodeFactory.reset_sequence(1)
        self.product_code = ProductCodeFactory.create()
        self.complete_data = {
            "name": "Page Views",
            "unit": "100k",
            "price_per_unit": '0.0500',
            "included_units": '0.0000',
            "product_code": self.product_code.value
        }

    """
    def _full_url(self, pk=None):
        base_url = "http://testserver"
        relative_url = reverse('metered-feature-detail', kwargs={'pk': pk})
        return urlparse.urljoin(base_url, relative_url)
    """

    def test_create_post_metered_feature(self):
        url = reverse('metered-feature-list')
        response = self.client.post(url, json.dumps(self.complete_data),
                                    content_type='application/json')
        assert response.status_code == status.HTTP_201_CREATED
        expected = self.complete_data
        # expected.update({'url': self._full_url(1)})
        assert expected == response.data

    def test_create_post_metered_feature_without_required_field(self):
        url = reverse('metered-feature-list')

        required_fields = ['name', 'price_per_unit', 'included_units']
        for field in required_fields:
            temp_data = self.complete_data.copy()
            try:
                temp_data.pop(field)
            except KeyError:
                pytest.xfail('Metered Feature required field %s not provided in'
                             'the complete test data.' % field)

            response = self.client.post(url, json.dumps(temp_data),
                                        content_type='application/json')

            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
            assert (response.data == {field: ['This field may not be blank.']} or
                    response.data == {field: ['This field is required.']})
    """
    #def test_create_post_metered_feature_bulk(self):
        #mfs = MeteredFeatureFactory.create_batch(7)

        #raw_mfs = json.loads(serializers.serialize('json', mfs))

        #serialized_mfs = []
        #for item in raw_mfs:
            #serialized_mfs.append(item['fields'])

        #url = reverse('metered-feature-list')

        #response = self.client.post(url, data=json.dumps(serialized_mfs),
                                    #content_type='application/json')

        #self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        #self.assertEqual(len(response.data), 7)

    def test_get_metered_feature_detail(self):
        metered_feature = MeteredFeatureFactory.create(product_code=self.product_code)

        url = reverse('metered-feature-detail',
                      kwargs={'pk': metered_feature.pk})

        response = self.client.get(url)

        assert response.status_code == status.HTTP_200_OK
        assert response.data == {
            "name": metered_feature.name,
            "unit": metered_feature.unit,
            "included_units": metered_feature.included_units.to_eng_string(),
            "price_per_unit": metered_feature.price_per_unit.to_eng_string(),
            "product_code": self.product_code.value,
            'url': self._full_url(1)
        }
    """

    def test_get_metered_feature_list(self):
        MeteredFeatureFactory.create_batch(40)
        url = reverse('metered-feature-list')

        response = self.client.get(url)

        full_url = build_absolute_test_url(url)

        assert response.status_code == status.HTTP_200_OK
        assert response._headers['link'] == \
            ('Link', '<' + full_url + '?page=2>; rel="next", ' +
             '<' + full_url + '?page=1>; rel="first", ' +
             '<' + full_url + '?page=2> rel="last"')

        response = self.client.get(url + '?page=2')

        assert response.status_code == status.HTTP_200_OK
        assert response._headers['link'] == \
            ('Link', '<' + full_url + '>; rel="prev", ' +
             '<' + full_url + '?page=1>; rel="first", ' +
             '<' + full_url + '?page=2> rel="last"')

    """
    def test_get_metered_feature_unexisting(self):
        url = reverse('metered-feature-detail',
                      kwargs={'pk': 42})

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, {u'detail': u'Not found'})

    def test_delete_metered_feature(self):
        MeteredFeatureFactory.create()

        url = reverse('metered-feature-detail', kwargs={'pk': 1})

        response = self.client.delete(url)

        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data,
                         {u'detail': u"Method 'DELETE' not allowed."})

    def test_edit_put_metered_feature(self):
        MeteredFeatureFactory.create()

        url = reverse('metered-feature-detail', kwargs={'pk': 1})

        response = self.client.put(url)

        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data,
                         {u'detail': u"Method 'PUT' not allowed."})

    def test_edit_patch_metered_feature(self):
        MeteredFeatureFactory.create()

        url = reverse('metered-feature-detail', kwargs={'pk': 1})

        response = self.client.patch(url)

        self.assertEqual(response.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data,
                         {u'detail': u"Method 'PATCH' not allowed."})

    """

class TestLinkedMeteredFeatureEndpoint(APITestCase):

    def setUp(self):
        admin_user = AdminUserFactory.create()
        self.client.force_authenticate(user=admin_user)
        ProductCodeFactory.reset_sequence(1)
        self.user_product_code = ProductCodeFactory.create(value="user_product_code")
        self.user_feature_data = {
            "name": "Users",
            "unit": "user",
            "price_per_unit": '1.0000',
            "included_units": '0.0000',
            "product_code": self.user_product_code.value
        }

        self.minutes_product_code = ProductCodeFactory.create(value="minutes_product_code")
        self.minutes_data = {
            "name": "Minutes",
            "unit": "20 minutes / user",
            "price_per_unit": '5.0000',
            "included_units": '20.0000',
            "product_code": self.minutes_product_code.value,
        }

        self.link                               = self.minutes_data.copy()
        self.link['linked_feature']             = self.user_product_code.value
        self.link['linked_feature_calculation'] = "multiply"

        self.prebill_minutes_product_code = ProductCodeFactory.create(
            value="prebill_minutes_product_code"
        )

        self.prebill_minutes_data = {
            "name": "Minutes",
            "unit": "20 minutes / user",
            "prebill_included_units": True,
            "price_per_unit": '5.0000',
            "included_units": '20.0000',
            "product_code": self.minutes_product_code.value,
        }

    @pytest.mark.django_db
    def test_create_post_metered_feature(self):
        """ Test creating the features individually.
        """

        url = reverse('metered-feature-list')
        response = self.client.post(url, json.dumps(self.user_feature_data),
                                    content_type='application/json')
        assert response.status_code == status.HTTP_201_CREATED
        expected = self.user_feature_data

        assert expected == response.data

        minutes_with_link = self.minutes_data

        response = self.client.post(url, json.dumps(minutes_with_link),
                                    content_type='application/json')

        assert response.status_code == status.HTTP_201_CREATED
        expected = self.minutes_data

        assert expected == response.data

    @pytest.mark.django_db
    def test_create_post_metered_feature_with_link(self):
        """ Create the features as above, add a link.
        """

        url = reverse('metered-feature-list')

        response = self.client.post(url,
                                    json.dumps(self.user_feature_data),
                                    content_type='application/json')

        l = self.link
        response = self.client.post(url, json.dumps(l),
                                    content_type='application/json')

        assert response.status_code == status.HTTP_201_CREATED
        expected = self.link

        assert response.data.get('linked_feature') == self.user_product_code.value

    @pytest.mark.django_db
    def test_create_prebilled_feature(self):
        url = reverse('metered-feature-list')

        response = self.client.post(url, json.dumps(self.prebill_minutes_data),
                                    content_type='application/json')

        assert response.status_code == status.HTTP_201_CREATED

        expected = self.prebill_minutes_data
        assert expected == response.data


import jwt
from datetime import datetime, timedelta
from django.conf import settings

JWT_EXPIRE_DAYS = 60
JWT_ALGORITHM = 'HS256'
JWT_SECRET_KEY = settings.SECRET_KEY

def jwt_decode(token):
    return jwt.decode(token, key=JWT_SECRET_KEY, algorithms=JWT_ALGORITHM)

def jwt_encode(pk):
    dt = datetime.now() + timedelta(days=JWT_EXPIRE_DAYS)
    print((dt-datetime.utcfromtimestamp(0)).total_seconds())
    print(dt.strftime('%S'))
    token = jwt.encode({
        'id': pk,
        'exp': int((dt-datetime.utcfromtimestamp(0)).total_seconds())
    }, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)

    return token.decode('utf-8')


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('provider', '0003_auto_20160623_1428'),
    ]

    operations = [
        migrations.AddField(
            model_name='address',
            name='user',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='practitioner',
            name='user',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AlterField(
            model_name='practitioner',
            name='fhir_id',
            field=models.CharField(default='', unique=True, max_length=24),
        ),
        migrations.AlterField(
            model_name='practitioner',
            name='npi',
            field=models.CharField(default='', unique=True, max_length=10),
        ),
    ]


import inspect

from interface import Interface
from excecoes import InterfaceInvalida

class Implementacao(object):

    def __init__(self, cls, implementacoes):
        self._verificar_implementacoes(implementacoes)
        self._definir_metodo_assegurar_interfaces(cls, implementacoes)

    def _verificar_implementacoes(self, implementacoes):
        for i in implementacoes:
            if not issubclass(i, Interface):
                raise InterfaceInvalida('"' + i.__name__ + ' invalida. Interfaces devem herdar "interface.Interface". ')

    def _obter_inspecao_dos_argumentos(self, metodo):
        return inspect.getargspec(metodo)

    def _definir_metodo_assegurar_interfaces(self, cls, implementacoes):
        @staticmethod
        def assegurar_interfaces():
            for interface in implementacoes:
                for attr in dir(interface):
                    if attr.startswith('_') or \
                     attr == 'InterfaceNaoImplementada':
                        continue

                    try:
                        atributo = getattr(cls, attr)

                    except AttributeError:
                        raise interface.InterfaceNaoImplementada(cls, 'atributo "' + attr + '" nao encontrado.')

                    if callable(getattr(interface, attr)):
                        if not callable(atributo):
                            raise interface.InterfaceNaoImplementada(cls, 'atributo "' + attr + '" deve ser um metodo.')

                        if not self._obter_inspecao_dos_argumentos(getattr(interface, attr)) \
                         == self._obter_inspecao_dos_argumentos(atributo):
                            raise interface.InterfaceNaoImplementada(cls, 'assinatura no metodo "' + attr + '" invalida.')

        cls.assegurar_interfaces = assegurar_interfaces

def implements(*implementacoes):
    def manipulador(cls):
        Implementacao(cls, implementacoes)

        return cls

    return manipulador


import turtle as tr
import time

pen = tr.Turtle()
tr.bgcolor('black')
tr.pensize(1)
tr.pencolor('white')

""" rysowanie ramki """

tr.penup()
tr.goto(255, 255)
tr.left(180)

for k in range(0,4):
    for i in range(1, 7):
        tr.pendown()
        tr.forward(30)
        tr.penup()
        tr.forward(30)
        tr.pendown()
    tr.forward(30)
    tr.left(90)

tr.pensize(1)
tr.pencolor('red')

tr.penup()
for i in range(1, 7):
    tr.forward(30)
    tr.pendown()
    tr.left(90)
    tr.forward(390)
    tr.right(90)
    tr.forward(30)
    tr.right(90)
    tr.forward(390)
    tr.left(90)

tr.penup()
tr.forward(30)
tr.left(90)
tr.forward(30)

tr.pencolor('blue')
tr.pendown()
for k in range(1, 7):
    tr.left(90)
    tr.forward(390)
    tr.right(90)
    tr.forward(30)
    tr.right(90)
    tr.forward(390)
    tr.left(90)
    tr.forward(30)

tr.bgcolor('white')
for w in range(1, 5):
    tr.left(90)
    tr.forward(390)

tr.pencolor('yellow')
tr.pensize(2)
tr.penup()
tr.goto(-135, 255)
tr.pendown()

x = -135
y = 255
krok = 30
for krok in range(30, 390, 60):
    tr.goto(x, y - krok)
    tr.goto(x + krok, y)
    krok += 30
    tr.goto(x + krok, y)
    tr.goto(x, y - krok)

tr.penup()

tr.pencolor('green')
x = 255
y = 255
krok = 30
tr.goto(-135 + 30, -135)
tr.pendown()

for krok in range(30, 390, 60):
    tr.goto(-135 + krok, -135)
    tr.goto(x, y - krok)
    krok += 30
    tr.goto(x, y - krok)
    tr.goto(-135 + krok, -135)

tr.goto(x, -135)

def main():
    tr.setup()
    tr.done()
main()


import psycopg2
import pytest

from procrastinate import exceptions, psycopg2_connector

def test_wrap_exceptions_wraps():
    @psycopg2_connector.wrap_exceptions
    def func():
        raise psycopg2.DatabaseError

    with pytest.raises(exceptions.ConnectorException):
        func()

def test_wrap_exceptions_success():
    @psycopg2_connector.wrap_exceptions
    def func(a, b):
        return a, b

    assert func(1, 2) == (1, 2)

@pytest.mark.parametrize("pool_args, called_count", [({"maxconn": 5}, 6), ({}, 1)])
def test_wrap_query_exceptions_reached_max_tries(mocker, pool_args, called_count):
    called = []

    @psycopg2_connector.wrap_query_exceptions
    def func(connector):
        called.append(True)
        raise psycopg2.errors.AdminShutdown()

    connector = mocker.Mock(_pool=mocker.Mock(**pool_args))

    with pytest.raises(exceptions.ConnectorException) as excinfo:
        func(connector)

    assert len(called) == called_count
    assert str(
        excinfo.value
    ) == "Could not get a valid connection after {} tries".format(called_count)

def test_wrap_query_exceptions_unhandled_exception(mocker):
    called = []

    @psycopg2_connector.wrap_query_exceptions
    def func(connector):
        called.append(True)
        raise psycopg2.errors.OperationalError()

    connector = mocker.Mock(_pool=mocker.Mock(maxconn=5))

    with pytest.raises(psycopg2.errors.OperationalError):
        func(connector)

    assert len(called) == 1

def test_wrap_query_exceptions_success(mocker):
    called = []

    @psycopg2_connector.wrap_query_exceptions
    def func(connector, a, b):
        if len(called) < 2:
            called.append(True)
            raise psycopg2.errors.AdminShutdown()
        return a, b

    connector = mocker.Mock(_pool=mocker.Mock(maxconn=5))
    assert func(connector, 1, 2) == (1, 2)
    assert len(called) == 2

@pytest.mark.parametrize(
    "method_name",
    ["__init__", "close", "execute_query", "execute_query_one", "execute_query_all"],
)
def test_wrap_exceptions_applied(method_name):
    connector = psycopg2_connector.Psycopg2Connector()
    assert getattr(connector, method_name)._exceptions_wrapped is True


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import notes.models

class Migration(migrations.Migration):

    dependencies = [
        ('notes', '0003_auto_20160122_1041'),
    ]

    operations = [
        migrations.AddField(
            model_name='textnote',
            name='image',
            field=models.ImageField(null=True, upload_to=notes.models.image_directory_path, blank=True),
        ),
    ]


from pymodaq.daq_move.utility_classes import DAQ_Move_base
from pymodaq.daq_move.utility_classes import comon_parameters
from pymodaq.daq_utils.daq_utils import ThreadCommand
from easydict import EasyDict as edict
from pymodaq_plugins.hardware.smaract.smaract import SmarAct
from pymodaq_plugins.hardware.smaract.smaract import get_controller_locators

class DAQ_Move_SmarActMCS(DAQ_Move_base):
    """
    This plugin supports only SmarAct LINEAR positionners (SLC type), with enabled sensors attached to them.
    We suppose to have one (or multiple) MCS controllers connected. With 3 channels (each).
    We suppose that the configuration of the controllers (sensor type etc) has been done via the SmarAct MCS
    Configuration software.
    Tested with one SLC-1740-S (closed loop with nanometer precision sensor) connected via a MCS-3S-EP-SDS15-TAB
    (sensor module) to a MCS-3D (or MCS-3C) controller on Windows 7.
    """

    _controller_units = 'µm'

    # find controller locators
    controller_locators = get_controller_locators()

    is_multiaxes = True
    # we suppose to have a MCS controller with 9 channels.
    stage_names = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    # bounds corresponding to the SLC-24180
    min_bound = -61500 # µm
    max_bound = +61500 # µm
    offset = 0 # µm

    params = [
                 {'title': 'group parameter:', 'name': 'group_parameter', 'type': 'group', 'children': [
                     {'title': 'Controller Name:', 'name': 'smaract_mcs', 'type': 'str',
                      'value': 'SmarAct MCS controller', 'readonly': True},
                     {'title': 'Controller locator', 'name': 'controller_locator', 'type': 'list',
                      'values': controller_locators},
                 ]},

                 ##########################################################
                 # the ones below should ALWAYS be present!!!
                 {'title': 'MultiAxes:', 'name': 'multiaxes', 'type': 'group', 'visible': is_multiaxes, 'children': [
                     {'title': 'is Multiaxes:', 'name': 'ismultiaxes', 'type': 'bool', 'value': is_multiaxes,
                      'default': False},
                     {'title': 'Status:', 'name': 'multi_status', 'type': 'list', 'value': 'Master',
                      'values': ['Master', 'Slave']},
                     {'title': 'Axis:', 'name': 'axis', 'type': 'list',
                      'values': stage_names, 'value': 6},

                 ]}] + comon_parameters
                 ##########################################################

    def __init__(self, parent=None, params_state=None):
        super(DAQ_Move_SmarActMCS, self).__init__(parent, params_state)

        self.controller = None

    def ini_stage(self, controller=None):
        """
            Initialize the controller and stages (axes) with given parameters.

            =============== ================================================ =========================================================================================
            **Parameters**   **Type**                                         **Description**
            *controller*     instance of the specific controller object       If defined this hardware will use it and will not initialize its own controller instance
            =============== ================================================ =========================================================================================

            Returns
            -------
            Easydict
                dictionnary containing keys:
                 * *info* : string displaying various info
                 * *controller*: instance of the controller object in order to control other axes without the need to init the same controller twice
                 * *stage*: instance of the stage (axis or whatever) object
                 * *initialized*: boolean indicating if initialization has been done correctly

            See Also
            --------
            DAQ_utils.ThreadCommand
        """
        try:
            # initialize the stage and its controller status
            # controller is an object that may be passed to other instances of DAQ_Move_Actuator in case
            # of one controller controlling multiaxes
            self.status.update(edict(info="", controller=None, initialized=False))

            #check whether this stage is controlled by a multiaxe controller (to be defined for each plugin)
            # if mutliaxes then init the controller here if Master state otherwise use external controller
            if self.settings.child('multiaxes', 'ismultiaxes').value() and self.settings.child('multiaxes','multi_status').value()=="Slave":
                if controller is None:
                    raise Exception('no controller has been defined externally while this axe is a slave one')
                else:
                    self.controller = controller
            else: #Master stage
                try:
                    self.close()
                except:
                    pass
                self.controller = SmarAct()
                self.controller.init_communication(self.settings.child('group_parameter', 'controller_locator').value())

            # The min and max bounds will depend on which positionner is plugged. Anyway the bounds are secured
            # by the library functions.
            self.settings.child('bounds', 'is_bounds').setValue(True)
            self.settings.child('bounds', 'min_bound').setValue(self.min_bound)
            self.settings.child('bounds', 'max_bound').setValue(self.max_bound)
            self.settings.child('scaling', 'use_scaling').setValue(False)
            self.settings.child('scaling', 'offset').setValue(self.offset)

            # The value of epsilon set the tolerance around the target position
            # within which it is considered that the target position is reached
            # Never set it below your actuator precision.
            self.settings.child(('epsilon')).setValue(0.002)

            self.status.controller = self.controller
            self.status.initialized = True

            return self.status

        except Exception as e:
            self.emit_status(ThreadCommand('Update_Status', [str(e), 'log']))
            self.status.info = str(e)
            self.status.initialized = False

            return self.status

    def close(self):
        """
            Close the communication with the SmarAct controller.
        """

        self.controller.close_communication()
        self.controller = None

    def check_position(self):
        """
            Get the current hardware position with scaling conversion given by get_position_with_scaling.
        """

        position = self.controller.get_position(self.settings.child('multiaxes', 'axis').value())

        # the position given by the controller is in nanometers, we convert in micrometers
        position = float(position)/1e3

        # convert position if scaling options have been used, mandatory here
        position = self.get_position_with_scaling(position)
        self.current_position = position
        self.emit_status(ThreadCommand('check_position', [position]))

        return position

    def move_Abs(self, position):
        """
            Move to an absolute position

        Parameters
        ----------
        position: float
        """
        #limit position if bounds options has been selected and if position is out of them
        position = self.check_bound(position)
        self.target_position = position
        # convert the user set position to the controller position if scaling has been activated by user
        position = self.set_position_with_scaling(position)

        # we convert position in nm
        position = int(position*1e3)

        # the SmarAct controller asks for nanometers
        self.controller.absolute_move(self.settings.child('multiaxes', 'axis').value(), position)

        # start polling the position until the actuator reach the target position within epsilon
        # defined as a parameter field (comon_parameters)
        self.poll_moving()

    def move_Rel(self,position):
        """
            Move to a relative position

        Parameters
        ----------
        position: float
        """
        # limit position if bounds options has been selected and if position is out of them
        position = self.check_bound(self.current_position + position) - self.current_position
        self.target_position = position + self.current_position
        # convert the user set position to the controller position if scaling has been activated by user
        position = self.set_position_with_scaling(position)

        # we convert position in nm
        position = int(position*1e3)

        # the SmarAct controller asks for nanometers
        self.controller.relative_move(self.settings.child('multiaxes', 'axis').value(), position)

        self.poll_moving()

    def move_Home(self):
        """
            Move to home and reset position to zero.
        """

        self.controller.find_reference(self.settings.child('multiaxes', 'axis').value())

    def stop_motion(self):
        """
            See Also
            --------
            DAQ_Move_base.move_done
        """

        self.controller.stop(self.settings.child('multiaxes', 'axis').value())

        self.move_done()

if __name__ == "__main__":
    test = DAQ_Move_SmarActMCS()


import random
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.cm as cm
import numpy as np
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import copy as kopi
import random
import math
from random import shuffle, randrange
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'

num_rows = int(input("rows")) # number of rows
num_cols = int(input("columns")) # number of columns

# The array M is going to hold the array information for each cell.
# The first four coordinates tell if walls exist on those sides
# and the fifth indicates if the cell has been visited in the search.
# M(LEFT, UP, RIGHT, DOWN, CHECK_IF_VISITED)
M = np.zeros((num_rows,num_cols,5), dtype=np.uint8)

# The array image is going to be the output image to display
image = np.zeros((num_rows*10,num_cols*10), dtype=np.uint8)

# Set starting row and column
r = 0
c = 0
history = [(r,c)] # The history is the stack of visited locations

# Trace a path though the cells of the maze and open walls along the path.
# We do this with a while loop, repeating the loop until there is no history,
# which would mean we backtracked to the initial start.
while history:
    M[r,c,4] = 1 # designate this location as visited
    # check if the adjacent cells are valid for moving to

    check = []
    if c > 0 and M[r,c-1,4] == 0:
        check.append('L')
    if r > 0 and M[r-1,c,4] == 0:
        check.append('U')
    if c < num_cols-1 and M[r,c+1,4] == 0:
        check.append('R')
    if r < num_rows-1 and M[r+1,c,4] == 0:
        check.append('D')

    if len(check): # If there is a valid cell to move to.
        # Mark the walls between cells as open if we move
        history.append([r,c])
        move_direction = random.choice(check)
        if move_direction == 'L':
            M[r,c,0] = 1
            c = c-1
            M[r,c,2] = 1
        if move_direction == 'U':
            M[r,c,1] = 1
            r = r-1
            M[r,c,3] = 1
        if move_direction == 'R':
            M[r,c,2] = 1
            c = c+1
            M[r,c,0] = 1
        if move_direction == 'D':
            M[r,c,3] = 1
            r = r+1
            M[r,c,1] = 1
    else: # If there are no valid cells to move to.
	# retrace one step back in history if no move is possible
        r,c = history.pop()

# Open the walls at the start and finish

M[0,num_cols-1,2] = 1

# Generate the image for display

for row in range(0,num_rows):
    for col in range(0,num_cols):

        print(row,col,M[row,col])

        cell_data = M[row,col]
        for i in range(10*row+1,10*row+9):
            image[i,range(10*col+1,10*col+9)] = 1
            if (cell_data[0] == 1):
                image[range(10*row+1,10*row+9),10*col] = 1

            if (cell_data[1] == 1):
                image[10*row,range(10*col+1,10*col+9)] = 1

            if (cell_data[2] == 1):
                image[range(10*row+1,10*row+9),10*col+9] = 1

            if (cell_data[3] == 1):
                image[10*row+9,range(10*col+1,10*col+9)] = 1

#######################################
class Pemakan:
    def __init__(self,a,b):
        self.posx=a
        self.posy=b
        self.speed=0.5
        self.skor=0.05
        self.x=-1
        self.y=-1
    def look(self):
        mindist=9999999999
        minfood=0

        for i in range (len(varbully)):
            if(varbully[i].status==1):
                dist=math.sqrt((self.posx-varbully[i].posx)**2+(self.posy-varbully[i].posy)**2)
                if (mindist>dist and dist!=0):
                    mindist=dist
                    minfood=i

        self.x=self.speed*(varbully[minfood].posx-self.posx)/mindist
        self.y=self.speed*(varbully[minfood].posy-self.posy)/mindist

    def move(self):
        self.posx=self.posx+self.x
        self.posy=self.posy+self.y
    def inc(self):
        self.speed+=self.skor

class Bully:

    def __init__(self,celposx,cel):
        self.celposx=num_rows-1
        self.celposy=0
        self.posx=0
        self.posy=0
        self.status=1
        self.x=-1
        self.y=-1
        self.map=kopi.copy(M)
        self.stackx=[]
        self.stacky=[]

    def celmove(self):
        if(self.celposx!=0 or self.celposy!=num_cols-1):

            print("jalan")
            movee=[]

            self.stackx.append(self.celposx)
            self.stacky.append(self.celposy)

            self.map[self.celposx,self.celposy,4]=0
            if(self.map[self.celposx,self.celposy,0]==1 and self.map[self.celposx,self.celposy-1,4]==1):
                movee.append(0)
            if(self.map[self.celposx,self.celposy,1]==1 and self.map[self.celposx-1,self.celposy,4]==1):
                movee.append(1)
            if(self.map[self.celposx,self.celposy,2]==1 and self.map[self.celposx,self.celposy+1,4]==1):
                movee.append(2)
            if(self.map[self.celposx,self.celposy,3]==1 and self.map[self.celposx+1,self.celposy,4]==1):
                movee.append(3)

            if(len(movee)>0):
                rand=random.randint(0,len(movee)-1)
                move=movee[rand]

                if(move==0):
                    self.celposy-=1
                elif(move==1):
                    self.celposx-=1
                elif(move==2):
                    self.celposy+=1
                elif(move==3):
                    self.celposx+=1
            else:
                print("backtrack")
                if(len(self.stackx)>0):
                    self.stackx.pop()
                    self.stacky.pop()
                if(len(self.stackx)>0):
                    self.celposx=self.stackx.pop()
                    self.celposy=self.stacky.pop()
            if(self.celposy==num_cols-1 and self.celposx==0):
                self.status=2

    def move(self):
        self.posx=self.celposy*10+random.randint(30,70)/10
        self.posy=self.celposx*10+random.randint(30,70)/10

varbully=[]
varmakan=[]

for i in range (30):
    varbully.append(Bully(random.randint(0,num_rows-3),random.randint(0,num_cols-4)))

varmakan.append(Pemakan(0,0))
varmakan.append(Pemakan((num_cols*10-1)/2,0))
tmax = 2000
pg=0
fig = plt.figure()

for t in range (tmax):

    fig = plt.figure()
    plt.gca().set_xlim([-10,(num_cols*10)+10])
    plt.gca().set_ylim([-10,(num_rows*10)+10])

    for i in range (0,len(varbully)):
        if(varbully[i].status>0):
            varbully[i].move()
            varbully[i].celmove()

    for i in range (0,len(varmakan)):
        varmakan[i].look()
        varmakan[i].move()

    for i in range (0,len(varmakan)):
        for j in range (0,len(varbully)):
            if(abs(varbully[j].posx-varmakan[i].posx )<=0.1*num_cols  and abs(varbully[j].posy-varmakan[i].posy )<= 0.1*num_rows):
                if(varbully[j].status==1):
                    varmakan[i].inc()
                    print("eat bro")
                    varbully[j].status=0

    for i in range (0,len(varbully)):
        if(varbully[i].status>0):
            plt.scatter (varbully[i].posx,varbully[i].posy,color='blue',s=5)

    for i in range (0,len(varmakan)):
        plt.scatter (varmakan[i].posx,varmakan[i].posy,color='red',s=150)

    plt.title('{0:03d}'.format(pg))
    plt.imshow(image, cmap = cm.Greys_r, interpolation='none')
    filename = 'frame{0:03d}.png'.format(pg)
    pg+=1
    plt.savefig(filename, bbox_inches='tight')
    plt.close(fig)


from abc import ABCMeta, abstractmethod
from threading import Thread, Event
import time
from utils import Event2Bool, EventQueue

class EventListener(object):

    __metaclass__ = ABCMeta

    @abstractmethod
    def on_event(self, event):
        pass

class Ownership(object):

    def __init__(self, event, owner=None):
        self.event = event
        self.owner = owner

class EventDispatcher(Thread):
    _started = Event2Bool(False)
    _gracefully = Event2Bool(False)

    def __init__(self, *args, **kwargs):
        super(EventDispatcher, self).__init__()
        self._started = False
        self._latch = None
        self._gracefully = False
        self.__flag = Event()
        self._event_manager = kwargs['event_manager']
        self._events = self._event_manager.events
        self._timeout = self._event_manager.timeout
        self._idle_time = self._event_manager.idle_time
        self._interval = self._event_manager.interval
        self._trigger_no_event = self._event_manager.trigger_no_event

    def start(self):
        if not self._started:
            self._started = True
            self._latch = Event()
            super(EventDispatcher, self).start()
            self.__flag.set()

    def stop(self, gracefully=True):
        if self._started:
            self._started = False
            self._gracefully = gracefully
            if self._gracefully:
                self._latch.wait()

    def is_alive(self):
        """return if is alive, if not alive, make it alive"""
        if not self._started:
            return False
        if not self.__flag.is_set():   # todo: lake wakeup
            self.__flag.set()
        return self.__flag.is_set()

    def wakeup(self):
        """pause thread"""
        if self.__flag.is_set():
            self.__flag.clear()

    def run(self):
        last_time = time.time()
        while True:
            self.__flag.wait()
            try:
                event = None
                if self.is_alive():
                    event = self._events.get(timeout=self._timeout)
                if not self.is_alive():
                    if not self._gracefully:
                        break
                    if event is None:
                        if self.__flag.is_set():
                            event = self._events.get(timeout=0.5)
                        else:
                            event = self._events.get()
                    if event is None:
                        break
                if event is not None:
                    if self._idle_time > 0:
                        last_time = time.time()
                    if self._interval > 0:
                        currents = []
                        currents.append(event)
                        while self._events.qsize() > 0:
                            event = self._events.get()
                            if event is not None:
                                currents.append(event)
                        self._event_manager.publish(currents)
                    else:
                        self._event_manager.publish(event)
                else:
                    if self._trigger_no_event:
                        self._event_manager.publish(None)
                    if self._idle_time > 0:
                        now = time.time()
                        if now - last_time > self._idle_time:
                            last_time = now
                            self._event_manager.on_idle()
                            if self._events.qsize() > 0:
                                continue
                if self._interval > 0 and self.is_alive():
                    time.sleep(self._interval)

            except KeyboardInterrupt:
                self.wakeup()
        if self._latch is not None:
            self._latch.set()

class EventManager(object):

    def __init__(self, name=None, idle_time=0, interval=0, timeout=1, trigger_no_event=False):
        self.listeners = []
        self.events = EventQueue()
        self.name = name
        self.idle_time = idle_time
        self.interval = interval
        self.timeout = timeout
        self.trigger_no_event = trigger_no_event
        self.event_dispatcher = EventDispatcher(event_manager=self)

    def publish(self, event):
        if isinstance(event, list):
            if len(event) > 0:
                self.publish(event[-1])
            return
        if event is not None and event.owner is not None:
            event.owner.on_event(event.event)
        else:
            e = event.event if event else None
            for listener in self.listeners:
                try:
                    listener.on_event(e)
                except:
                    pass

    def on_idle(self):
        pass

    def add_listener(self, listener):
        if listener is not None and listener not in self.listeners:
            self.listeners.append(listener)

    def start(self):
        self.event_dispatcher.start()

    def stop(self, gracefully=False):
        self.event_dispatcher.stop(gracefully=gracefully)

    def add(self, event, owner=None):
        if event is None:
            return False
        self.events.put(Ownership(event, owner))


#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import os
from math import ceil
import urllib.request
import json
import time

if __name__ == "__main__":

	# TRIVIAL VARIALBES
	clear = 'cls' if (os.name == 'nt') else 'clear'
	name_tags = {}
	suggar_names = {}
	exchange = {}
	instructions = """
	[LIST]: 	Show a list of all currencies. (requires internet)
	[ADD]: 		To add a new currency.
	[REMOVE]: 	To remove a previous currency.
	[UPDATE]: 	To get a new currency value. (requires internet)
	[CURRENCY]:	Show the exchange values with  USD.
	[CHANGE]: 	Update a exchange value manually. (against USD)
	[EXIT]: 	Allows you to save changes and quit.
	[RESET]: 	Deletes all configurations files. (in case they get bugged)
	[INSTRUCTIONS]: Shows instructions.
	[ANY LETTER EXCEPT 'K']: Change to the currency defined with that letter.
	>>> Letter 'k' is reserved and counts as '000', so 5kk is equal to 500000
	"""

	#LOAD PREVIOUS CONFIGURATIONS AND/OR DEFAULT VALUES
	if os.path.isfile("currency_calc.names"):
		with open("currency_calc.names", "r") as file_open:
			for line in file_open.readlines():
				letter, name, suggar = line.split(":")
				name_tags[letter] = name
				suggar_names[letter] = suggar
	else:
		name_tags 		= {'j': 'JPY', 		'c' : 'CAD', 	'u':'USD'}
		suggar_names 	= {'j': "Yenes(¥)",	'c':"CAD (C)",	'u':"USA(U$S)"}

	if os.path.isfile("currency_calc.rates"):
		with open("currency_calc.rates", "r") as file_open:
			for line in file_open.readlines():
				letter, value = line.split(":")
				exchange[letter] = float(value)
	else:
		exchange		= {'j': 111.079002,	'c': 1.31183,	'u': 1.0}

	#AUXILIARY FUNCITONS
	def exchangeRate(_from,_to):
		return exchange[_to]/exchange[_from]

	def getAllCurrencies():
		url = "https://free.currencyconverterapi.com/api/v5/currencies"
		return_val = []
		try:
			contents = json.loads(urllib.request.urlopen(url).read().decode('utf-8'))["results"]
			return_val = (["{1}({0})".format(cn,contents[cn]['currencyName']) for cn in contents])
		except urllib.error.URLError:
				print("Url error, page unavaiable and/or internet is down.")

		return return_val

	def getExchangeRateUpdate(names):
		update_url = "http://free.currencyconverterapi.com/api/v5/convert?q={}_{}&compact=y"
		exchangeRate = {}

		for key, name in names.items():
			contents = "{}"
			found = False
			try:
				contents = urllib.request.urlopen(update_url.format("USD",name)).read().decode('utf-8')
				found = True
			except urllib.error.URLError:
				print("Url error, currency name is incorrect and/or internet is down.")

			if found:
				jsondata = json.loads(contents)
				exchangeRate[key] = float(jsondata[next(iter(jsondata))]['val'])

		return exchangeRate

	#MAIN
	title = "\033[4m\033[1m~~Offline Currency Calculator~~\033[0m"
	os.system(clear)
	print(title)
	print("For more instructions, write 'instructions'")
	time.sleep(1)
	os.system(clear)
	print(title)

	mode = "u"
	step = 0
	i = ""
	changed_currency_names = False
	changed_currency_values = False
	under   	= "\033[4m"
	flat 		= "\033[0m"

	while i != "exit" and i!='reset':
		options_list = ''.join([x for x in name_tags])
		request_str = '/'.join(["{0}{1}{2}".format(under if l == mode else flat,l.upper(),flat) for l in options_list])
		request = "[{}]>>".format(request_str)

		i = input(request).lower().replace("k","000")
		if step > 2:
			step = 0
			os.system(clear)
			print(title)
			print(request + i)
		step += 1
		if i == "instructions":
			print(instructions)
		elif i == "list":
			n = 30
			clist = (getAllCurrencies())
			while len(clist) > 0:
				nlist = clist[:n]
				clist = clist[n:]
				print(", ".join(nlist))
				input("Press enter to continue")
		elif i == "exchange":
			print (exchange)
		elif i == "change":
			letter = input("Write letter: [example C for canadian Dollars]").lower()
			assert(len(letter) == 1)
			if letter in list(options_list):
				value = input("Write new value of currency vs USD: [example 1.31 for canadian Dollars]")
				exchange[letter] = float(value)
				changed_currency_values = True
		elif i == "update":
			exchange = getExchangeRateUpdate(name_tags)
			changed_currency_values = True
		elif i == "add":
			letter = input("Write letter: [example C for canadian Dollars]").lower()
			assert(len(letter) == 1)
			tag    = input("Write currency abreviation: [example CAD for Canadian Dollars]").upper()
			suggar = input("<optional> Write a name for the currency: [example Canadian for Canadian Dollars]")
			suggar = tag if suggar  == "" else suggar
			name_tags[letter] = tag
			suggar_names[letter] = suggar
			exchange = getExchangeRateUpdate(name_tags)
			changed_currency_names = True
			changed_currency_values = True
		elif i == "remove":
			if len(name_tags) < 3:
				print("Can not have less than 2 currencies")
			else:
				letter = input("Select letter to remove: (leave empty to cancel)  ").lower()
				if letter != "":
					del name_tags[letter]
					del suggar_names[letter]
					if letter == mode:
						mode = next(iter(name_tags))
					changed_currency_names = True
					changed_currency_values = True
		elif i in list(options_list):
			mode = i
		elif i.isnumeric():
			n = float(i)
			for l in options_list:
				print("{:<8}: {:.2f}".format(suggar_names[l], (n * exchangeRate(mode,l))))
			print("")

	if i == 'reset':
		changed_currency_names = False
		changed_currency_values = False
		if os.path.isfile("currency_calc.names"):
			os.remove("currency_calc.names")
		if os.path.isfile("currency_calc.rates"):
			os.remove("currency_calc.rates")

	if changed_currency_names or changed_currency_values:
		if input("Do you want to save changes? (Yes/No)").lower() in ["y","yes"]:
			problems = False

			if changed_currency_names:
				try:
					with open("currency_calc.names", "w") as file_open:
						for key,value in name_tags.items():
							print("{}:{}:{}".format(key,value, suggar_names[key]), file = file_open)
				except:
					print("CCN failure")
					problems = True

			if not problems:
				try:
					with open("currency_calc.rates", "w") as file_open:
						for key,value in exchange.items():
							print("{}:{}".format(key,value), file = file_open)
					print("Changes saved")
				except:
					print("CCR failure")
					problems = True

			if problems:
				print("Something went wrong when storing the file(s), changes not properly saved")
				print("Hint: you may need a 'Reset'")
		else:
			print("Changes not saved")

	input("PRESS ENTER TO CLOSE")


import numpy as np
import sys
import cv2

def func5():
    mat1 = np.array(np.arange(12)).reshape(3, 4)

    print('mat1:')
    print(mat1)

    h, w = mat1.shape[:2]

    mat2 = np.zeros(mat1.shape, type(mat1))

    for j in range(h):
        for i in range(w):
            mat2[j, 1] = mat1[j, i] + 10

    print('mat2:')
    print(mat2)

if __name__ == '__main__':
    func5()


import pandas as pd

__author__ = 'Darryl Oatridge'

class FeatureBuilders(object):
    """A set of methods to help build features as pandas.Dataframe"""

    @staticmethod
    def flatten_categorical(df, key, column, prefix=None, index_key=True, dups=True) -> pd.DataFrame:
        """ flattens a categorical as a sum of one-hot

        :param df: the pandas.DataFrame to be cleaned
        :param key: the key column to sum on
        :param column: the category type column break into the category columns
        :param prefix: a prefix for the category columns
        :param index_key: set the key as the index. Default to True
        :param dups: id duplicates should be removed from the origional df
        :return: a pd.Dataframe of the flattened categorical
        """
        if key not in df:
            raise NameError("The key {} can't be found in the DataFrame".format(key))
        if column not in df:
            raise NameError("The column {} can't be found in the DataFrame".format(column))
        if df[column].dtype.name != 'category':
            raise TypeError("the column {} is not of dtype category".format(column))
        if prefix is None:
            prefix = 'HOT'
        if not dups:
            df.drop_duplicates(inplace=True)
        dummy_df = pd.get_dummies(df[[key, column]], columns=[column], prefix=prefix)
        dummy_cols = dummy_df.columns[dummy_df.columns.to_series().str.contains('{}_'.format(prefix))]
        dummy_df = dummy_df.groupby([pd.Grouper(key=key)])[dummy_cols].sum()
        if index_key:
            dummy_df = dummy_df.set_index(key)
        return dummy_df

    @staticmethod
    def date_matrix(df, key, column, index_key=True) -> pd.DataFrame:
        """ returns a pandas.Dataframe of the datetime broken down

        :param df: the pandas.Dataframe to take the columns from
        :param key: the key column
        :param column: the date column
        :param index_key: if to index the key. Default to True
        :return: a pandas.DataFrame of the datetime breakdown
        """
        if key not in df:
            raise NameError("The key {} can't be found in the DataFrame".format(key))
        if column not in df:
            raise NameError("The column {} can't be found in the DataFrame".format(column))
        if not df[column].dtype.name.startswith('datetime'):
            raise TypeError("the column {} is not of dtype datetime".format(column))
        df_time = df.filter([key, column], axis=1)
        df_time['{}_yr'.format(column)] = df[column].dt.year
        df_time['{}_dec'.format(column)] = (df[column].dt.year - df[column].dt.year % 10).astype('category')
        df_time['{}_mon'.format(column)] = df[column].dt.month
        df_time['{}_day'.format(column)] = df[column].dt.day
        df_time['{}_dow'.format(column)] = df[column].dt.dayofweek
        df_time['{}_hr'.format(column)] = df[column].dt.hour
        df_time['{}_min'.format(column)] = df[column].dt.minute
        df_time['{}_woy'.format(column)] = df[column].dt.weekofyear
        df_time['{}_doy'.format(column)] = df[column].dt.dayofyear

        if index_key:
            df_time = df_time.set_index(key)
        return df_time

    @staticmethod
    def merge(df_left, df_right, how='inner', on=None, left_on=None, right_on=None, left_index=False,
              right_index=False, sort=True, suffixes=('_x', '_y'), indicator=False, validate=None):
        """ converts columns to object type

        :param left: A DataFrame object.
        :param right: Another DataFrame object.
        :param on: Column or index level names to join on. Must be found in both the left and right DataFrame objects.
                If not passed and left_index and right_index are False, the intersection of the columns in the
                DataFrames will be inferred to be the join keys.
        :param left_on: Columns or index levels from the left DataFrame to use as keys. Can either be column names,
                index level names, or arrays with length equal to the length of the DataFrame.
        :param right_on: Columns or index levels from the right DataFrame to use as keys. Can either be column names,
                index level names, or arrays with length equal to the length of the DataFrame.
        :param left_index: If True, use the index (row labels) from the left DataFrame as its join key(s). In the case
                of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join
                keys from the right DataFrame.
        :param right_index: Same usage as left_index for the right DataFrame
        :param how: One of 'left', 'right', 'outer', 'inner'. Defaults to inner.
        :param sort: Sort the result DataFrame by the join keys in lexicographical order. Defaults to True, setting
                to False will improve performance substantially in many cases.
        :param suffixes: A tuple of string suffixes to apply to overlapping columns. Defaults to ('_x', '_y').
        :param in place: Always copy data (default True) from the passed DataFrame objects, even when reindexing is
                not necessary. Cannot be avoided in many cases but may improve performance / memory usage. The cases
                where copying can be avoided are somewhat pathological but this option is provided nonetheless.
        :param validate : string, default None. If specified, checks if merge is of specified type.
                    “one_to_one” or “1:1”: checks if merge keys are unique in both left and right datasets.
                    “one_to_many” or “1:m”: checks if merge keys are unique in left dataset.
                    “many_to_one” or “m:1”: checks if merge keys are unique in right dataset.
                    “many_to_many” or “m:m”: allowed, but does not result in checks.
        :param inplace: if the passed pandas.DataFrame should be used or a deep copy
        :return: if inplace, returns a formatted cleaner contract for this method, else a deep copy pandas.DataFrame.
        """
        df = pd.merge(left=df_left, right=df_right, how=how, on=on, left_on=left_on, right_on=right_on,
                      left_index=left_index, right_index=right_index, copy=True, sort=sort, suffixes=suffixes,
                      indicator=indicator, validate=validate)
        return df

    @staticmethod
    def binning(df, column, bins, labels=None):
        # return pd.cut()
        pass

    def timeseries_rolling(self):
        pass


"""atus_api URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""

from django.conf.urls import include, url
from django.contrib import admin

from api import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'respondents', views.RespondentViewSet, base_name='respondent')
router.register(r'activity-codes', views.ActivitiesViewSet)

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^', include(router.urls)),
    url(r'^respondents/(?P<pk>\d+)/household-members/$', views.HouseholdMemberListCreateView.as_view(),
        name="householdmember-list"),
    url(r'^household-members/(?P<pk>\d+)/$', views.HouseholdMemberDetailView.as_view(),
        name="householdmember-detail"),
    url(r'^respondents/(?P<pk>\d+)/activity-codes/$', views.RespondentActivitiesListCreateView.as_view(),
        name='member-activities-list'),
    url(r'^activity-instance/(?P<pk>\d+)/$', views.ActivityInstanceDetailView.as_view(),
        name="activityinstances-detail"),
    url(r'^activity-instance-data/(?P<pk>\d+)/$', views.ActivitiesDataView.as_view(),
        name="activity-data-detail"),
]


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-850 -*-

#Titulo				:caracterizarv0_1.py
#Descripción		:Programa de caracterización.
#Autor          	:Javier Campos Rojas
#Fecha            	:enero-2017
#Versión         	:3.6
#Notas          	:
#==============================================================================

from graphics import *
from button import *
import serialKepco_tmsv3 as SK
from HarmGenv2 import *
import matplotlib.pyplot as plt
import numpy as np
import math
import io
import base64
import Tkinter as tk
from urllib2 import urlopen
import glob ##### para buscar los puertos USB disponibles
import controlTektronix as CT
import RPi.GPIO as GPIO
import SensorVC_v2 as VC
global GPIO
global SK
global CT
global VC

def main():
	##Relay##
	relay=14;
	GPIO.setwarnings(False);
	GPIO.setmode(GPIO.BCM)
	GPIO.setup(relay, GPIO.OUT,initial=GPIO.LOW)

	xgrid=30;
	ygrid=10;
	refy=19;
	refx=2;
	refx2=11;
	width_b=2.5;
	heigh_b=1.8;
	Tm=0.0005;
	puertos=glob.glob('/dev/tty[U]*')
	try:
		puerto1 = puertos[0]
	except IndexError:
		puerto1 = 'no hay dispositivo'
	try:
		puerto2 = puertos[1]
	except IndexError:
		puerto2 = 'no hay dispositivo'

	win = GraphWin("Caracterizador",width=400, height=350)
	win.setCoords(0,0,ygrid,xgrid)
	#win.setBackground('#BCC6CC')
	myImage = Image(Point(5,15), 'backg2.gif')
	myImage.draw(win)
	LogoSESLab = Image(Point(5,27), 'SESLab.gif')
	LogoSESLab.draw(win)

	line = Line(Point(0, refy+2), Point(ygrid,refy+2))
	line.setFill("white")
	line.setWidth(2)
	line.draw(win)

	line2 = Line(Point(0, refy-11.5), Point(ygrid,refy-11.5))
	line2.setFill("white")
	line2.setWidth(2)
	line2.draw(win)

	line3 = Line(Point(0, refy-14.5), Point(ygrid,refy-14.5))
	line3.setFill("white")
	line3.setWidth(2)
	line3.draw(win)

	connects1 = Button(win, Point(refx-0.5,refy-13), width_b, heigh_b, "Conectar")
	connects1.activate()

	caracterizar = Button(win, Point(refx+3,refy-13), width_b, heigh_b, "Caracterizar")
	#caracterizar.activate()

	Salir = Button(win, Point(refx+6.5,refy-13), width_b, heigh_b, "Salir")
	Salir.activate()

	###############################---Datos Fuente 1---###############################
		################## Frecuencia 1 ##################

	freq=Text(Point(refx,refy),"Frecuencia(Hz): ")
	freq.setFace('arial')
	freq.setStyle('bold')
	freq.setSize(12)
	#freq.setTextColor("#8EB84A")
	freq.setTextColor("white")
	freq.draw(win)

	freq_val=Entry(Point(refx+5,refy),20)
	freq_val.setFace('arial')
	freq_val.setSize(10)
	freq_val.setTextColor("white")
	freq_val.setFill('#6B6B6B')
	freq_val.draw(win)

		################## Tensión 1 ##################

	volt=Text(Point(refx,refy-3),"Tensión(V): ")
	volt.setFace('arial')
	volt.setStyle('bold')
	volt.setSize(12)
	volt.setTextColor("white")
	volt.draw(win)

	volt_val=Entry(Point(refx+5,refy-3),20)
	volt_val.setFace('arial')
	volt_val.setSize(10)
	volt_val.setTextColor("white")
	volt_val.setFill('#6B6B6B')
	volt_val.draw(win)

		################## Corriente 1 ##################

	curr=Text(Point(refx,refy-6),"Corriente(A): ")
	curr.setFace('arial')
	curr.setStyle('bold')
	curr.setSize(12)
	curr.setTextColor("white")
	curr.draw(win)

	curr_val=Entry(Point(refx+5,refy-6),20)
	curr_val.setFace('arial')
	curr_val.setSize(10)
	curr_val.setTextColor("white")
	curr_val.setFill('#6B6B6B')
	curr_val.draw(win)

		################## Periodos 1 ##################

	period=Text(Point(refx,refy-9),"Δt de barrido(s): ")
	period.setFace('arial')
	period.setStyle('bold')
	period.setSize(12)
	period.setTextColor("white")
	period.draw(win)

	period_val=Entry(Point(refx+5,refy-9),20)
	period_val.setFace('arial')
	period_val.setSize(10)
	period_val.setTextColor("white")
	period_val.setFill('#6B6B6B')
	period_val.draw(win)

		################## Puerto Serial 1 ##################

	port1_name=Text(Point(refx,refy+4),"Puerto Serial 1: ")
	port1_name.setFace('arial')
	port1_name.setStyle('bold')
	port1_name.setSize(12)
	port1_name.setTextColor("white")
	port1_name.draw(win)

	port1_val=Entry(Point(refx+5,refy+4),20)
	port1_val.setFace('arial')
	port1_val.setSize(10)
	port1_val.setTextColor("white")
	port1_val.setFill('#6B6B6B')
	port1_val.setText(puerto1)
	port1_val.draw(win)

		################## Mensaje de lectura ##################
	mensaje=Text(Point(5,2),"")
	mensaje.setFace('arial')
	mensaje.setStyle('bold')
	mensaje.setSize(11)
	mensaje.setTextColor("black")
	mensaje.draw(win)

	def rutinaDeltaf(V,f,C,n,fuente):
		for i in range(int(f)-5,int(f)+5):
			fuente.WriteVoltSine(V,i,i*n,C)
			time.sleep(1);
	def rutinaDeltaV(V,f,C,n,fuente):
		for i in range(int(V),int(V)+15):
			fuente.WriteVoltSine(i,f,f*n,C)
			time.sleep(1);
		for i in range(int(V)+15,int(V)-15,-1):
			fuente.WriteVoltSine(i,f,f*n,C)
			time.sleep(1);

	pt = win.getMouse()
	a=1;
	while not Salir.clicked(pt):
		puertos=glob.glob('/dev/tty[U]*')
		try:
			puerto1 = puertos[0]
		except IndexError:
			puerto1 = 'no hay dispositivo'
		port1_val.setText(puerto1)
		if connects1.clicked(pt):
			port1=port1_val.getText()
			kepco1=SK.Source("Fuente1",port1)
			m1=kepco1.connectport()
			m2=kepco1.identify()
			mensaje.setText(m1 + m2)
			caracterizar.activate()
		if caracterizar.clicked(pt):
			GPIO.output(relay, GPIO.LOW);
			time.sleep(0.2)
			n=float(period_val.getText())
			f=float(freq_val.getText())
			V=float(volt_val.getText())
			C=float(curr_val.getText())
			#ts=float(tsm.getText())
			Salir.deactivate()
			mensaje.setText("Caracterizando...")
			osc1=CT.getWave();
			#meas=VC.Sensor();
			meas=VC.Sensor(55*(1+n));
			alerta1=osc1.connectOsc()
			mensaje.setText("Caracterizando..."+'\n'+alerta1)
			alerta2=osc1.OscWave()
			mensaje.setText("Caracterizando..."+'\n'+alerta2)
			meas.start();
			#meas.CurrMeas(55*(1+n));
			##Rutina Barrido de Frecuencias##
			osc1=CT.getWave();
			rutinaDeltaf(V,f,C,n,kepco1);
			osc1=CT.getWave();
			rutinaDeltaV(V,f,C,n,kepco1)
			osc1=CT.getWave();
			##Rutina Barrido de Desconexion##
			GPIO.output(relay, GPIO.HIGH);
			time.sleep(1);
			GPIO.output(relay, GPIO.LOW);
			Salir.activate()
			mensaje.setText("¡Caracterización lista!")
		pt = win.getMouse()
	win.close()
main()


import csv
from DB_schema import OrthologEcoli, Interaction, InteractionReference, Metabolite, InteractionSource
from DB_build import is_experimental_psimi

def parse_ecoli_uniprot(session):
    with open('Ecoli/PSICQUIC/UniProt.txt') as csvfile:
        reader = csv.DictReader(csvfile, delimiter='\t')
        for row in reader:
            interactors = []
            orthologs_B = []
            id_B = row['ID(s) interactor B'].split(':')
            if id_B[0] == 'uniprotkb':
                orthologs_B = session.query(OrthologEcoli).filter(OrthologEcoli.ortholog_uniprot == id_B[1]).all()

            if len(orthologs_B) == 0: continue

            orthologs_A = []
            metabolite = None
            id_A = row['#ID(s) interactor A'].split(':')
            if id_A[0] == 'uniprotkb':
                orthologs_A = session.query(OrthologEcoli).filter(OrthologEcoli.ortholog_uniprot == id_A[1]).all()
            elif id_A[0] == 'chebi':
                metabolite = session.query(Metabolite).filter(Metabolite.chebi == id_A[1]).first()
                if metabolite is None:
                    metabolite = Metabolite(id=id_A[1], chebi=id_A[1])
                    session.add(metabolite), session.commit()

            for ortholog_A in orthologs_A:
                for ortholog_B in orthologs_B:
                    if (ortholog_A is not None) and (ortholog_B is not None):
                        if ortholog_A.strain_protein == ortholog_B.strain_protein:
                            interactors.append([[ortholog_A.protein, ortholog_A.ortholog_id],
                                                [ortholog_B.protein, ortholog_B.ortholog_id]])

            if metabolite is not None:
                for ortholog_B in orthologs_B:
                    interactors.append([[metabolite, metabolite.id], [ortholog_B.protein, ortholog_B.ortholog_id]])

            for interactor_pair in interactors:
                homogenous = (interactor_pair[0][0] == interactor_pair[1][0])
                interaction = session.query(Interaction).filter(Interaction.interactors.contains(interactor_pair[0][0]),
                                                                Interaction.interactors.contains(interactor_pair[1][0]),
                                                                Interaction.homogenous == homogenous).first()
                if interaction is not None:
                    if interaction.ortholog_derived is None:
                        interaction.ortholog_derived = 'cfe'
                    elif 'fe' not in interaction.ortholog_derived:
                        interaction.ortholog_derived += ', cfe'
                    session.commit()
                else:
                    interaction = Interaction(strain=interactor_pair[0][0].strain,
                                              interactors=[interactor_pair[0][0], interactor_pair[1][0]],
                                              type=(interactor_pair[0][0].type + '-' + interactor_pair[1][0]),
                                              ortholog_derived='fe')
                    if 'MI:' in row['Interaction detection method(s)']:
                        if is_experimental_psimi(row['Interaction detection method(s)'].split('MI:')[1][:4]):
                            interaction.is_experimental = 1
                    session.add(interaction), session.commit()

                interactor_a, interactor_b = None, None
                if interaction.interactors[0] == interactor_pair[0][0]:
                    interactor_a = interactor_pair[0][1]
                    interactor_b = interactor_pair[1][1]
                else:
                    interactor_b = interactor_pair[0][1]
                    interactor_a = interactor_pair[1][1]

                reference = InteractionReference(interaction_id=interaction.id,
                                                 psimi_detection=
                                                 row['Interaction detection method(s)'].split('MI:')[1][:4],
                                                 detection_method=row['Interaction detection method(s)'].split('(')[
                                                                      1][:-1],
                                                 author_ln=row['Publication 1st author(s)'].split(' ')[0],
                                                 pub_date=row['Publication 1st author(s)'].split('(')[1][:-1],
                                                 pmid=
                                                 row['Publication Identifier(s)'].split('pubmed:')[1].split('|')[0],
                                                 psimi_type=
                                                 row['Interaction type(s)'].split('MI:')[1][:4],
                                                 interaction_type=row['Interaction type(s)'].split('(')[1][:-1],
                                                 psimi_db=row['Source database(s)'].split('MI:')[1][:4],
                                                 source_db=row['Source database(s)'].split('(')[1][:-1],
                                                 confidence_score=row['Confidence value(s)'],
                                                 interactor_a_id=interactor_a,
                                                 interactor_b_id=interactor_b)
                session.add(reference)

                source = session.query(InteractionSource).filter(InteractionSource.interaction_id == interaction.id,
                                                                 InteractionSource.data_source == 'UniProt').first()

                if source is None:
                    source = InteractionSource(interaction_id=interaction.id, data_source='UniProt')
                    session.add(source)

        session.commit()
        print(session.query(Interaction).count())


import os
import configobj
from unittest import TestCase
import mock

try:
    from StringIO import StringIO
except ImportError:
    # Python 3
    from io import StringIO

try:
    import __builtin__
    builtin_module_name = '__builtin__'
except ImportError:
    # Python 3
    builtin_module_name = 'builtins'

from dvc.cloud.data_cloud import DataCloud
from dvc.cloud.aws import DataCloudAWS
from dvc.cloud.gcp import DataCloudGCP
from dvc.main import main
from tests.basic_env import TestDvc

class TestConfigTest(TestCase):
    def setUp(self):
        pass

    def _conf(self, s):
        c = configobj.ConfigObj(s)
        return c

    def storage_path_hierarchy_test(self):
        """ StoragePath should be read first from global and then from cloud section """

        c = ("[core]",
             "loglevel =",
             "cloud = aws",
             "storagepath = globalsb/global_storage_path",
             "[aws]",
             "storagepath = awssb/aws_storage_path",
             "credentialpath =",
             "[gcp]",
             "storagepath = googlesb/google_storage_path"
           )
        s = StringIO('\n'.join(c))
        conf = self._conf(s)
        cloud = DataCloud(None, conf)
        self.assertIsInstance(cloud._cloud, DataCloudAWS)
        self.assertEqual(cloud._cloud.storage_bucket, 'globalsb')
        self.assertEqual(cloud._cloud.storage_prefix, 'global_storage_path')

        c = ("[core]",
             "loglevel =",
             "cloud = Aws",
             "[aws]",
             "storagepath = awssb/aws_storage_path",
             "credentialpath =",
             "[gcp]",
             "storagepath = googlesb/google_storage_path"
           )
        s = StringIO('\n'.join(c))
        conf = self._conf(s)
        cloud = DataCloud(None, conf)
        self.assertIsInstance(cloud._cloud, DataCloudAWS)
        self.assertEqual(cloud._cloud.storage_bucket, 'awssb')
        self.assertEqual(cloud._cloud.storage_prefix, 'aws_storage_path')

    def mocked_open_aws_default_credentials(klass, file, asdf):
        """ mocked open for ~/.aws/credentials """
        if file == os.path.expanduser('~/.aws/credentials'):
            creds0 = ("[default]",
                      "aws_access_key_id = default_access_id",
                      "aws_secret_access_key = default_sekret")
            return StringIO('\n'.join(creds0))

        creds1 = ("[default]",
                  "aws_access_key_id = override_access_id",
                  "aws_secret_access_key = override_sekret")

        return StringIO('\n'.join(creds1))

    def aws_credentials_default_tes_t_DISABLED(self):
        """ in absence of [AWS] -> CredentialPath, aws creds should be read from ~/.aws/credentials """

        default_path = os.path.expanduser('~/.aws/credentials')
        c = ("[core]",
             "loglevel =",
             "cloud = aws",
             "[aws]",
             "storagepath = awssb/aws_storage_path",
             "credentialpath =",
           )
        s = StringIO('\n'.join(c))

        patcher = mock.patch(builtin_module_name + '.open', side_effect=self.mocked_open_aws_default_credentials)

        # patcher.start()
        conf = self._conf(s)
        cloud = DataCloud(None, conf)
        aws_creds = cloud._cloud._get_credentials()
        patcher.stop()

        self.assertEqual(aws_creds[0], 'default_access_id')
        self.assertEqual(aws_creds[1], 'default_sekret')

    def mocked_isfile(file):
        """ tell os some_credential_path exists """
        return file == 'some_credential_path'

    @mock.patch('dvc.config.os.path.isfile', side_effect = mocked_isfile)
    def aws_credentials_specified_tes_t_DISABLED(self, isfile_function):
        """ in presence of [AWS] -> CredentialPath, use those credentials """

        c = ("[core]",
             "loglevel =",
             "cloud = aws",
             "[aws]",
             "storagePath = awssb/aws_storage_path",
             "credentialpath = some_credential_path",
           )
        s = StringIO('\n'.join(c))

        patcher = mock.patch(builtin_module_name + '.open', side_effect=self.mocked_open_aws_default_credentials)

        patcher.start()
        conf = self._conf(s)
        cloud = DataCloud(None, conf)
        aws_creds = cloud._cloud._get_credentials()
        patcher.stop()

        self.assertEqual(aws_creds[0], 'override_access_id')
        self.assertEqual(aws_creds[1], 'override_sekret')

class TestConfigCLI(TestDvc):
    def _contains(self, section, field, value):
        config = configobj.ConfigObj(self.dvc.config.config_file)
        if section not in config.keys():
            return False

        if field not in config[section].keys():
            return False

        if config[section][field] != value:
            return False

        return True

    def test(self):
        section = 'setsection'
        field = 'setfield'
        section_field = '{}.{}'.format(section, field)
        value = 'setvalue'
        newvalue = 'setnewvalue'

        ret = main(['config', section_field, value])
        self.assertEqual(ret, 0)
        self.assertTrue(self._contains(section, field, value))

        ret = main(['config', section_field])
        self.assertEqual(ret, 0)

        ret = main(['config', section_field, newvalue])
        self.assertEqual(ret, 0)
        self.assertTrue(self._contains(section, field, newvalue))
        self.assertFalse(self._contains(section, field, value))

        ret = main(['config', section_field, '--unset'])
        self.assertEqual(ret, 0)
        self.assertFalse(self._contains(section, field, value))

    def test_non_existing(self):
        #FIXME check stdout/err

        ret = main(['config', 'non_existing_section.field'])
        self.assertEqual(ret, 1)

        ret = main(['config', 'global.non_existing_field'])
        self.assertEqual(ret, 1)

        ret = main(['config', 'non_existing_section.field', '-u'])
        self.assertEqual(ret, 1)

        ret = main(['config', 'global.non_existing_field', '-u'])
        self.assertEqual(ret, 1)


# using two sets
# Time: O(N)

def intersection2(arr1, arr2):
	array1 = set(arr1)
	result = set()

	for num in arr2:
		if num in array1:
			result.add(num)

	return list(result)

print(intersection2([1, 2, 3, 4], [5, 6, 7, 2, 5, 2]))

# Binary search
# Time: O(N log N)

def intersection4(arr1, arr2):
	result = set()
	arr2.sort()
	for num in arr1:
		binary_search(arr2, num, 0, len(arr2) - 1, result)

	return list(result)

def binary_search(arr2, num, start, end, result):
	if start <= end:
		mid = (start + end)//2
		if arr2[mid] == num:
			result.add(num)
			return result
		elif arr2[mid] > num:
			binary_search(arr2, num, start, mid - 1, result)
		elif arr2[mid] < num:
			binary_search(arr2, num, mid + 1, end, result)

	return result

print(intersection4([1, 2, 3, 4], [5, 6, 7, 2, 5, 2, 4]))

# sorting and using two pointers

def intersection3(arr1, arr2):
	result = set()
	arr1.sort()
	arr2.sort()

	i, j = 0, 0

	while i < len(arr1) and j < len(arr2):
		if arr1[i] < arr2[j]:
			i += 1
		elif arr1[i] > arr2[j]:
			j += 1
		else:
			result.add(arr1[i])
			i += 1
			j += 1

	return list(result)

print(intersection3([1, 2, 3, 4], [5, 6, 7, 2, 5, 2]))

# using bitwise &

def intersection(arr1, arr2):
	num1 = set(arr1)
	num2 = set(arr2)

	return list(num1&num2)

#print(intersection([1, 2, 3, 4], [5, 6, 7, 2, 5, 2]))


# -*- coding: utf-8 -*-
"""
Tools to store results of simulations.

Created on Mon Feb 10 11:47:00 2020

@author: Administrator
"""

# =============================================================================
# %% IMPORTS
# =============================================================================
import os
from errno import EEXIST
import h5py

import numpy as np

# =============================================================================
# %% FUNCTION DEFINITIONS
# =============================================================================

def mkdir_p(mypath):
    """
    Creates a directory. equivalent to using mkdir -p on the command line.
    Source: https://stackoverflow.com/questions/11373610/save-matplotlib-file-to-a-directory

    Parameters
    ----------
    mypath : string
        path of directories that have to be created.

    Returns
    -------
    None.

    """
    try:
        os.makedirs(mypath)
    except OSError as exc:
        if exc.errno == EEXIST and os.path.isdir(mypath):
            pass
        else: raise

def check_extension(path, ext):
    """
    Asserts that the given path ends with a specified extension.

    Parameters
    ----------
    path : str
        Path to file.
    ext : str
        File extension.

    Returns
    -------
    path : str
        Path with specified extension.

    """
    if not path.endswith(ext):
        if ext[0] == ".":
            path += ext
        else:
            path += "."+ext
    return path

def write_results_hdf5(filename,
                       metadata,
                       separate_metadata = True,
                       group = "/",
                       **results):
    """
    Writes simulation results to a hdf5 file. If the given filename refers to
    an existing file, then the data are appended, otherwise a new file is
    created.

    Parameters
    ----------
    filename : str
        Path to file.
    metadata : dict
        Metadata of the results.
    group : str, optional
        If given, this specifies a group in the hdf5 file, where the results have to be stored.
        If None is given, the results are stored in the main file and the
        metadata are stored as attributes of a "metadata" group.
        The default is root.
    **results : ndarrays
        arrays that have to be written to the hdf5 file.

    Returns
    -------
    filename : str
        Path to hdf5 file.

    """
    # Write (on) file
    #==========================================================================
    filename = check_extension(filename,"hdf5")
    with h5py.File(filename, mode = "a") as file:
        try:
            # group doesn't exsist yet
            results_group = file.create_group(group)
        except ValueError:
            # group already exists
            results_group = file[group]

        if separate_metadata:
            # Add metadata to a group named ""metadata"
            #------------------------------------------------------
            try:
                # group doesn't exsist yet -> make new metadata subgroup
                metadata_group = results_group.create_group("metadata")
            except ValueError:
                # group already exists
                metadata_group = results_group["metadata"]
            add_metadata_as_attributes(metadata_group, metadata)

        # Add results to file
        #------------------------------------------------------
        for resultname, result in results.items():
            results_group.create_dataset(resultname,data=result)
            if not separate_metadata:
                try:
                    add_metadata_as_attributes(results_group, metadata[resultname])
                except KeyError:
                    add_metadata_as_attributes(results_group, metadata)
    return filename

def add_metadata_as_attributes(metadata_group, metadata_dict):
    """
    Adds metadata to group in hdf5 file.

    If metadata is a dict of dicts, then separate subgroups are created for
    which the items of the subdicts are stored as attributes.

    Parameters
    ----------
    metadata_group : hdf5 group
        group where metadata are stored as attributes.
    metadata_dict : dict
        dict with names and values of metadata.

    Returns
    -------
    None.

    """
    for mdg_name, mdg_val in metadata_dict.items():
                if isinstance(mdg_val, dict): # if dict in dict: create subgroup
                    metadata_subgroup = metadata_group.create_group(mdg_name)
                    add_metadata_as_attributes(metadata_subgroup, mdg_val)
                else:
                    try:
                        metadata_group.attrs[mdg_name] = mdg_val
                    except TypeError as te:
                        print(mdg_name)
                        print(mdg_val)
                        raise te

def load_results_hdf5(filename, result_names, group = "/"):
    """
    Loads results, stored in hdf5 file.

    Parameters
    ----------
    filename : string
        Path to file.
    result_names : list
        List contraining the names (`str`) of the datasets which have to be loaded.
    group : string or Nonetype, optional
        Group in which the datasets are stored.
        If None, the results are being looked for at the root.
        The default is None.

    Returns
    -------
    results : list
        Datasets loaded from the hdf5 file.

    """
    filename = check_extension(filename,"hdf5") # asserts that the filename ends with the hdf5 extension
    results = []
    with h5py.File(filename, mode = "r") as file:
        for dataset in result_names:
            results.append(file[group][dataset][()]) # get values from dataset
    return results

def load_group_metadata_hdf5(filename, group = "/"):
    """
    Loads specific metadata of hdf5 file as a dict.

    Parameters
    ----------
    filename : string
        Path to file.
    group : string or Nonetype, optional
        Group in which the datasets are stored.
        If None, the results are being looked for at the root.
        The default is root.

    Returns
    -------
    dict
        Loaded metadata.

    """
    filename = check_extension(filename,"hdf5") # asserts that the filename ends with the hdf5 extension
    with h5py.File(filename, mode = "r") as file:
        return dict(file[group].attrs)

def show_contents_hdf5(filename,
                       groups = None,
                       f_md_ndarray = lambda a:"{}".format(type(a))):
    """
    Prints the contents of an hdf5 file, created with `write_results_hdf5` where
    separate_metadata == True.
    Parameters
    ----------
    filename : string
        Path to file..
    groups : list or Nonetype, optional
        Groups that have to be printed. If None, al groups in the file are printed.
        The default is None.
    f_md_ndarray : function, optional
        Function to format ndarray in the metadata.
        The default is lambda a:"{}".format(type(a)).

    Returns
    -------
    None.

    """
    def print_attributes(group, f_md_ndarray):
        """
        Auxilary function.
        """
        attr = dict(group.attrs)
        for a,val in attr.items():
            if isinstance(val, np.ndarray):
                print(f"\t- {a:15s}:\t"+f_md_ndarray(val))
            else:
                print(f"\t- {a:15s}:\t{val}")

    filename = check_extension(filename,"hdf5") # asserts that the filename ends with the hdf5 extension
    line_len = 50
    with h5py.File(filename, mode = "r") as file:
        # header: file name
        #-------------------
        print()
        print(filename)
        print("_"*line_len, end = "\n\n\n")
        if groups is None:
            groups = ["/"] # if no groups are given: groups = root
        for g in groups:
            if g != "/":
                print("#"*line_len)
                print(g)
                print("#"*line_len)

            group = file[g]

            print("\nMetadata")
            print("="*line_len)

            metadata_group = group["metadata"]
            print_attributes(metadata_group,f_md_ndarray)

            for subgroup in metadata_group:
                print("-"*line_len)
                print("|-"+subgroup)
                print("-"*line_len)
                print_attributes(metadata_group[subgroup],f_md_ndarray)

            print("\nDatasets")
            print("="*line_len)
            datasets = {}
            for obj in group:
                if isinstance(group[obj], h5py._hl.dataset.Dataset):
                    try:
                        obj_splitted = obj.split("_")
                        assert len(obj_splitted) > 1
                        prefix = "_".join(obj_splitted[0:-1])
                        suffix = obj_splitted[-1]
                        datasets[prefix].append(suffix)
                    except KeyError:
                        datasets[prefix] = [suffix]
                    except AssertionError:
                        datasets[obj] = []
            for ds in datasets:
                try:
                    suffixes = sorted(datasets[ds], key = int)
                    suffixes = ", ".join(suffixes)
                    print(f"{ds}_[{suffixes}]")
                except ValueError:
                    print(f"{ds}")

def show_all_contents_hdf5(filename):
    """
    Prints contents of hdf5 file.

    Parameters
    ----------
    filename : str
        Path to hdf5 file.

    Returns
    -------
    None.

    """

    filename = check_extension(filename,"hdf5") # asserts that the filename ends with the hdf5 extension
    line_len = 50

    def print_attrs(name, obj):
        """
        Auxilary function, used in visititems method.

        """
        name_split = name.split("/")
        level = len(name_split)
        if isinstance(obj, h5py._hl.dataset.Dataset):
            name_print = f"{name_split[-1]} : ndarray shape {obj.shape}, type {obj.dtype}"
        else:
            name_print = name_split[-1]
        print("|  "*(level-1)+"|-", name_print)
        for key, val in obj.attrs.items():
            print("|  "*level+"|---", f"{key:15s}\t: {val}")

    print(filename)
    print("="*line_len)
    with h5py.File(filename, mode = "r") as file:
        file.visititems(print_attrs)


# coding: utf-8
# @Author  : wenbin
# @Time    : 2020/3/18 上午10:57
# @Software: PyCharm
# @File    : queue_test.py

import queue
import time

'''
方法介绍
Queue([maxsize])
创建共享的进程队列。maxsize是队列中允许的最大项数。如果省略此参数，则无大小限制。底层队列使用管道和锁定实现。
另外，还需要运行支持线程以便队列中的数据传输到底层管道中。
Queue的实例q具有以下方法：
q.get( [ block [ ,timeout ] ] )
返回q中的一个项目。如果q为空，此方法将阻塞，直到队列中有项目可用为止。block用于控制阻塞行为，默认为True. 如果设置为False，
将引发Queue.Empty异常（定义在Queue模块中）。
timeout是可选超时时间，用在阻塞模式中。如果在制定的时间间隔内没有项目变为可用，将引发Queue.Empty异常。
q.get_nowait( )
同q.get(False)方法。
q.put(item [, block [,timeout ] ] )
将item放入队列。如果队列已满，此方法将阻塞至有空间可用为止。block控制阻塞行为，默认为True。如果设置为False，
将引发Queue.Empty异常（定义在Queue库模块中）。timeout指定在阻塞模式中等待可用空间的时间长短。超时后将引发Queue.Full异常。
q.qsize()
返回队列中目前项目的正确数量。此函数的结果并不可靠，因为在返回结果和在稍后程序中使用结果之间，队列中可能添加或删除了项目。
在某些系统上，此方法可能引发NotImplementedError异常。
q.empty()
如果调用此方法时 q为空，返回True。如果其他进程或线程正在往队列中添加项目，结果是不可靠的。
也就是说，在返回和使用结果之间，队列中可能已经加入新的项目。
q.full()
如果q已满，返回为True. 由于线程的存在，结果也可能是不可靠的（参考q.empty（）方法）。。
'''
# my_queue = queue.Queue(maxsize=199) # maxsize是设置队列的长度，会报queue.Full异常
# my_queue = queue.Queue(maxsize=200) # maxsize是设置队列的长度，会报queue.Full异常
my_queue = queue.Queue(maxsize=201)  # maxsize是设置队列的长度，会报queue.Full异常
# my_queue = queue.Queue() # 如果不填,maxsize=0，也就是队列长度无大小限制

# with open('queue_data', mode='a+', encoding='utf-8') as file:
# for i in range(1, 201):
#     file.write('data' + str(i) + '\n')

with open('queue_data', mode='r', encoding='utf-8') as file:
    count = 0
    for i in file:
        count += 1
        print('当前队列是否为空：{}'.format(my_queue.empty()))  # 第一次运行时：当前队列是否为空：True
        my_queue.put(i.strip('\n'))
        print('当前队列中的长度：{}'.format(my_queue.qsize()))
        print('my_queue.full:{}, count计数器:{}'.format(my_queue.full(), count))  # my_queue.full:False, count计数器:200
        # my_queue.put(i.strip('\n'), block=False)
        # print('my_queue.full:{}, count计数器:{}'.format(my_queue.full(), count)) # my_queue.full:True, count计数器:199
        # my_queue.put_nowait(i.strip('\n')) # put_nowait(i.strip('\n'))等同于put(i.strip('\n'), block=False)
        # print('my_queue.full:{}, count计数器:{}'.format(my_queue.full(), count)) # my_queue.full:True, count计数器:199

while 1:
    '''
    get_nowait()等同于get(block=False)
    '''
    # data = my_queue.get(block=False) # 当队列中的数据消费完之后，会抛出queue.Empty异常
    # data = my_queue.get_nowait() # 当队列中的数据消费完之后，会抛出queue.Empty异常
    # data = my_queue.get(timeout=5)
    data = my_queue.get()
    # my_queue.put(data) # 消费一个data后再将data放回my_queue中
    print(data)

# 其他方法(了解)
# q.close()
# 关闭队列，防止队列中加入更多数据。调用此方法时，后台线程将继续写入那些已入队列但尚未写入的数据，但将在此方法完成时马上关闭。如果q被垃圾收集，将自动调用此方法。关闭队列不会在队列使用者中生成任何类型的数据结束信号或异常。例如，如果某个使用者正被阻塞在get（）操作上，关闭生产者中的队列不会导致get（）方法返回错误。
# q.cancel_join_thread()
# 不会再进程退出时自动连接后台线程。这可以防止join_thread()方法阻塞。
# q.join_thread()
# 连接队列的后台线程。此方法用于在调用q.close()方法后，等待所有队列项被消耗。默认情况下，此方法由不是q的原始创建者的所有进程调用。调用q.cancel_join_thread()方法可以禁止这种行为。


# Sebastian Raschka, 2015
# Function for sequential feature selection via
# Sequential Backward Selection (SBS)
# mlxtend Machine Learning Library Extensions

from sklearn.base import clone
from sklearn.base import BaseEstimator
from sklearn.base import MetaEstimatorMixin
from itertools import combinations
from sklearn.cross_validation import cross_val_score
import numpy as np

class SBS(BaseEstimator, MetaEstimatorMixin):
    """ Sequential Backward Selection for feature selection.

    Parameters
    ----------
    clfs : scikit-learn estimator object

    k_features : int
      Number of features to select where k_features.

    scoring : str, (default='accuracy')
      Scoring metric for the cross validation scorer.

    cv : int (default: 5)
      Number of folds in StratifiedKFold.

    n_jobs : int (default: 1)
      The number of CPUs to use for cross validation. -1 means 'all CPUs'.

    Attributes
    ----------
    indices_ : array-like, shape = [n_predictions]
      Indices of the selected subsets.

    k_score_ : float
      Cross validation mean scores of the selected subset

    subsets_ : list of tuples
      Indices of the sequentially selected subsets.

    scores_ : list
      Cross validation mean scores of the sequentially selected subsets.

    Examples
    --------
    >>> from sklearn.neighbors import KNeighborsClassifier
    >>> from sklearn.datasets import load_iris
    >>> iris = load_iris()
    >>> X = iris.data
    >>> y = iris.target
    >>> knn = KNeighborsClassifier(n_neighbors=4)
    >>> sbs = SBS(knn, k_features=2, scoring='accuracy', cv=5)
    >>> sbs = sbs.fit(X, y)
    >>> sbs.indices_
    (0, 3)
    >>> sbs.k_score_
    0.96
    >>> sbs.transform(X)
    array([[ 5.1,  0.2],
       [ 4.9,  0.2],
       [ 4.7,  0.2],
       [ 4.6,  0.2],
       [ 5. ,  0.2]])

    """
    def __init__(self, estimator, k_features, scoring='accuracy', cv=5, n_jobs=1):
        self.scoring = scoring
        self.estimator = estimator
        self.cv = cv
        self.k_features = k_features
        self.n_jobs = n_jobs

    def fit(self, X, y):

        dim = X.shape[1]
        self.indices_ = tuple(range(dim))
        self.subsets_ = [self.indices_]
        cv_score = self._calc_score(X, y, self.indices_)
        self.scores_ = [cv_score.mean()]

        while dim > self.k_features:
            scores = []
            subsets = []

            for p in combinations(self.indices_, r=dim-1):
                cv_score = self._calc_score(X, y, p)
                scores.append(cv_score.mean())
                subsets.append(p)

            best = np.argmax(scores)
            self.indices_ = subsets[best]
            self.subsets_.append(self.indices_)
            dim -= 1

            self.scores_.append(scores[best])
        self.k_score_ = self.scores_[-1]

        return self

    def transform(self, X):
        return X[:, self.indices_]

    def fit_transform(self, X, y):
        self.fit(X, y)
        return self.transform(X)

    def _calc_score(self, X, y, indices):
        cv_score = cross_val_score(self.estimator,
                                   X[:, indices], y,
                                   cv=self.cv,
                                   scoring=self.scoring,
                                   n_jobs = self.n_jobs)
        return cv_score


#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
from skimage import color

def candidate_generation_pixel_normrgb(im):
    # convert input image to the normRGB color space

    normrgb_im = np.zeros(im.shape)
    eps_val = 0.00001
    norm_factor_matrix = im[:,:,0] + im[:,:,1] + im[:,:,2] + eps_val

    normrgb_im[:,:,0] = im[:,:,0] / norm_factor_matrix
    normrgb_im[:,:,1] = im[:,:,1] / norm_factor_matrix
    normrgb_im[:,:,2] = im[:,:,2] / norm_factor_matrix

    # Develop your method here:
    # Example:
    pixel_candidates = normrgb_im[:,:,0]>100;

    return pixel_candidates

def candidate_generation_pixel_hsv(im):
    # convert input image to HSV color space
    hsv_im = color.rgb2hsv(im)

    # Develop your method here:
    # Example:
    pixel_candidates = hsv_im[:,:,0] > 0.4;

    return pixel_candidates

# Create your own candidate_generation_pixel_xxx functions for other color spaces/methods
# Add them to the switcher dictionary in the switch_color_space() function
# These functions should take an image as input and output the pixel_candidates mask image

def switch_color_space(im, color_space):
    switcher = {
        'normrgb': candidate_generation_pixel_normrgb,
        'hsv'    : candidate_generation_pixel_hsv
        #'lab'    : candidate_generation_pixel_lab,
    }
    # Get the function from switcher dictionary
    func = switcher.get(color_space, lambda: "Invalid color space")

    # Execute the function
    pixel_candidates =  func(im)

    return pixel_candidates

def candidate_generation_pixel(im, color_space):

    pixel_candidates = switch_color_space(im, color_space)

    return pixel_candidates

if __name__ == '__main__':
    pixel_candidates1 = candidate_generation_pixel(im, 'normrgb')
    pixel_candidates2 = candidate_generation_pixel(im, 'hsv')


from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

import pymysql
import Mysqlpy

chrome_options = Options()

'''
# References: https://www.jianshu.com/p/1531e12f8852
# Python+Selenium基础入门及实践
# 使用headless无界面浏览器模式
'''
#增加无界面选项
chrome_options.add_argument('--headless')
#如果不加这个选项，有时定位会出现问题
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1366,768')

def getWeb(city,month):
	# 启动浏览器，获取网页源代码
	browser = webdriver.Chrome(chrome_options=chrome_options)

	browser.implicitly_wait(15)
	mainUrl = "https://www.aqistudy.cn/historydata/daydata.php?city="+city+"&month="+month
	browser.get(mainUrl)

	#获取它的th
	#通过tag name方式定位

	time.sleep(3)
	tbody = browser.find_element_by_class_name("row")
	if tbody == None:
		print('[]'+ city + month)

	# each_tr = tbody.find_elements_by_tag_name("tr")
	each_tr = tbody.find_element_by_tag_name("tbody").find_elements_by_tag_name("tr")
	tdList = []
	for tr in each_tr:
		#print("找到了一行tr:"+tr.text)
		each_td = tr.find_elements_by_tag_name("td")
		for td in each_td:
			# print("td:"+td.text)
			tdList.append(td.text)

	browser.quit()
	#print(tdList)
	return tdList

def get(city, month):
	print("正在获取在线数据，请稍候..")
	result = getWeb(city,month)
	dataList = []
	ll = []
	try:
		for i in range(len(result)):
			if i % 9 == 8:

				ll.append(result[i])

				l = ll[:]
				dataList.append(l)

				ll.clear()

			else:

				ll.append(result[i])

	except Exception as e:
		print(str(e))

	print(dataList)
	for q in dataList:
		try:
			Mysqlpy.dataHandler(city,q)
		except Exception as e:
			print(str(e))

get("珠海","201703")