"""Utilities for augmenting the data and generating batches of it.

Author: Lucy Tan

This module exports the Augmenter class for augmenting the training data with
image augmentation techniques, balancing the classes of the training data, and
generating sequences that yield batches of data. The sequences are designed
for use with the Keras APIs for model training, evaluating, and prediction.
"""
import glob
import math
import os
import shelve
from typing import Sequence, NamedTuple, Tuple

import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_io as tfio

from utils import common

# Default parameters to use for augmenting if none are provided.
_DEFAULT_PARAMS = {
    'AUGMENTATION_ARGS': dict(width_shift_range=0.3,
            horizontal_flip=True,
            brightness_range=[0.3, 0.9],
            fill_mode='nearest'),
    'BASE_DATA_DIR': 'dzanga-bai-20210816T230919Z-001/dzanga-bai',
    'BASE_ELP_WAV_DATA_DIR': 'elp_data/wav_files',
    'OUTPUT_PATH': 'dzanga-bai-20210816T230919Z-001/dzanga-bai',
    'SHELF_PATH': 'backups/shelves/shelf-%s-%s-%d',
    'BATCH_SIZE': 16,
    'IMAGE_SIZE': 512,
    'SEED': 100,
    'TARGET_COL': 'agecat',
    'USE_WAV_FILES': False,
    'AUGMENT_WITH_BALANCED_CLASSES': False,
}

# Adapted from https://stackoverflow.com/questions/66410340/filter-tensorflow-dataset-by-id
def filter_elp_dataset(dataset, indices):
    keys_tensor = tf.constant(indices)
    vals_tensor = tf.ones_like(keys_tensor)  # Ones will be casted to True.

    table = tf.lookup.StaticHashTable(
        tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor),
        default_value=0)  # If index not in table, return 0.

    @tf.function
    def hash_table_filter(index, value):
        table_value = table.lookup(index)  # 1 if index in arr, else 0.
        index_in_arr =  tf.cast(table_value, tf.bool) # 1 -> True, 0 -> False
        return index_in_arr

    return dataset.enumerate().filter(hash_table_filter).map(lambda idx, value: value)

# Copied from https://www.tensorflow.org/tutorials/audio/transfer_learning_audio
@tf.function
def load_wav_16k_mono(filename):
    """ Load a WAV file, convert it to a float tensor, resample to 16 kHz single-channel audio. """
    file_contents = tf.io.read_file(filename)
    wav, sample_rate = tf.audio.decode_wav(
          file_contents,
          desired_channels=1)
    wav = tf.squeeze(wav, axis=-1)
    sample_rate = tf.cast(sample_rate, dtype=tf.int64)
    wav = tfio.audio.resample(wav, rate_in=sample_rate, rate_out=16000)
    return tf.reshape(wav, [-1])

class CrossValFoldSequence(NamedTuple):
    """Contains the sequences for a single cross validation fold.

    Each batch is a tuple of x_data, y_data, where x_data is spectrogram pixel
    values and y_data is 1-hot encoded target labels.

    train: The sequence used for the train data of this fold.
    val: The sequence used for the validation data of this fold.
    """
    train: tf.keras.utils.Sequence
    val: tf.keras.utils.Sequence

class DatasetSequence(tf.keras.utils.Sequence):

    def __init__(self, dataset, labels, label_mapping, shelf_path, length=None):
        self._dataset = dataset
        self.classes = labels
        self.class_indices = label_mapping
        if length is None:
            self._length = len(dataset)
        else:
            self._length = length
        self._shelf_path = shelf_path
        self._data = CompressedShelf(shelf_path)

    def __len__(self):
        return self._length

    def _prefetch_data(self):
        dataset_iterator = self._dataset.as_numpy_iterator()
        for i in range(self._length):
            self._data[str(i)] = next(dataset_iterator)
        self._data.sync()

    def __getitem__(self, index):
        str_index = str(index)
        if str_index not in self._data:
            print('Prefetching data')
            self._prefetch_data()
        return self._data[str_index]

    def delete_data(self):
        self._data.close()
        try:
            for f in glob.glob(f'{self._shelf_path}*'):
                os.remove(f)
                print('Deleted', f)
        except Exception as e:
            print('Failed to delete shelf')
            print(e)

    def on_epoch_end(self):
        pass

class CombinedSequence(tf.keras.utils.Sequence):
    """Combines sequences to produce data from all the given sequences.

    It is not guaranteed that each batch will have the same amount of data
    from each given sequence. Instead, if there are N sequences, then across
    each group of N batches, there will be batch_size elements from each
    sequence.

    It is designed to be used with the Keras APIs for model training,
    evaluating, and prediction. As a result, it needs to implement the
    following methods:
        __len__: indicates how many total elements are in the sequence
        __iter__: iterates through the sequence, generating each batch of data
        __next__: yields the next batch of data
    """
    def __init__(self, seed, batch_size, labels, label_mapping, *sequences):
        """Create a CombinedSequence with the seed, batch size, and sequences.

        The sequence is created to use in the __next__ method.
        """
        self._seed = seed
        self._batch_size = batch_size
        self._sequences = sequences
        assert batch_size % len(sequences) == 0, 'Batch size must be a multiple of the number of sequences to make each batch even'
        self._rng = np.random.default_rng(seed=self._seed)
        self._num_batches_per_sequence = self._get_num_batches_per_sequence()
        self._len = max(self._num_batches_per_sequence) * len(sequences)
        self.classes = []
        for _ in range(self._len):
            for i in range(len(sequences)):
                self.classes.extend([labels[i]] * (batch_size // len(sequences)))
        self.class_indices = label_mapping

    def __len__(self):
        return self._len

    def _get_num_batches_per_sequence(self):
        full_sequence_lengths = []
        for seq in self._sequences:
            i = len(seq) - 1
            while i > -1:
                if len(seq[i][0]) >= self._batch_size:
                    full_sequence_lengths.append(i + 1)
                    break
                i -= 1
            if i == -1:
                full_sequence_lengths.append(1)
        return full_sequence_lengths

    def _batches_per_sequence(self):
        shortest_length = len(min(self._sequences, key=len))
        while shortest_length > 0:
            all_are_valid = True
            for sequence in self._sequences:
                if len(sequence[shortest_length - 1][0]) < self._batch_size:
                    all_are_valid = False
                    break
            if all_are_valid:
                break
            shortest_length -= 1
        return shortest_length

    def _get_data_for_epoch(self):
        x_data = []
        y_data = []
        for sequence in self._sequences:
            for i in range(len(sequence)):
                cur_x_data, cur_y_data = sequence[i]
                # Don't use batch groups where a sequence had less than a full
                # batch. This would allow the training data to be unbalanced.
                if len(cur_x_data) != self._batch_size:
                    continue
                x_data.append(cur_x_data)
                y_data.append(cur_y_data)
        merged_data = np.concatenate(x_data), np.concatenate(y_data)
        data_len = len(merged_data[0])
        indices = np.arange(data_len)
        self._rng.shuffle(indices)
        return merged_data[0][indices], merged_data[1][indices]

    def __getitem__(self, index):
        sequence_batch_index = index // len(self._sequences)
        sequence_batches = [self._sequences[i][sequence_batch_index % self._num_batches_per_sequence[i]] for i in range(len(self._sequences))]
        batch_start_index = self._batch_size * (index % len(self._sequences))
        batch_end_index = batch_start_index + self._batch_size
        batch_indices = np.arange(batch_start_index, batch_end_index)
        x_data = []
        y_data = []
        for i in range(len(self._sequences)):
            cur_indices = batch_indices[batch_indices % len(self._sequences) == i] // len(self._sequences)
            x_data.extend(sequence_batches[i][0][cur_indices])
            y_data.extend(sequence_batches[i][1][cur_indices])
        indices = np.arange(len(x_data))
        return np.array(x_data)[indices], np.array(y_data)[indices]

    def on_epoch_end(self):
        for sequence in self._sequences:
            sequence.on_epoch_end()
        self._rng = np.random.default_rng(seed=self._seed)

class Augmenter:
    """A class to augment the training data and create sequences of batches.

    The public methods are:
        get_sequences: Returns the cross validation train and val sequences
            for the Dzanga Bai data given the indices (output by the
            CrossValidator).
        get_test_sequence: Returns the test sequence for the Dzanga Bai data
            given the indices (output by the TestSplitter).
    """

    def __init__(self, params=None):
        """Create a Augmenter with the given params.

        The params should include all of the following:
            AUGMENTATION_ARGS
            BASE_DATA_DIR: The path to the directory with the Dzanga Bai data.
            BATCH_SIZE: The number of data points to use in each batch.
            IMAGE_SIZE: The size in pixels for both height and width of the
                spectrogram when input to the model.
            SEED: The random seed to use for consistent image augmentation and
                data shuffling.
            TARGET_COL: The name of the column containing the target label.
        """
        self._params = _DEFAULT_PARAMS.copy()
        if params is not None:
            self._params.update(params)

    def _load_wav_for_map(self, filename, one_hot_label, label):
        return load_wav_16k_mono(filename), one_hot_label, label

    def _get_sequence_audio(self, df, filtered_df, shuffle, fold_index, is_train_fold):
        target_col = self._params['TARGET_COL']
        one_hot_labels = pd.get_dummies(filtered_df[target_col].astype(pd.CategoricalDtype(categories=sorted(list(df[target_col].unique())))))
        dataset = tf.data.Dataset.from_tensor_slices((filtered_df['wav_path'], one_hot_labels, np.argmax(one_hot_labels.to_numpy(), axis=1)))
        dataset = dataset.map(self._load_wav_for_map)
        max_length = dataset.reduce(np.int32(0), lambda cur_max, new_x: tf.math.maximum(cur_max, tf.shape(new_x[0])[0])).numpy()
        if shuffle:
            dataset = dataset.shuffle(buffer_size=len(filtered_df), seed=self._params['SEED'], reshuffle_each_iteration=False)
        dataset_labels = list(dataset.map(lambda x,y,label: label).as_numpy_iterator())
        label_mapping = {value: index for index, value in enumerate(one_hot_labels.columns)}
        dataset = dataset.map(lambda x,y,label: (tf.reshape(tf.pad(x, [[0, max_length - tf.shape(x)[0]]]), [max_length]),y))
        shelf_path = self._params['SHELF_PATH'] % ('dz', 'train' if is_train_fold else ('val' if fold_index is not None else 'test'), fold_index if fold_index is not None else 0)
        return DatasetSequence(dataset.batch(self._params['BATCH_SIZE']).prefetch(tf.data.AUTOTUNE), dataset_labels, label_mapping, shelf_path)

    def _get_sequence_image(self, df, filtered_df, shuffle, augment):
        target_col = self._params['TARGET_COL']
        image_size = self._params['IMAGE_SIZE']
        augmentation_args = self._params['AUGMENTATION_ARGS'] if augment else {}
        return tf.keras.preprocessing.image.ImageDataGenerator(
            **augmentation_args).flow_from_dataframe(
            dataframe=filtered_df,
            x_col='path',
            y_col=target_col,
            target_size=(image_size, image_size),
            color_mode='rgb',
            classes=sorted(list(df[target_col].unique())),
            class_mode='categorical',
            batch_size=self._params['BATCH_SIZE'],
            shuffle=shuffle,
            seed=self._params['SEED'],
            save_to_dir=None,
            save_prefix='',
            save_format='png',
            subset=None,
            interpolation='nearest',
            validate_filenames=True,)

    def _get_sequence(self, df, shuffle, augment, fold_index, is_train_fold, indices=None):
        filtered_df = df.iloc[indices] if indices is not None else df
        if self._params['USE_WAV_FILES']:
            return self._get_sequence_audio(df, filtered_df, shuffle, fold_index, is_train_fold)
        return self._get_sequence_image(df, filtered_df, augment, shuffle)

    def _get_elp_sequence(self, dataset, shuffle, indices, fold_index, is_train_fold):
        dataset = filter_elp_dataset(dataset, indices)
        max_length = dataset.reduce(np.int32(0), lambda cur_max, new_x: tf.math.maximum(cur_max, tf.shape(new_x)[0])).numpy()
        if shuffle:
            dataset = dataset.shuffle(buffer_size=len(indices), seed=self._params['SEED'], reshuffle_each_iteration=False)
        dataset = dataset.map(lambda x: tf.reshape(tf.pad(x, [[0, max_length - tf.shape(x)[0]]]), [max_length]))
        dataset = dataset.map(lambda x: (x, np.zeros(())))
        shelf_path = self._params['SHELF_PATH'] % ('elp', 'train' if is_train_fold else 'val', fold_index)
        return DatasetSequence(dataset.batch(self._params['BATCH_SIZE']).prefetch(tf.data.AUTOTUNE), None, None, shelf_path, math.ceil(len(indices) / self._params['BATCH_SIZE']))

    def _filter_indices(self, df, indices, value_to_accept):
        new_indices = [
            idx for idx in indices
            if df[self._params['TARGET_COL']].iloc[idx] == value_to_accept
        ]
        return np.array(new_indices)

    def _get_balanced_sequence(self, df, indices, fold_index):
        seed = self._params['SEED']
        target_col = self._params['TARGET_COL']
        sequences = []
        for target_val in sorted(df[target_col].unique()):
            filtered_indices = self._filter_indices(
                df, indices, target_val)
            sequences.append(self._get_sequence(
                df, shuffle=True, augment=True, fold_index=fold_index, is_train_fold=True, indices=filtered_indices))
        label_mapping = {value: index for index, value in enumerate(sorted(list(df[target_col].unique())))}
        return CombinedSequence(seed, self._params['BATCH_SIZE'], list(range(len(sequences))), label_mapping, *sequences)

    def get_test_sequence(self, test_indices):
        df = common.load_dz_data(self._params['BASE_DATA_DIR'])
        return self._get_sequence(df, shuffle=False, augment=False, fold_index=None, is_train_fold=False, indices=test_indices)

    def get_sequences(self, cross_val_indices, augment=True):
        """Get the sequences for the given indices.

        If augment is True, use image augmentation and class balancing for the
        training data.

        For each cross-validation fold, generate a sequence for the train and
        validation data.
        """
        df = common.load_dz_data(self._params['BASE_DATA_DIR'])
        target_col = self._params['TARGET_COL']
        sequences = []
        for i, fold_indices in enumerate(cross_val_indices):
            if augment and self._params['AUGMENT_WITH_BALANCED_CLASSES'] and not self._params['USE_WAV_FILES']:
                train_sequence = self._get_balanced_sequence(
                    df, fold_indices[0], i)
            else:
                train_sequence = self._get_sequence(
                    df, shuffle=augment, augment=augment, fold_index=i, is_train_fold=True, indices=fold_indices[0])
            val_sequence = self._get_sequence(
                df, shuffle=False, augment=False, fold_index=i, is_train_fold=False, indices=fold_indices[1])
            sequences.append(CrossValFoldSequence(
                train_sequence, val_sequence))
        return sequences

    def get_elp_sequences(self, cross_val_indices, shuffle=True):
        """Get the ELP sequences for the given indices.

        For each cross-validation fold, generate a sequence for the train and
        validation data.
        """
        dataset = common.load_elp_data(self._params['BASE_ELP_WAV_DATA_DIR'])
        sequences = []
        for i, fold_indices in enumerate(cross_val_indices):
            train_sequence = self._get_elp_sequence(
                    dataset, shuffle=shuffle, fold_index=i, is_train_fold=True, indices=fold_indices[0])
            val_sequence = self._get_elp_sequence(
                dataset, shuffle=False, fold_index=i, is_train_fold=False, indices=fold_indices[1])
            sequences.append(CrossValFoldSequence(
                train_sequence, val_sequence))
        return sequences

if __name__ == '__main__':
    # train_indices_filename_pattern = os.path.join(
    #     _DEFAULT_PARAMS['OUTPUT_PATH'], 'train_indices_%s.csv')
    # val_indices_filename_pattern = os.path.join(
    #     _DEFAULT_PARAMS['OUTPUT_PATH'], 'val_indices_%s.csv')
    # cross_val_indices = []
    # for i in range(5):
    #     with open(train_indices_filename_pattern % i, 'rt') as f:
    #         train_indices = np.array([int(index) for index in f.readlines()])
    #     with open(val_indices_filename_pattern % i, 'rt') as f:
    #         val_indices = np.array([int(index) for index in f.readlines()])
    #     cross_val_indices.append((train_indices,val_indices))
    # augmenter = Augmenter()
    # kfold_sequences = augmenter.get_sequences(cross_val_indices)
    # test_indices_filename = os.path.join(
    #     _DEFAULT_PARAMS['BASE_DATA_DIR'], 'test_indices.csv')
    # with open(test_indices_filename, 'rt') as f:
    #     test_indices = np.array([int(index) for index in f.readlines()])
    # test_sequence = augmenter.get_test_sequence(test_indices)
    # cross_val_data = [
    #     (next(iter(sequence.train)), next(iter(sequence.val)))
    #     for sequence in kfold_sequences
    # ]
    # #print(cross_val_data, next(iter(test_sequence)))
    # #print(test_sequence.classes, test_sequence.class_indices)
    # print(kfold_sequences[0].train.classes)
    # print(kfold_sequences[0].train.class_indices)
    # for i in range(len(kfold_sequences[0].train)):
    #     print(kfold_sequences[0].train[i][1])

    train_indices_filename_pattern = os.path.join(
        _DEFAULT_PARAMS['OUTPUT_PATH'], 'elp_train_indices_%s.csv')
    val_indices_filename_pattern = os.path.join(
        _DEFAULT_PARAMS['OUTPUT_PATH'], 'elp_val_indices_%s.csv')
    cross_val_indices = []
    for i in range(5):
        with open(train_indices_filename_pattern % i, 'rt') as f:
            train_indices = np.array([int(index) for index in f.readlines()])
        with open(val_indices_filename_pattern % i, 'rt') as f:
            val_indices = np.array([int(index) for index in f.readlines()])
        cross_val_indices.append((train_indices,val_indices))
    augmenter = Augmenter()
    kfold_sequences = augmenter.get_elp_sequences(cross_val_indices)
    cross_val_data = [
        (sequence.train[0], sequence.val[0])
        for sequence in kfold_sequences
    ]
    cross_val_len = [
        (len(sequence.train), len(sequence.val))
        for sequence in kfold_sequences
    ]
    print(cross_val_data, cross_val_len)


class Note:
    def __init__(self, title, start_hash, edit_date, content, number = None):
        self.number = number
        self.title = title
        self.start_hash = start_hash
        self.edit_date = edit_date
        self.content = content


from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from .serializers import PortfolioSerializer, BusinessSerializer, Portfolio
from account.utils import BaseResponse, abort
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser

from django.http import QueryDict

# Create your views here.
class PortfolioView(APIView):
    permission_classes = (IsAuthenticated,)
    parser_classes = [MultiPartParser]
    serializer_class = PortfolioSerializer

    def post(self, request):
        print(request.user.id)

        # Create a mutable copy of request.data
        mutable_data = QueryDict('', mutable=True)
        mutable_data.update(request.data)

        # Assign the service_provider
        mutable_data['service_provider'] = request.user.id

        serializer = self.serializer_class(data=mutable_data, context={'request': request})

        print(request.data)
        try:

            serializer.is_valid(raise_exception=True)
            print(serializer.validated_data)
            serializer.save()
            base_response = BaseResponse(serializer.data, None, 'Portfolio created successfully')
            return Response(base_response.to_dict())
        except Exception as e:
            return abort(400, str(e))

class BusinessView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        print(request.user.id)
        request.data['service_provider'] = request.user.id
        serializer = BusinessSerializer(data=request.data, context={'request': request})
        try:
            serializer.is_valid(raise_exception=True)
            # print(serializer.data)
            print(serializer.validated_data)
            serializer.save()
            base_response = BaseResponse(serializer.data, None, 'Business created successfully')
            return Response(base_response.to_dict())
        except:

            return abort(400, serializer.errors)


from zope import schema
from zope.interface import Interface
from zope.i18nmessageid import MessageFactory

_ = MessageFactory('collective.tinymceplugins.imagebrowser')

class ITinyMCELibrariesImageResources(Interface):
    """Plone registry entries to register TinyMCE image browser resources.
    """

    imagebrowser_resources = schema.List(title=_(u"Image Resources"),
                              required=False,
                              value_type=schema.TextLine(),
                              default=[],
                              missing_value=[])


import boto3
from .aws_boto_session import BotoSession

class SSMGlobalParameters(BotoSession):
    """Query SSM for Global Parameters.

    Methods to retrieve Global SSM data.

    Methods
    ----------
    get_regions(DetailLevel='low')
        Returns list of regions
    """

    # ==========================================================
    def __init__(self, **kwargs):

        # Global Parameters.
        self.service_name = 'ssm'
        self.path = '/aws/service/global-infrastructure/regions'
        self.info = []
        self.list = []

        # Connect to SSM
        self.boto = boto3.client('ssm')

    # ==========================================================
    def _query_ssm_for_region_data(self):

        # Query SSM for region info.
        resp = self.boto.get_parameters_by_path(
            Path=self.path
        )

        # Add response 'Parameters' to info list.
        self.info.extend(resp['Parameters'])

        # Continue to query until no NextToken present.
        while 'NextToken' in resp:
            resp = self.boto.get_parameters_by_path(
                Path=self.path,
                NextToken=resp['NextToken']
            )

            # Add response 'Parameters' to info list.
            self.info.extend(resp['Parameters'])

    # ==========================================================
    # Return low detail level
    def _get_detail_low(self):
        for i in self.info:
            self.list.append(
                i.get('Value', None)
            )

        return self.list

    # ==========================================================
    # Get regions.
    def get_regions(self, DetailLevel='low'):
        """Generates list of regions

        Parameters
        ----------
        DetailLevel : str, optional
            Level of detail in returned list, can be 'high' or 'low'
            Defaults to 'low'
        """

        # Auto-generate data.
        self._query_ssm_for_region_data()

        # Return level of data based on arguments.
        if DetailLevel.lower() == 'high':
            return self.info
        else:
            return self._get_detail_low()


import paho.mqtt.client as mqtt #import the client1
import time
from smartcard.System import readers
from smartcard.util import toHexString, toASCIIString, toBytes
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import time
import sys

def generateFinalKnowledge(k1, k2):
    master_key = bytes(b1 ^ b2 for (b1, b2) in zip(k1, k2)) # to have completion of final knowledge
    return master_key

def acquireK1():
    f = open(sys.argv[1], "rb")
    k1 = f.read()
    f.close()
    return k1

def waitCard(connection):
    try:
        connection.connect()
        return True
    except:
        print("Waiting smartcard")
        return False

def readCard(connection):
    end = False
    i = 1 # start from sector 1
    typefield = ""
    payload = ""
    while not end:
    # decrypt first block of sector with key. if succeed, sector is unlocked
    # if other sector is unlocked, previous sector is locked
        COMMAND = [0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, i*4, 0x60, 0x00]
        data, sw1, sw2 = connection.transmit(COMMAND)
        if (sw1, sw2) == (0x90, 0x0):
            #print("Status: Decryption sector "+ str(i) +" using key #0 as Key A successful.")
            print()
        elif (sw1, sw2) == (0x63, 0x0):
            #print("Status: Decryption sector "+ str(i) +" failed. Trying as Key B")
            COMMAND = [0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, i*4, 0x61, 0x00]
            data, sw1, sw2 = connection.transmit(COMMAND)
        if (sw1, sw2) == (0x90, 0x0):
            #print("Status: Decryption sector "+ str(i) +" using key #0 as Key B successful.")
            print()
        elif (sw1, sw2) == (0x63, 0x0):
            print("Status: Decryption sector "+ str(i) +" failed.")
            sys.exit()

        #print("---------------------------------Sector "+ str(i) +"---------------------------------")
        for block in range(i*4, i*4+3): # because last block of each sector is the key
            COMMAND = [0xFF, 0xB0, 0x00]
            COMMAND.append(block)
            COMMAND.append(16)
            data, sw1, sw2 = connection.transmit(COMMAND)
            blockdata = toHexString(data).replace(" ","")
            if(block==4): # first block

                ndefFormat = False
                j = 1
                while(not ndefFormat):
                    if(blockdata[2*(j-1):2*j]!="03"):
                        if(blockdata[2*(j-1):2*j]=="00"):
                            #print("Ignore byte #" + str(j))
                            j = j + 1
                        else:
                            print("NO ndef format found")
                            sys.exit()
                    else:
                        ndefFormat = True

                length = blockdata[j*2:(j+1)*2]
                if(length=="00"):
                    print("NO value")
                    sys.exit()
                if(length=="FF"):
                    j = j + 1
                    length = int(blockdata[j*2:(j+2)*2],16)
                else:
                    length = int(blockdata[j*2:(j+1)*2],16)
                #print("Total length = " + str(length))

                j=j+2
                typelength = blockdata[j*2:(j+1)*2]
                if(typelength=="00"):
                    print("NO type field")
                if(typelength=="FF"):
                    j = j + 1
                    typelength = int(blockdata[j*2:(j+2)*2],16)
                else:
                    typelength = int(blockdata[j*2:(j+1)*2],16)
                #print("Type length = " + str(typelength))

                j = j + 1
                payloadlength = blockdata[j*2:(j+1)*2]
                if(payloadlength=="FF"):
                    j = j + 1
                    payloadlength = int(blockdata[j*2:(j+2)*2],16)
                else:
                    payloadlength = int(blockdata[j*2:(j+1)*2],16)
                #print("Payload length = " + str(payloadlength))

                j = j + 1
                if(j<16):
                    if(typelength+j>=16):
                        typefield = typefield + blockdata[j*2:]
                    else:
                        typefield = typefield + blockdata[j*2:j*2+typelength*2]
                        payload = payload + blockdata[j*2+typelength*2:]
                        payloadlength = payloadlength - (16 - j - typelength)
                    typelength = typelength - (16 - j)
                    #print("Type length = " + str(typelength))
            else:
                #print("Payload length = " + str(payloadlength))
                if(typelength>0): # not first block but typefield to read
                    if(typelength<=16):
                        if(typelength==16):
                            typefield = typefield + blockdata
                        else:
                            typefield = typefield + blockdata[:typelength*2]
                            payload = payload + blockdata[typelength*2:]
                            payloadlength = payloadlength - (16-typelength)
                        typelength = 0
                    else:
                        typefield = typefield + blockdata
                        typelength -= 16
                else:
                    if(payloadlength<=16):
                        payload += blockdata[:payloadlength*2]
                        payloadlength = 0
                        end = True
                    else:
                        payload += blockdata
                        payloadlength -= 16

            #print("block "+ str(block) +":\t"+ toHexString(data) +" | "+''.join(chr(j) for j in data))

        #print("Status words: %02X %02X" % (sw1, sw2))
        if (sw1, sw2) == (0x90, 0x0):
            #print("Status: The operation completed successfully.")
            ok = True
        elif (sw1, sw2) == (0x63, 0x0):
            #print("Status: The operation failed. Maybe auth is needed.")
            ok = False

        i = i+1

    typestring = toASCIIString(toBytes(typefield))
    #print(payload)
    k2 = bytearray.fromhex(payload)
    return k2, typestring

k1 = acquireK1()

r = readers()
if len(r) < 1:
	print("error: No readers available!")
	sys.exit()

#print("Available readers: ", r)

reader = r[0]
#print("Using: ", reader)

connection = reader.createConnection()
while(True):
    if(waitCard(connection)):
        print("Smartcard revealed")
        break
    else:
        time.sleep(5)
        continue

k2, typestring = readCard(connection)
#print("Type: " + typestring)
print("K1 = ", k1.hex())
print("K2 = ", k2.hex())

master_key = generateFinalKnowledge(k1, k2)
print("MK = ", master_key.hex())

############
def on_message(client, userdata, message):
    decipher = AES.new(master_key, AES.MODE_ECB)
    encryptedmessage = message.payload
    paddedtext = decipher.decrypt(encryptedmessage)
    originalmessage = unpad(paddedtext, AES.block_size).decode("utf-8", "ignore")
    print("Message received =", str(encryptedmessage.hex()))
    print('Message decrypted =', str(originalmessage))
############

broker_address="broker.hivemq.com"
print("Creating new subscriber instance")
client = mqtt.Client("braintech_subscriber") #create new instance
client.on_message=on_message #attach function to callback
#print("connecting to broker")
client.connect(broker_address) #connect to broker
client.loop_start() #start the loop
print("Subscribing to topic","braintech/masterdegree/test")
client.subscribe("braintech/masterdegree/test")
time.sleep(30) #wait
client.loop_stop() #stop the loop


# Ainsley Lawson.  ainsley.lawson@utoronto.ca
# August 2009

from genshi import HTML

def format_relations_for_flare(self, r_dict):
    """
    Takes a dictionary of relations and returns the HTML for the
    data in json format (for Flare to visualize)
    """

    #TODO:  Strength is always set to 1 at the moment, since I haven't
    #		figured out how to show edge weights yet in Flare.

    html = '['
    for file1 in r_dict:
        if r_dict[file1] == []:
            html += '{"name":"sn/' + file1 + '","strength":1,"links":[]},'
            continue
        html += '{"name":"sn/' + file1 + '","strength":1,"links":['
        for link in r_dict[file1]:
            html += '"sn/' + link + '",'
        html = html[0:len(html) - 1] + ']},'
    html = html[0:len(html) - 1] + ']'
    if html == ']':
        html = '[]'

    data = HTML(html)
    return data

def get_my_files_data(self, person, depth):
    """
    Returns the HTML for a data file that Flare uses to construct the graph
    of the my file relations.
    """
    db = self.env.get_db_cnx()
    cursor = db.cursor()

    q, relations, dist = [], [], {}

    # Get the files the person has worked on
    cursor.execute('SELECT DISTINCT path \
                    FROM node_change n, revision r \
                    WHERE n.rev = r.rev \
                    AND r.author = %s',
                   (person,))
    for row in cursor:
        q.append(row[0])
        dist[row[0]] = 0

    while len(q) != 0:

        # Grab a file from the queue and get its related files
        current = q[0]
        q.remove(current)
        cursor.execute('SELECT file1, file2 \
                        FROM code_relations \
                        WHERE file1 = %s \
                        OR file2 = %s',
                       (current, current,))

        # Examine each file neighbouring node 'current'
        for file1, file2 in cursor:
            if file1 == current:
                file1, file2 = file2, file1

            # Calculate distance from root node(s)
            if (file1 not in dist):
                dist[file1] = dist[current] + 1

                # Add file to queue if necessary
                if dist[file1] <= depth:
                    q.append(file1)

            # Record the relation
            if ((current, file1) not in relations) \
                and ((file1, current) not in relations) \
                and (dist[file1] <= depth):
                relations.append((current, file1))

                # end for
        # end while

    db.close()

    # Set up a dictionary of the relations
    r_dict = {}
    for file1, file2 in relations:
        if file2 not in r_dict:
            r_dict[file2] = []
        if file1 in r_dict:
            r_dict[file1].append(file2)
        else:
            r_dict[file1] = [file2]

    # Format data for Flare
    data = format_relations_for_flare(self, r_dict)

    return data

def get_overall_files_data(self):
    """
    Returns the HTML for a data file that Flare uses to construct the graph
    of the overall file relations.
    """

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    # Get all the file relations
    cursor.execute('SELECT file1, file2 \
                    FROM code_relations')

    # Set up a dictionary of the relations
    r_dict = {}
    for file1, file2 in cursor:
        file1 = file1[0: file1.rfind('/')] + '/*'
        file2 = file2[0: file2.rfind('/')] + '/*'
        if file1 != file2:
            if file2 not in r_dict:
                r_dict[file2] = []
            if file1 in r_dict:
                if file2 not in r_dict[file1]:
                    r_dict[file1].append(file2)
            else:
                r_dict[file1] = [file2]

    db.close()

    # Format data for Flare
    data = format_relations_for_flare(self, r_dict)

    return data

def get_subdirs_files_data(self, subdirs):
    """
    Returns the HTML for a data file that Flare uses to construct the graph
    of the specified file relations.  subdirs is a list of directories.
    Only relations between files in the specified directories (and their
    child directories) are included.
    """

    relations = []
    subdirs.sort()

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    # Get the relevant file relations
    for i in range(0, len(subdirs)):
        dir1 = subdirs[i]

        for j in range(i, len(subdirs)):
            dir2 = subdirs[j]
            cursor.execute('SELECT file1, file2 \
                            FROM code_relations \
                            WHERE (file1 LIKE "' + dir1 + '%" \
                            AND file2 LIKE "' + dir2 + '%")')
            for file1, file2 in cursor:
                if file1 != file2:
                    relations.append((file1, file2))

    # Set up a dictionary of the relations
    r_dict = {}
    for file1, file2 in relations:
        if file2 not in r_dict:
            r_dict[file2] = []
        if file1 in r_dict:
            r_dict[file1].append(file2)
        else:
            r_dict[file1] = [file2]

    # Format data for Flare
    data = format_relations_for_flare(self, r_dict)

    db.close()

    return data

def get_my_social_data(self, me, depth):
    """
    Returns the HTML for a data file that Flare uses to construct the graph
    of the my social relations.
    """
    db = self.env.get_db_cnx()
    cursor = db.cursor()

    q, relations, dist = [], [], {}

    q.append(me)
    dist[me] = 0

    while len(q) != 0:

        # Grab a person from the queue and get its related people
        current = q[0]
        q.remove(current)
        cursor.execute('SELECT person1, person2 \
                        FROM social_relations \
                        WHERE person1 = %s \
                        OR person2 = %s',
                       (current, current,))

        # Examine each person neighbouring node 'current'
        for person1, person2 in cursor:
            if person1 == current:
                person1, person2 = person2, person1

            # Calculate distance from root node(s)
            if (person1 not in dist):
                dist[person1] = dist[current] + 1

                # Add file to queue if necessary
                if dist[person1] <= depth:
                    q.append(person1)

            # Record the relation
            if ((current, person1) not in relations) \
                and ((person1, current) not in relations) \
                and (dist[person1] <= depth):
                relations.append((current, person1))

                # end for
        # end while

    db.close()

    # Set up a dictionary of the relations
    r_dict = {}
    for person1, person2 in relations:
        if person2 not in r_dict:
            r_dict[person2] = []
        if person1 in r_dict:
            r_dict[person1].append(person2)
        else:
            r_dict[person1] = [person2]

    # Format data for Flare
    data = format_relations_for_flare(self, r_dict)

    return data

def get_overall_social_data(self):
    """
    Returns the HTML for a data file that Flare uses to construct the graph
    of the overall social relations.
    """

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    # Get all social relations
    cursor.execute('SELECT person1, person2, strength \
                    FROM social_relations')
    r_dict = {}

    # Set up a dictionary of the relations
    for person1, person2, strength in cursor:
        if person2 not in r_dict:
            r_dict[person2] = []
        if person1 in r_dict:
            r_dict[person1].append(person2)
        else:
            r_dict[person1] = [person2]

    # Format data for Flare
    data = format_relations_for_flare(self, r_dict)

    db.close()

    return (data)

def get_correction_dropdown(self, person):
    """
    Return the HTML for the options of a dropdown list of people
    that person does not talk to.
    """

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    all_people, spoken_to = [], [person]

    # Get all the people
    cursor.execute("SELECT DISTINCT author FROM revision \
                    UNION \
                    SELECT DISTINCT reporter FROM ticket \
                    UNION \
                    SELECT DISTINCT author FROM ticket_change")
    for row in cursor:
        all_people.append(row[0])

    # Get the people that person talks to
    cursor.execute('SELECT DISTINCT person1 \
                    FROM social_relations \
                    WHERE person2 = %s',
                   (person,))
    for row in cursor:
        spoken_to.append(row[0])

    cursor.execute('SELECT DISTINCT person2 \
                    FROM social_relations \
                    WHERE person1 = %s',
                   (person,))
    for row in cursor:
        spoken_to.append(row[0])

    # Subtract to get the people that person doesn't talk to
    all_people = set(all_people)
    spoken_to = set(spoken_to)
    not_spoken_to = all_people.difference(spoken_to)

    # Format as HTML dropdown list options
    drop_down = ""
    for p in not_spoken_to:
        drop_down += '<option value="' + p + '">' + p + '</option>'

    return HTML(drop_down)

def get_my_linkto(self, me, them):
    '''
    Returns the HTML for a data file that Flare uses to construct a graph
    of the shortest path of social connections between person 'me' and
    person 'them'.  If there is no path, then the data file is empty.
    '''

    # Make sure that people have been specified
    if me == "" or them == "":
        return HTML("[]")

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    # Get all the social relations
    cursor.execute("SELECT person1, person2 \
                    FROM social_relations")

    # Get a list of all people who have communicated
    all_nodes = []
    for person1, person2 in cursor:
        all_nodes.append(person1)
        all_nodes.append(person2)
    all_nodes = list(set(all_nodes))

    # Make sure that 'me' and 'them' have had social communication
    if (me not in all_nodes) or (them not in all_nodes):
        return HTML("[]")

    dist = {}    # dist[p] = distance in tree from 'me' to 'p'
    prev = {}    # prev[p] = parent of person in the path from 'me' to 'p'

    # Find shortest path from 'me' to 'them' using Dijkstra's algorithm
    # http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode

    # Initialize variables
    for node in all_nodes:
        dist[node] = None
        prev[node] = None
    dist[me] = 0
    q = all_nodes

    while len(q) != 0:

        # Get the node in q with smalled dist[]
        smallest = q[0]
        for node in q:
            if dist[smallest] == None and dist[node] != None:
                smallest = node
            elif (dist[smallest] != None and dist[node] != None
                  and dist[node] < dist[smallest]):
                smallest = node

        # Check if 'me' has no social connection to 'them'
        if dist[smallest] == None:
            break

        # Remove smallest from q
        q.remove(smallest)

        # Get the neighbours of smallest that are still in the q
        neighbours = []
        cursor.execute("SELECT person1, person2 \
                        FROM social_relations \
                        WHERE person1 = %s \
                        OR person2 = %s",
                       (smallest, smallest,))
        for person1, person2 in cursor:
            if person1 == smallest and person2 in q:
                neighbours.append(person2)
            elif person2 == smallest and person1 in q:
                neighbours.append(person1)

        # Update distances and parent nodes
        for node in neighbours:
            alt = dist[smallest] + 1
            if dist[node] == None or alt < dist[node]:
                dist[node] = alt
                prev[node] = smallest

    # end while

    db.close()

    # Get all the people in the path from 'me' to 'them'
    r_dict = {}
    current = them
    while current != me:
        r_dict[current] = [prev[current]]
        current = prev[current]
    r_dict[me] = []

    # Format data for Flare
    data = format_relations_for_flare(self, r_dict)

    return data

def get_recent_files(self, author, base_path):
    '''
    Get the HTML for a list of author's most recent files.
    base_path should be the link to the trac environment, so that
    the list can include links to the files.
    '''

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    # Get author's recent files
    cursor.execute('SELECT nc.path, r.time \
                    FROM node_change nc, revision r\
                    WHERE r.author=%s \
                    AND nc.rev = r.rev \
                    AND nc.node_type="F" \
                    ORDER BY r.time DESC',
                   (author,))

    html = '
'        # HTML for the list
    num_recent = 0        # Number of files in the list

    # Construct the list
    for path, time in cursor:

        # Maximum of 10 files in the list
        num_recent += 1
        if num_recent > 10:
            break

        # Link to the file
        html += '
' + \
                path + '
'

    html += '
'

    return HTML(html)

def determine_directory_structure(self, repo):
    """
    Return a dictionary where each entry is the form
    ( directory : [list of sub-directories] ).  The directory is the
    full path of the directory, and each item in the value list is a name
    of a direct sub-directory. 	For example, if the directories are:
        d1, d2, d1/d1a, d1/d1b, d1/d1a/d1aa
    the dictionary would have the following entries:
        { "":["d1", "d2"], "d1":["d1a", "d1b"], "d2":[],
          "d1/d1a":["d1aa"], "d1/d1b":[], "d1/d1a/d1aa":[] }
    """

    db = self.env.get_db_cnx()
    cursor = db.cursor()

    # Get all the directories
    cursor.execute('SELECT DISTINCT path \
                    FROM node_change \
                    WHERE node_type = "D"')

    # Construct the directory dictionary
    # directory_dict[d] = [list of d's subdirectories]
    directory_dict = {}
    for (path,) in cursor:
        ind = path.rfind('/')
        directory = path[0:ind]

        if ind == -1:
            directory = ""
        if path not in directory_dict:
            directory_dict[path] = []
        if directory in directory_dict:
            directory_dict[directory].append(path)
        else:
            directory_dict[directory] = [path]
    db.close()

    return directory_dict

def process_structure(self, directory, directory_dict, indent):
    """
    Construct the HTML for the options of a drop-down list of the
    directory structure.
    - directory is the directory you want to start the structure from
      ("" if you want to start from the root)
    - directory_dict is as the output from determine_directory_structure().
    - indent is the string of blank characters that should preceed this
      option in the dropdown list (pass in "" to start)
    """

    # Get the last token in the path to the directory
    if directory == "":
        this_dir = ""
    else:
        ind = directory.rfind('/')
        this_dir = directory[ind + 1:]

    # Add this directory to the result
    result = ''
    if this_dir != "":
        result = '<option value="' + directory + '">' + indent + \
                 ' |- ' + this_dir + '</option>'

    # Process this directory's subdirectories
    sub_directories = directory_dict[directory]
    indent += '&nbsp&nbsp&nbsp'
    for sub in sub_directories:
        result += process_structure(self, sub, directory_dict, indent)

    return result

def get_directory_list(self, repo):
    """
    Returns the HTML for a form to select directories, and pass them as
    query args to sn_overall_files page.  repo is the svn repository.
    """

    # Get the directory dictionary
    dd = determine_directory_structure(self, repo)

    # Construct the HTML
    html = '\
    <form method="GET" action="sn_overall_files"> \
    \

 \

 \
           \
            Select directories you wish to examine \
            (hold ctrl to select more than one). \
          	 \
           \
            <select name="subdirs" multiple size=6>' + \
           process_structure(self, "", dd, "") + \
           '</select> \
         	 \
          \
           &nbsp&nbsp<input type="submit" value="Submit" /> \
         	 \

 \

 \
    \
   </form>'

    return HTML(html)


from nova.openstack.common import log as logging
from nova.virt.libvirt import volume

LOG = logging.getLogger(__name__)

class NfsVolumeDriver(volume.LibvirtNFSVolumeDriver):
    """Deprecated driver for NFS, renamed to LibvirtNFSVolumeDriver
       and moved into the main volume.py module. Kept for backwards
       compatibility in the Grizzly cycle to give users opportunity
       to configure before its removal in the Hxxxx cycle."""

    def __init__(self, *args, **kwargs):
        super(NfsVolumeDriver,
              self).__init__(*args, **kwargs)
        LOG.deprecated(
            _("The nova.virt.libvirt.volume_nfs.NfsVolumeDriver "
              "class is deprecated and will be removed in the "
              "Hxxxx release. Please update nova.conf so that "
              "the 'libvirt_volume_drivers' parameter refers to "
              "nova.virt.libvirt.volume.LibvirtNFSVolumeDriver."))


import argparse
import os
from pathlib import Path
from app import *

# Parse args ('-z' for location of zip file)
# Return location of zip file and project's name
def get_from_cli():
    parser = argparse.ArgumentParser()

    parser.add_argument('-z', '--zipfile',
                        required=True,
                        help="Project's ZIP file")
    args = parser.parse_args()

    if not os.path.basename(args.zipfile).endswith('.zip'):
        print("Not in ZIP format!\nExiting...")
        exit()
    elif not os.path.isfile(args.zipfile):
        print("File does not exist!\nExiting...")
        exit()
    else:
        return args.zipfile, Path(args.zipfile).stem

if __name__ == '__main__':
    zipfile, prj_name = get_from_cli()
    test = Application(zipfile, prj_name)
    print(test.scan())


class Node:
    #Constructor, Time O(1), Space O(1)
    def __init__(self, value):
        self.data = value
        self.next = None
        self.pre = None

class Deque:
    #Constructor, Time O(1), Space O(1)
    def __init__(self):
        self.front = self.rear = None
        self.deque_size = 0

    # Add at the head, Time O(1), Space O(1)
    def insert_first(self, value):
        new_node = Node(value)
        if self.front == None: # edge case
            self.rear = new_node
        else:
            self.front.pre = new_node
            new_node.next = self.front
        self.front = new_node
        self.deque_size += 1

    # Add at the tail, Time O(1), Space O(1)
    def insert_last(self, value):
        new_node = Node(value)
        if self.front == None:
            self.front = new_node
        else:
            self.rear.next = new_node
            new_node.pre = self.rear
        self.rear = new_node
        self.deque_size += 1

    # Delete the first node, Time O(1), Space O(1)
    def delete_first(self):
        if self.front == None:   #empty list
            return
        if self.front != self.rear:  # at least two nodes
            self.front = self.front.next
            self.front.pre = None
        else :
            self.front = self.rear = None #edge case, last node
        self.deque_size -= 1

    # Delete the last node, Time O(1), Space O(1)
    def delete_last(self):
        if self.front == None:  #empty list
             return
        if self.front != self.rear: # at least two nodes
            self.rear =  self.rear.pre
            self.rear.next = None
        else :
           self.front = self.rear = None #edge case, last node
        self.deque_size -= 1

    #Return front value, Time O(1), Space O(1)
    def get_first(self) :
        if self.is_empty():
            return None
        return self.front.data

    #Return last value, Time O(1), Space O(1)
    def get_last(self) :
        if self.is_empty():
            return None
        return self.rear.data

    #Print all, Time O(n), Space O(1), n is number of items in queue
    def print(self) :
        node = self.front
        while node != None:
            print(str(node.data), end= " ")
            node = node.next
        print()

    #Return length, Time O(1), Space O(1)
    def size(self) :
        return self.deque_size

    #Check empty, Time O(1), Space O(1)
    def is_empty(self):
        return self.front == None

# Test
if __name__ == '__main__':
    #Initialize, enqueue, size
    deque = Deque()
    deque.insert_first(4)
    deque.insert_last(64)
    deque.insert_last(-6)
    deque.insert_last(3)
    deque.insert_last(32)
    deque.insert_last(-6)
    deque.insert_last(11)
    deque.insert_first(19)
    deque.print()
    print("size: " + str(deque.size()))
    print("first: " + str(deque.get_first()))
    print("last: " + str(deque.get_last()))

    #Dequeue
    deque.delete_first()
    deque.delete_last()
    deque.print()
    print("size: " + str(deque.size()))
    print("first " + str(deque.get_first()))
    print("last: " + str(deque.get_last()))

    #enqueue again
    deque.insert_last(70)
    deque.print()
    print("size: " + str(deque.size()))
    print("first: " + str(deque.get_first()))
    print("last: " + str(deque.get_last()))


import tkinter as tk
import os
from PIL import ImageTk, Image

class ToggleButton(tk.Frame):

    def __init__(self, parent, controller, size, bg='#92D050', command=None, state='off',
                 on_command=None, off_command=None):
        super().__init__(master=parent, bg=bg, width=size[0], height=size[1])
        self.parent = parent
        self.controller = controller
        self.size = size
        self.state = state
        self.off_command = off_command
        self.on_command = on_command

        self.off_pic = ImageTk.PhotoImage(
            self.controller.pictures['toggle_off'].resize(self.size), master=self.controller)
        self.on_pic = ImageTk.PhotoImage(
            self.controller.pictures['toggle_on'].resize(self.size), master=self.controller)

        self.layout()

    def layout(self):
        current_pic = self.off_pic
        if self.state == 'on':
            current_pic = self.on_pic
        canvas = tk.Canvas(self, width=self.size[0], height=self.size[1],
                           bg='#92D050', bd=0, highlightthickness=0, relief='ridge', cursor='hand2')
        pic = canvas.create_image(0, 0, anchor=tk.NW, image=current_pic)
        canvas.image = current_pic

        canvas.pack(fill=tk.BOTH, expand=True)

        global on_p
        on_p = False

        def bind_canvas_click(*args):
            global on_p
            if on_p == False:
                return
            if self.state == 'off':
                canvas.itemconfig(pic, image=self.on_pic)
                canvas.image = self.on_pic
                self.state = 'on'
                try:
                    self.on_command()
                except Exception as ex:
                    print(ex)
                    pass

            else:
                canvas.itemconfig(pic, image=self.off_pic)
                canvas.image = self.off_pic
                self.state = 'off'
                try:
                    self.off_command()
                except Exception as ex:
                    print(ex)
                    pass

        def bind_enter(*args):
            global on_p
            on_p = True

        def bind_leave(*args):
            global on_p
            on_p = False
        canvas.bind('<ButtonRelease-1>', bind_canvas_click)
        canvas.bind('<Enter>', bind_enter)
        canvas.bind('<Leave>', bind_leave)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 14:32:24 2021

@author: ran
"""

import cv2
import numpy as np
import face_recognition
import os

path="database"
images=[]
classNames=[]
mylist= os.listdir(path)
print(mylist)

for clas in mylist:
    curImg=cv2.imread(f'{path}/{clas}')
    print(len(curImg))
    images.append(curImg)
    classNames.append(os.path.splitext(clas)[0])
print(classNames)

def findEncodings(images):
    encodeList=[]
    for img in images:
        img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
        encode=face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
        #faceLoc= face_recognition.face_locations(img)[0]
        return encodeList

encodeListKnown=findEncodings(images)
print(len(encodeListKnown))
#cv2.rectangle(imageElon,(faceLoc1[3],faceLoc1[0],faceLoc1[1],faceLoc1[2]),(255,0,255), 2)


import cv2
import numpy as np
import time

from adas_helper_functions import *
from ldw_helper_functions import *

countL = 0
countR = 0
c = 0
number = 0
counter = 0

ref_left = np.array([-0.0001, 0, 300])
ref_right = np.array([-0.0001, 0, 500])
left_fit = np.array([-0.0001, 0, 300])
right_fit = np.array([-0.0001, 0, 500])

currentL = np.zeros([3])
previousL = np.zeros([3])
currentR = np.zeros([3])
previousR = np.zeros([3])

DAY_BRIGHTNESS_TRESH = 30

def run_pipeline(frame):
    global ref_left, ref_right

    # Pre-processing

    """STEP#0 SCALE TO FIXED"""
    frame = scale_to_fixed(frame)
    # (h2, w2) = frame.shape[:2]

    brightness = getBrightness(frame)

    # ---------LDW PIPELINE

    """LDW-STEP#1 CROP ROAD ROI"""
    crop_road_roi_frame = crop_road_roi(frame, frame_output=False)

    """LDW-STEP#2 PERSPECTIVE TRANSFORM"""
    warped_image = apply_perspective_transform(frame, crop_road_roi_frame, toWarp=True)
    cv2.imshow("warp",warped_image)
    blur = cv2.GaussianBlur(warped_image, (5, 5), 0)
    """LDW-STEP#3 TIME CONDITION CHECK & BINARIZE"""
    if brightness > DAY_BRIGHTNESS_TRESH:
        # WHEN CLEAR BRIGHT DAY
        sharpened_image = sharpened(blur)
        binaryImage = compute_binary_image(warped_image, window_name="1st binary", output_show=False)
        # cv2.imshow("binary",binaryImage)
        whites = cv2.countNonZero(binaryImage)
        # print(whites)
        # WHITE COUNTS FOR WHEN IT RAINS
        if 0 < whites < 3000:
            binaryImage = edge_filter(warped_image, binaryImage)

        else:
            # morph top - remove big region
            # morph open - remove small region ie. erosion
            kernel_1 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9))
            environment = cv2.morphologyEx(binaryImage, cv2.MORPH_TOPHAT, kernel_1)
            kernel_2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
            binaryImage = cv2.morphologyEx(environment, cv2.MORPH_OPEN, kernel_2)

    else:
        # WHEN IT IS NOT CLEAR BRIGHT DAY (NIGHT || UNDER BRIDGE)
        # denoise = cv2.fastNlMeansDenoisingColored(warped_image)
        sharpened_image = sharpened(warped_image)
        # sharpened_image = cv2.bilateralFilter(sharpened_image, 9, 18, 9 / 2)
        # cv2.imshow("bila",sharpened_image)
        binaryImage1 = compute_binary_image(sharpened_image, window_name="1st binary", output_show=False)
        binaryImage = edge_filter(warped_image, binaryImage1)

        # whites = cv2.countNonZero(binaryImage)

    """LDW-STEP#4 DEFINE LANE-LINES"""
    leftx, lefty, rightx, righty, left_lane_inds, right_lane_inds = extract_lanes_pixels(binaryImage, plot_show=True)
    left_fit, right_fit = poly_fit(leftx, lefty, rightx, righty, left_lane_inds, right_lane_inds,
                                   binaryImage, output_show=False)

    """LDW-STEP#5 SANITY CHECK"""
    sanity_stat = sanity_check(leftx, rightx, left_fit, right_fit, 0, .25)

    """LDW-STEP#6 DEAL WITH RELIABLE & UNRELIABLE FIT"""
    if sanity_stat:
        # Save as last known reliable fit
        ref_left, ref_right = left_fit, right_fit
        left_fit_up, right_fit_up = left_fit, right_fit
    else:
        if len(leftx) == 0:
            right = right_fit[0] * 540 ** 2 + right_fit[1] * 540 + right_fit[2]
            left_fit_up = np.array([-0.0001, 0, right - 200])
            right_fit_up = right_fit

        elif len(rightx) == 0:
            left = left_fit[0] * 540 ** 2 + left_fit[1] * 540 + left_fit[2]
            right_fit_up = np.array([-0.0001, 0, left + 200])
            left_fit_up = left_fit

        else:
            left_fit_up, right_fit_up = ref_left, ref_right

    """LDW-STEP#7 TRIGGER WARNING"""
    color, center = warning(left_fit_up, right_fit_up)

    if color == 1:
        color = (0, 0, 255)
    elif color == 2:
        color = (0, 255, 255)
    else:
        color = (255, 215, 0)

    warped_color_img = drawLine(frame, binaryImage, left_fit_up, right_fit_up, color, int(center))

    dewarped_image = apply_perspective_transform(frame, warped_color_img,  toWarp=False)

    frame = cv2.addWeighted(dewarped_image, 0.8, frame, 1.0, 0)
    cv2.line(frame, (int(640 / 2), 360), (int(640 / 2), 0), (0, 0, 255), 1)

    return frame

# source_frame = cv2.VideoCapture("C:/Users/default.DESKTOP-O651TTO/Documents/LDWS/SiangHW.mp4") #Day time video
# source_frame = cv2.VideoCapture("C:/Users/default.DESKTOP-O651TTO/Documents/Video ADAS/WIN_20180803_205421.MP4") # Night time video
# source_frame = cv2.VideoCapture("C:/Users/default.DESKTOP-O651TTO/Documents/Video ADAS/WIN_20180821_114234.MP4")
source_frame = cv2.VideoCapture("C:\\Users\\Sayang Nurul\\Lane detection2\\640 x 360\\Straight Lane.mp4")#Siang
 #  source_frame = cv2.VideoCapture("C:\\Users\\lenovo\\Documents\\Video ADAS\\WIN_20180803_205421.MP4") #mlm

_, test_frame = source_frame.read()
(h, w) = test_frame.shape[:2]
createtrackbar(h, w)
start = time.time()
count=0
while True:
    _, frame = source_frame.read()

    final_merge = run_pipeline(frame)

    cv2.imshow("FINAL-OUTPUT", final_merge)
    count=count+1;
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

end = time.time()
duration = end-start
print("time taken: ",duration, count)
source_frame.release()
cv2.destroyAllWindows()


def bfs(set,m,n,matrix): # queue为队列
    dir = [[0,1],[0,-1],[1,0],[-1,0]] # 数组中四个元素代表四个方向
    queue = list(set)
    while len(queue) > 0:
    	x, y = queue.pop() # 取出队头的元素，由于是一个坐标，使用两个变量来接收
    	for d in dir: # 循环遍历4个方向
    		nx = x + d[0]
    		ny = y + d[1]
    		if 0 <= nx and nx < m and 0 <= ny and ny < n: # 如果新的点在二维数组内
    			if matrix[nx][ny] >= matrix[x][y]:
    				if (nx, ny) not in set:
    					queue.append((nx,ny))
    					set.add((nx, ny))
    print(set)
def solve(matrix): # matrix为存储地图的二维数组
  	if not matrix:
  		return matrix # 如果二维数组为空，那么就返回空
  	m = len(matrix) # 表示二维数组有多少行
  	n = len(matrix[0]) # 表示二位数组有多少列
  	toPoint = set([(0,y) for y in range(n)]) # 上边的点的横坐标为0，纵坐标为0到n-1
  	leftPoint = set([(x,0) for x in range(m)]) # 左边的点的横坐标为0到m-1,纵坐标为0
  	bottomPoint = set([(m-1,y) for y in range(n)]) # 下边的点的横坐标为m-2,纵坐标为0到n-1
  	rightPoint = set([(x,n-1) for x in range(m)]) # 右边的点的横坐标为0到m-1，纵坐标为n-1
  	a = bfs(toPoint,m,n,matrix) # 依次调用4次bfs
  	bfs(leftPoint,m,n,matrix)
  	bfs(bottomPoint,m,n,matrix)
  	bfs(rightPoint,m,n,matrix)
  	result = toPoint & leftPoint & bottomPoint & rightPoint # 求集合的交集
  	return result
matrix = [[1,3,2,3,5],[3,4,5,6,3],[2,7,4,3,3],[5,2,2,3,1]]
s = solve(matrix)
print(s)

书籍/你也能看懂的python算法书/广度优先遍历应用2.py

广度优先遍历应用2.py


import torch
import torch.distributions as dist
from escnn import gspaces

from models.model import SteerableCNN
from utils import BatchGeometricTensor
from common.blocks import EmbeddingBlock

class SteerableCNN_QM9(SteerableCNN):
    def __init__(self, gspace: gspaces, filter_type: str, non_linearity: str,
                 n_g_blocks: int, num_nodes: list, num_classes: int,
                 connectivity: str, channels: list, max_freq: list, node_dim: int, edge_dim: int, edge_att_type: str,
                 use_bn: int, x_dist: dist = None, attr_dist: dist = None, pool_type: str = 'mean',
                 use_skipcons: bool = False, aggr: str = 'add', **kwargs):

        embed_block = EmbeddingBlock(
            non_linearity=non_linearity,
            channels=channels[0],
            L=max_freq[0],
            in_type=gspace.type(*(node_dim * [gspace.trivial_repr]))
        )

        super().__init__(embed_block, filter_type, non_linearity, n_g_blocks, num_nodes, num_classes,
                 connectivity, channels, max_freq, edge_dim, edge_att_type, use_bn,
                 x_dist, attr_dist, pool_type, use_skipcons, aggr, **kwargs)

    def forward(self, pos_in: torch.Tensor, batch: torch.Tensor,
                node_features: torch.Tensor = None, edge_index: torch.Tensor = None, edge_attr: torch.Tensor = None):
        """
        Forward pass of the network.

        Args:
            pos_in (torch.Tensor): Input positions of shape `(num_nodes, 3)`.
            batch (torch.Tensor): Batch vector of shape `(num_nodes, )`.
            node_features (torch.Tensor, optional): Node features of shape `(num_nodes, num_node_features)`.
                Defaults to None.
            edge_index (torch.Tensor, optional): Edge indices of shape `(2, num_edges)` for graph connectivity.
                Defaults to None.
            edge_attr (torch.Tensor, optional): Edge attributes of shape `(num_edges, num_edge_features)`.
                Defaults to None.

        Returns:
            torch.Tensor: Output tensor of shape `(num_samples, num_classes)`.
        """
        x = self.embed_block(node_features, pos_in)

        # induce connectivity if 'knn' or 'radius' passed
        if self.connectivity != "given":
            edge_index = None

        x = BatchGeometricTensor(
            x,
            batch,
            node_features=node_features,
            edge_index=edge_index,
            edge_attr=edge_attr,
        )
        x = self.g_blocks(x)
        x, batch = self.inv_block(x)
        x = self.pooling(x, batch)
        x = self.fully_net(x)

        return x


'''
Created on Jun 29, 2012

@author: Benjamin Dezile
'''

TEST_KEY = "test_key"
TEST_STR = "fdkslfds"
TEST_LIST = [4, "Fds", False, None]
TEST_DICT = { "a":1, "b":"fds", "c":False }
TEST_SET = set(TEST_LIST)
TEST_SORTED_SET = { 'name1':4.0, 'name2':3.0, 'name3':2.0, 'name4':1.0 }

from pyutils.lib.unit_test import TestSuite, test_case
from pyutils.lib.cache import Cache

class TestCache(TestSuite):
    ''' Unit test for Cache '''

    def setup(self):
        self.r = Cache.instance.redis
        Cache.flush()
        self.assert_equal(Cache.size(), 0)

    @test_case
    def test1_put_and_get_string(self):
        ''' Test putting/getting strings '''
        key = TEST_KEY + "_str"
        Cache.put(key, TEST_STR)
        obj = Cache.get(key)
        self.assert_not_none(obj)
        self.assert_equal(obj, TEST_STR)
        self.assert_true(Cache.has(key))

    @test_case
    def test2_put_and_get_list(self):
        ''' Test putting/getting lists '''
        key = TEST_KEY + "_list"
        Cache.put(key, TEST_LIST)
        obj = Cache.get(key)
        self.assert_not_none(obj)
        self.assert_equal(obj, TEST_LIST)
        self.assert_true(Cache.has(key))

    @test_case
    def test3_put_and_get_dict(self):
        ''' Test putting/getting dictionaries '''
        key = TEST_KEY + "_dict"
        Cache.put(key, TEST_DICT)
        obj = Cache.get(key)
        self.assert_not_none(obj)
        self.assert_equal(obj, TEST_DICT)
        self.assert_true(Cache.has(key))

    @test_case
    def test4_get_size(self):
        ''' Test getting the cache size '''
        self.assert_equal(Cache.size(), 3)

    @test_case
    def test5_remove_from(self):
        ''' Test removing from a set or list '''

        key = "testSet"
        Cache.put(key, set([1, 2, 3, 4, 5]))
        self.assert_true(Cache.has(key))
        self.assert_equal(self.r.scard(key), 5)
        Cache.remove_from(key, 3)
        self.assert_equal(self.r.scard(key), 4)

    @test_case
    def test6_union(self):
        ''' Test doing the union of two sets '''

        key1 = "testSetUnion1"
        key2 = "testSetUnion2"
        N = 10
        s = range(N)

        Cache.put(key1, set(s[:N/2]))
        Cache.put(key2, set(s[N/2:]))
        self.assert_true(Cache.has(key1))
        self.assert_equal(self.r.scard(key1), N/2)
        self.assert_true(Cache.has(key2))
        self.assert_equal(self.r.scard(key2), N/2)

        u = Cache.union(key1, key2)
        self.assert_not_none(u)
        self.assert_equal(len(u), N)
        for i in u:
            self.assert_in(int(i), s)

        (res_key, n) = Cache.union(key1, key2, inplace=True)
        self.assert_equal(n, N)
        self.assert_not_none(res_key)
        self.assert_equal(Cache.size(res_key), n)
        u = Cache.get(res_key)
        for i in u:
            self.assert_in(int(i), s)

    @test_case
    def test7_inter(self):
        ''' Test doing the intersection of two sets '''

        key1 = "testSetInter1"
        key2 = "testSetInter2"
        N = 10
        s = range(N)
        inter0 = [5, 6, 7]

        Cache.put(key1, set(s[3:8]))
        Cache.put(key2, set(s[5:]))
        self.assert_true(Cache.has(key1))
        self.assert_equal(self.r.scard(key1), N/2)
        self.assert_true(Cache.has(key2))
        self.assert_equal(self.r.scard(key2), N/2)

        inter = Cache.inter(key1, key2)
        self.assert_not_none(inter)
        self.assert_equal(len(inter), len(inter0))
        for i in inter:
            self.assert_in(int(i), inter0)

        (res_key, n) = Cache.inter(key1, key2, inplace=True)
        self.assert_equal(n, len(inter0))
        self.assert_not_none(res_key)
        self.assert_equal(Cache.size(res_key), n)
        inter = Cache.get(res_key)
        for i in inter:
            self.assert_in(int(i), inter0)

    @test_case
    def test8_sorted_sets(self):
        ''' Test dealing with sorted sets '''

        key = "testSortedSet"
        Cache.put(key, TEST_SORTED_SET, sorted=True)
        self.assert_true(Cache.has(key))
        self.assert_equal(Cache.size(key), len(TEST_SORTED_SET))
        self.assert_equal(self.r.type(key), Cache.REDIS_TYPE_SORTED_SET)

        items = Cache.get(key, range=(0, -1))
        self.assert_not_none(items)
        self.assert_equal(items, ['name4', 'name3', 'name2', 'name1'])

        items = Cache.get(key, score_range=(2.0, 3.0))
        self.assert_not_none(items)
        self.assert_equal(len(items), 2)
        self.assert_equal(items, ['name3', 'name2'])

    @test_case
    def test9_keys(self):
        ''' Test getting key listing based on patterns '''

        base_key = "test_key_unique_"
        for i in range(10):
            Cache.put("%s%s" % (base_key, i), "1")
        keys = Cache.keys("%s*" % base_key)
        self.assert_not_none(keys)
        self.assert_equal(len(keys), 10)

if __name__ == "__main__":
    TestCache().run()


import UNet.Up as Up
import UNet.Down as Down
import torch.nn as nn

class Unet(nn.Module):

    def __init__(self, down_channels = [1, 2], up_channels = [2, 1], retain_size=True):
        super().__init__()
        self.down_arc = Down.Down(down_channels)
        self.up_arc = Up.Up(up_channels)
        self.retain_size = retain_size
        self.result = nn.Conv2d(up_channels[-1], 4, 1)

    def forward(self, x, out_size=(512,512)):
        down_features = self.down_arc(x)
        res = self.up_arc(down_features[::-1][0], down_features[::-1][1:])
        res = self.result(res)
        if self.retain_size:
            res = nn.functional.interpolate(res, out_size)
        return res


N=input("Factoring! ")
n=int(N)
s=n

p=[]
exp=[]

two=0
while(n%2==0):
    two+=1
    n=n/2
if(two>0):
    p.append(2)
    exp.append(two)

three=0
while(n%3==0):
    three+=1
    n=n/3
if(three>0):
    p.append(3)
    exp.append(three)

i=1
while(n>1):
    ae=0
    be=0
    while(n%(6*i-1)==0):
        n=n/(6*i-1)
        ae=ae+1
    if(ae!=0):
        p.append(6*i-1)
        exp.append(ae)
#ここから以上と相同の処理
    while(n%(6*i+1)==0):
        n=n/(6*i+1)
        be=be+1
    if(be!=0):
        p.append(6*i+1)
        exp.append(be)
#ここまでで1つのiに対する処理が終わり、iを更新する
    i=i+1
    if(s>(6*i-1)*(6*i-1)):
        continue

ans=str(s)+" = "
for c in range(len(p)):
    if(exp[c]!=1):
        ans=ans+str(p[c])+"^"+str(exp[c])+"*"
    else:
        ans=ans+str(p[c])+"*"

if(s==1):
    print(str(s)+" = 1")
else:
    print(ans[:-1])


import torch
from PIL import Image
from mmocr.utils.ocr import MMOCR
from torchvision import transforms

to_tensor = transforms.ToTensor()

if __name__ == "__main__":

    # 导入模型到内存
    ocr = MMOCR(det='DB_r50', recog=None)
    img = Image.open(r'F:\OCR-TASK\OCR_Dataset\Other_back\0.png')
    results,feamap = ocr.readtext(to_tensor(img),
                                  output='./', export='./',
                                  feaName=["neck.lateral_convs.0",
                                           "neck.lateral_convs.1",
                                           "neck.lateral_convs.2",
                                           "neck.lateral_convs.3",
                                           "bbox_head.binarize.7"])

    print(feamap[0].fea.shape)
    print(feamap[1].fea.shape)
    print(feamap[2].fea.shape)
    print(feamap[3].fea.shape)
    print(torch.max(feamap[4].fea))


def sumar_digitos(a):
    suma=0
    for i in str(a):
        i+=str(a)
    return suma

numero=int(input("Pon un numero: "))
suma=sumar_digitos(numero)

if suma%2==0:
    print ("Es par")
else:
    print("Es impar")


from zope.interface import Attribute, Interface
from zope.schema import Dict, Text, TextLine, URI

from pyams_chat import _

CHAT_PING_ROUTE = 'chat.ping'
CHAT_WORKER_ROUTE = 'chat.worker'

REST_CONTEXT_ROUTE = 'chat.rest.context'
REST_NOTIFICATIONS_ROUTE = 'chat.rest.notifications'

class IChatMessage(Interface):
    """Chat message interface"""

    host = TextLine(title=_("Message host name"))

    channel = TextLine(title=_("Message channel"))

    action = TextLine(title=_("Message action"))

    category = TextLine(title=_("Message category"))

    status = TextLine(title=_("Message status"))

    title = TextLine(title=_("Message title"))

    message = Text(title=_("Message content"))

    image = URI(title=_("Message image URL"),
                required=False)

    source = Dict(title=_("Message source"),
                  description=_("Attributes of the principal which emitted the notification"),
                  key_type=TextLine(),
                  value_type=TextLine())

    target = Dict(title=_("Message target"),
                  description=_("Message targets can be principals, roles..."),
                  key_type=TextLine())

    url = TextLine(title=_("Notification URL"),
                   description=_("URL target of this message notification"),
                   required=False)

    timestamp = TextLine(title=_("Message timestamp in ISO-8601 format"))

    user_data = Dict(title=_("Internal user data"),
                     description=_("User data used for internal usage; these data are not "
                                   "sent in notifications contents"))

    def send(self):
        """Send notification to recipients"""

class IChatMessageExtension(Interface):
    """Chat message extension interface

    These extensions, defined as adapters, can be used to add custom
    information to an existing message.

    This interface doesn't provide any method, as adapters should
    directly extend the original message.
    """

    weight = Attribute("Optional ordering weight")

class IChatMessageHandler(Interface):
    """Chat message handler interface

    This interface is used to define adapters which can be used to
    define a message target based on it's category.
    """

    weight = Attribute("Optional ordering weight")

    def get_target(self):
        """Get message target"""

class IRedisClient(Interface):
    """Redis client interface for chat"""


from time import sleep

def wakkerofslapen():
    ochtend = input("opstaan of slapen: ")
    while ochtend == "slapen":
        print("je gaat weer verder slapen")
        sleep(2)
        print("na 15 minuten wordt je weer wakker")
        ochtend = input("opstaan of slapen: ")
    if ochtend == "opstaan":
        print("je staat op")
        sleep(2)
        print("ga je eerst douchen en dan eten of niet douchen")
def douchenofeten():
    naochtend = input("douchen of eten: ")
    if naochtend == "douchen":
        print("je gaat douchen")
        sleep(2)
        print("je bent klaar met douchen")
        sleep(2)
        print("je gaat nu eten")
        sleep(2)
        print("wat ga je eten")
    elif naochtend == "eten":
        print("je gaat eten")
        sleep(2)
        print("wat ga je eten? ")
def wateten():
    eten = input("niks, brood of ontbijtgranen: ")
    if eten == "niks":
        print("weet je het zeker")
        jaofnee = input("ja of nee: ")
        if jaofnee == "ja":
            print("je hebt honger")

        if jaofnee == "nee":
            print("wat ga je dan eten")
            wateten()
    if eten == "brood":
        print("je maakt brood")
    if eten == "ontbijtgranen":
        print("je maakt ontbijtgranen")
def metwatopvakantie():
    print("ga je met de trein of vliegtuig naar Nederland")
    sleep(2)
    opvakantie = input("trein of vliegtuig: ")
    if opvakantie == "trein":
        print("je gaat naar het centraal station")
    if opvakantie == "vliegtuig":
        print("je gaat naar het vliegveld")
def hotelofhuisje():
    print("ga je naar een hotel of naar een huisje?")
    hotelhuis = input("hotel of huisje: ")
    if hotelhuis == "hotel":
        print("je zoekt een hotel op waar je kan slapen")
        sleep(2)
        print("je hebt je hotel gevonden")
        sleep(2)
        print("je gaat nu uiteten of in het hotel eten")
        sleep(2)
        hotelwaareten()
    if hotelhuis == "huisje":
        print("je zoekt een huisje waar je kan slapen")
        sleep(2)
        print("je hebt je huisje gevonden")
        sleep(2)
        print("je gaat nu uiteten of etenhalen")
        sleep(2)
        huisjewaareten()
def hotelwaareten():
    eten = input("uiteten of hotel: ")
    if eten == "uiteten":
        print("je zoekt een restaurant")
        sleep(2)
        print("je hebt een restaurant gevonden")
        sleep(2)
        print("wat ga je eten")
        sleep(2)
        hotelwateten()
    if eten == "hotel":
        print("je gaat naar het restaurant van het hotel")
        sleep(2)
        print("wat ga je eten?")
        sleep(2)
        hotelwateten()
def huisjewaareten():
    eten = input("uiteten of etenhalen: ")
    if eten == "uiteten":
        print("je zoekt een restaurant")
        sleep(2)
        print("je hebt een restaurant gevonden")
        sleep(2)
        print("wat ga je eten")
        sleep(2)
        huisjewateten()
    if eten == "etenhalen":
        print("je gaat naar de supermarkt om eten te halen")
        sleep(2)
        print("wat ga je halen")
        sleep(2)
        etenhalen()
def hotelwateten():
    eten = input("burger of schnitzel: ")
    if eten == "burger":
        print("je eet de burger")
        sleep(2)
        print("je vondt hem lekker")
        sleep(2)
        hotelofstad()
    if eten == "schnitzel":
        print("je eet de schnitzel")
        sleep(2)
        print("je vondt hem lekker")
        sleep(2)
        hotelofstad()
def huisjewateten():
    eten = input("burger of schnitzel: ")
    if eten == "burger":
        print("je eet de burger")
        sleep(2)
        print("je vondt hem lekker")
        sleep(2)
        huisjeofstad()
    if eten == "schnitzel":
        print("je eet de schnitzel")
        sleep(2)
        print("je vondt hem lekker")
        sleep(2)
        huisjeofstad()
def etenhalen():
    eten = input("burger of schnitzel: ")
    if eten == "burger":
        print("je eet de burger")
        sleep(2)
        print("je vondt hem lekker")
        sleep(2)
        huisjeofstad()
    if eten == "schnitzel":
        print("je maakt de schnitzel")
        sleep(2)
        print("je eet de schnitzel")
        sleep(2)
        print("je vondt hem lekker")
        sleep(2)
        huisjeofstad()
def hotelofstad():
        print("ga je naar de stad of naar terug naar je hotel")
        sleep(2)
        buitenofbinnen = input("stad of hotel: ")
        if buitenofbinnen == "stad":
            print("je loopt naar de stad")
            sleep(2)
            print("je loopt een rondje door de stad")
            sleep(2)
            print("je wordt moe")
            sleep(2)
            print("je gaat weer naar je hotel")
            sleep(2)
            print("je gaat nog even op je telefoon voor dat je in slaap valt")
        if buitenofbinnen == "hotel":
            print("je loopt weer terug naar je hotel")
            sleep(2)
            print("je bent moe")
            sleep(2)
            print("je gaat in je bed liggen")
            sleep(2)
            print("je gaat nog even op je telefoon voor dat je in slaap valt")
def huisjeofstad():
    print("ga je naar de stad of terug naar je huisje")
    sleep(2)
    buitenofbinnen = input("stad of huisje: ")
    if buitenofbinnen == "stad":
        print("je loopt naar de stad")
        sleep(2)
        print("je loopt een rondje door de stad")
        sleep(2)
        print("je wordt moe")
        sleep(2)
        print("je gaat weer naar je huisje")
        sleep(2)
        print("je gaat nog even op je telefoon voor dat je in slaap valt")
    if buitenofbinnen == "huisje":
        print("je loopt weer terug naar je huisje")
        sleep(2)
        print("je bent moe")
        sleep(2)
        print("je gaat in je bed liggen")
        sleep(2)
        print("je gaat nog ecven op je telefoon voor dat je in slaap valt")
def naarhuisofblijven():
    wegofblijven = input("blijven of huis: ")
    if wegofblijven == "blijven":
        print("je gaat ontbijten ")
        sleep(2)
        print("je gaat weer door de stad lopen")
        sleep(2)
        print("je krijg wel honger")
        sleep(2)
        print("je zoekt een restaurant")
        sleep(2)
        print("je besteld wat te eten")
        sleep(2)
        print("je vondt het lekker")
        sleep(2)
        print("je gaat weer naar huis")
        sleep(2)
        print("hoe ga je naar huis")
        sleep(2)
        metwatterug()
    if wegofblijven == "huis":
        print("je gaat ontbijten")
        sleep(2)
        print("met wat ga je weer terug")
        sleep(2)
        metwatterug()
def metwatterug():
    weg = input("vliegtuig of trein: ")
    if weg == "vliegtuig":
        print("je gaat naar het vliegveld")
        sleep(2)
        print("je bent weer thuis")
    if weg == "trein":
        print("je gaat naar het centraal station")
        sleep(2)
        print("je bent weer thuis")
def feestenofthuis():
    feest = input("feestje of thuis: ")
    if feest == "feestje":
        print("je gaat naar het feestje")
        sleep(2)
        print("ga je drinken of niet")
        sleep(2)
        drinkenofniet()
    if feest == "thuis":
        print("je blijft thuis")
        sleep(2)
        print("ga je een film kijken of slapen")
        sleep(2)
        filmofslapen()
def filmofslapen():
    filmofslapen = input("film of slapen: ")
    if filmofslapen == "film":
        print("je gaat een film kijken")
        sleep(2)
        iemandbinnen()
    if filmofslapen == "slapen":
        print("je gaat slapen")
        sleep(2)
        print("je wordt niet meer wakker")
def drinkenofniet():
    drinkenofniet = input("drinken of niet drinken: ")
    if drinkenofniet == "drinken":
        print("je bent heel dronken")
        sleep(2)
        print("je gaat weer naar huis fietsen")
        sleep(2)
        print("je valt in een sloot en verdrinkt")
    if drinkenofniet == "niet drinken":
        print("je gaat weer naar huis fietsen")
        sleep(2)
        print("je bent weer thuis en gaat naar bed")
        sleep(2)
        print("je wordt niet meer wakker")
def iemandbinnen():
    print("er komt iemand je huis binnen")
    sleep(2)
    print("je hebt het niet door omdat je een film aan het kijken bent")
    sleep(2)
    print("hij komt je kamer binnen")
    sleep(2)
    print("hij steekt je neer")
    sleep(2)
    print("je overleeft het niet")

print("je wordt wakker")
sleep(2)
print("maak een keuzen opstaan of verder slapen")
sleep(2)
wakkerofslapen()
sleep(2)
douchenofeten()
sleep(2)
wateten()
sleep(2)
print("je pakt je spullen in")
sleep(2)
print("je gaat op vakantie")
sleep(2)
metwatopvakantie()
sleep(2)
print("je komt aan in Nederland")
sleep(2)
hotelofhuisje()
sleep(2)
print("je wordt weer wakker")
sleep(2)
print("wil je nog een dagje blijven of ga je weer naar huis")
sleep(2)
naarhuisofblijven()
sleep(2)
feestenofthuis()


'''
Created on Apr 8, 2015

@author: desposito
'''
import unittest
from Tkinter import Tk
from View.InstrumentView import InstrumentView

class Test(unittest.TestCase):

    def test_MANUAL_UI_TEST(self):
        root = Tk()
        IView = InstrumentView(root)
        IView.pack()
        root.mainloop()

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.test_MANUAL_UI_TEST']
    unittest.main()


#!/usr/bin/python
# codings: utf-8

l = []
ad = 's'

while ad == 's':
	l.append(input("Digite item: "))
	ad = input(str("Deseja continuar? s ou n?"))

print("A lista digitada é ", l)


from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import (
    DetailEmployee, ListPost, DetailPost, SearchPost,
    RecommandByJob, RecommandByViewLog, RecommandBySearchLog,
    RecommandByFollow
)

urlpatterns = [
    path('detail_employee/<str:emp_id>/', DetailEmployee.as_view()),
    path('list_post/', ListPost.as_view()),
    path('detail_post/<int:post_id>/', DetailPost.as_view()),
    path('search_post/', SearchPost.as_view()),
    path('recommand_by_job/', RecommandByJob.as_view()),
    path('recommand_by_view_log/', RecommandByViewLog.as_view()),
    path('recommand_by_search_log/', RecommandBySearchLog.as_view()),
    path('recommand_by_follow/', RecommandByFollow.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)


import streamlit as st
import plotly_express as px
import pandas as pd
import numpy as np
import datetime

data = pd.read_csv('cleaned_data.csv', index_col=0)

# Sidebar
st.sidebar.title("Sidebar Search")
st.sidebar.info("This is an application for our data analysis")

facility = st.sidebar.multiselect('What is the facility?', data['facilityID'].unique())
apt_title = st.sidebar.multiselect('Select Appointment?', data['appointmentTitle'].unique())

# Page

'''
# Observations:
- We can see that majority of our data is duplicates.
- Our memory usage has comedown from ***183 MB*** to ***4 MB*** .
- eventDate must be changed to a DateTime type
- We do not know what **pid** , **providerID** and **appointmentStatus** actually represent
- our memory usage is 183.1 MB, which will slow things down when using complex transformations.
- We need a different data slice from out database. This dataset is very imbalances.
- If we had access to the database scema, it would help in feature engineering

--------------------------------------------------------------------------------------------------------------------------------------

# ML model

--------------------------------------------------------------------------------------------------------------------------------------

## Dataset and Historical Analysis
'''
st.dataframe(data)
'''
### Unique counts
'''

st.dataframe(data.nunique())
'''
### Discription of Numerical
'''
st.dataframe(data.describe())

'''
### Appointment Titles

'''
st.dataframe(data.appointmentTitle.value_counts())
'''
### Facility
'''
st.dataframe(data.facilityID.value_counts())

'''
### Appointment Status
'''
st.dataframe(data.appointmentStatus.value_counts())

'''
### Datewise
'''
st.dataframe(data.eventDate.value_counts())

'''
### Grouped
'''
st.dataframe(data.groupby(['eventDate','lastName', 'firstName','facilityID']).nunique().sort_values(by=['facilityID'], ascending=False).head(20))

st.dataframe(data.groupby(['eventDate', 'facilityID','appointmentTitle']).nunique())

'''
---------------------------------------------------------------------------------------------------------------
'''
'''
## Running the model
'''

t = st.time_input("Run the model at:", datetime.time(8, 45))
st.write("The model will run at:", t)

option = st.selectbox( "How would you like to be contacted?", ("Email", "Home phone", "Mobile phone"))

'''
---------------------------------------------------------------------------------------------------------------
'''

'''
## Input from streamlit
'''

Patitent = st.text_input("Name of Patient ")
sex = st.selectbox("Sex",options=['Male' , 'Female'])
age = st.slider("Age", 1, 100,1)
p_class = st.selectbox("Patient Class",options=['A Class' , 'B Class' , 'C Class'])

# Filter dataframe
#new_df = data[(data['facilityID'].isin(facility)) & (data['appointmentTitle'].isin(apt_title))]
# write dataframe to screen
#st.dataframe(new_df)