# -*- coding: utf-8 -*-
# Spearmint
#
# Academic and Non-Commercial Research Use Software License and Terms
# of Use
#
# Spearmint is a software package to perform Bayesian optimization
# according to specific algorithms (the “Software”).  The Software is
# designed to automatically run experiments (thus the code name
# 'spearmint') in a manner that iteratively adjusts a number of
# parameters so as to minimize some objective in as few runs as
# possible.
#
# The Software was developed by Ryan P. Adams, Michael Gelbart, and
# Jasper Snoek at Harvard University, Kevin Swersky at the
# University of Toronto (“Toronto”), and Hugo Larochelle at the
# Université de Sherbrooke (“Sherbrooke”), which assigned its rights
# in the Software to Socpra Sciences et Génie
# S.E.C. (“Socpra”). Pursuant to an inter-institutional agreement
# between the parties, it is distributed for free academic and
# non-commercial research use by the President and Fellows of Harvard
# College (“Harvard”).
#
# Using the Software indicates your agreement to be bound by the terms
# of this Software Use Agreement (“Agreement”). Absent your agreement
# to the terms below, you (the “End User”) have no rights to hold or
# use the Software whatsoever.
#
# Harvard agrees to grant hereunder the limited non-exclusive license
# to End User for the use of the Software in the performance of End
# User’s internal, non-commercial research and academic use at End
# User’s academic or not-for-profit research institution
# (“Institution”) on the following terms and conditions:
#
# 1.  NO REDISTRIBUTION. The Software remains the property Harvard,
# Toronto and Socpra, and except as set forth in Section 4, End User
# shall not publish, distribute, or otherwise transfer or make
# available the Software to any other party.
#
# 2.  NO COMMERCIAL USE. End User shall not use the Software for
# commercial purposes and any such use of the Software is expressly
# prohibited. This includes, but is not limited to, use of the
# Software in fee-for-service arrangements, core facilities or
# laboratories or to provide research services to (or in collaboration
# with) third parties for a fee, and in industry-sponsored
# collaborative research projects where any commercial rights are
# granted to the sponsor. If End User wishes to use the Software for
# commercial purposes or for any other restricted purpose, End User
# must execute a separate license agreement with Harvard.
#
# Requests for use of the Software for commercial purposes, please
# contact:
#
# Office of Technology Development
# Harvard University
# Smith Campus Center, Suite 727E
# 1350 Massachusetts Avenue
# Cambridge, MA 02138 USA
# Telephone: (617) 495-3067
# Facsimile: (617) 495-9568
# E-mail: otd@harvard.edu
#
# 3.  OWNERSHIP AND COPYRIGHT NOTICE. Harvard, Toronto and Socpra own
# all intellectual property in the Software. End User shall gain no
# ownership to the Software. End User shall not remove or delete and
# shall retain in the Software, in any modifications to Software and
# in any Derivative Works, the copyright, trademark, or other notices
# pertaining to Software as provided with the Software.
#
# 4.  DERIVATIVE WORKS. End User may create and use Derivative Works,
# as such term is defined under U.S. copyright laws, provided that any
# such Derivative Works shall be restricted to non-commercial,
# internal research and academic use at End User’s Institution. End
# User may distribute Derivative Works to other Institutions solely
# for the performance of non-commercial, internal research and
# academic use on terms substantially similar to this License and
# Terms of Use.
#
# 5.  FEEDBACK. In order to improve the Software, comments from End
# Users may be useful. End User agrees to provide Harvard with
# feedback on the End User’s use of the Software (e.g., any bugs in
# the Software, the user experience, etc.).  Harvard is permitted to
# use such information provided by End User in making changes and
# improvements to the Software without compensation or an accounting
# to End User.
#
# 6.  NON ASSERT. End User acknowledges that Harvard, Toronto and/or
# Sherbrooke or Socpra may develop modifications to the Software that
# may be based on the feedback provided by End User under Section 5
# above. Harvard, Toronto and Sherbrooke/Socpra shall not be
# restricted in any way by End User regarding their use of such
# information.  End User acknowledges the right of Harvard, Toronto
# and Sherbrooke/Socpra to prepare, publish, display, reproduce,
# transmit and or use modifications to the Software that may be
# substantially similar or functionally equivalent to End User’s
# modifications and/or improvements if any.  In the event that End
# User obtains patent protection for any modification or improvement
# to Software, End User agrees not to allege or enjoin infringement of
# End User’s patent against Harvard, Toronto or Sherbrooke or Socpra,
# or any of the researchers, medical or research staff, officers,
# directors and employees of those institutions.
#
# 7.  PUBLICATION & ATTRIBUTION. End User has the right to publish,
# present, or share results from the use of the Software.  In
# accordance with customary academic practice, End User will
# acknowledge Harvard, Toronto and Sherbrooke/Socpra as the providers
# of the Software and may cite the relevant reference(s) from the
# following list of publications:
#
# Practical Bayesian Optimization of Machine Learning Algorithms
# Jasper Snoek, Hugo Larochelle and Ryan Prescott Adams
# Neural Information Processing Systems, 2012
#
# Multi-Task Bayesian Optimization
# Kevin Swersky, Jasper Snoek and Ryan Prescott Adams
# Advances in Neural Information Processing Systems, 2013
#
# Input Warping for Bayesian Optimization of Non-stationary Functions
# Jasper Snoek, Kevin Swersky, Richard Zemel and Ryan Prescott Adams
# Preprint, arXiv:1402.0929, http://arxiv.org/abs/1402.0929, 2013
#
# Bayesian Optimization and Semiparametric Models with Applications to
# Assistive Technology Jasper Snoek, PhD Thesis, University of
# Toronto, 2013
#
# 8.  NO WARRANTIES. THE SOFTWARE IS PROVIDED "AS IS." TO THE FULLEST
# EXTENT PERMITTED BY LAW, HARVARD, TORONTO AND SHERBROOKE AND SOCPRA
# HEREBY DISCLAIM ALL WARRANTIES OF ANY KIND (EXPRESS, IMPLIED OR
# OTHERWISE) REGARDING THE SOFTWARE, INCLUDING BUT NOT LIMITED TO ANY
# IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE, OWNERSHIP, AND NON-INFRINGEMENT.  HARVARD, TORONTO AND
# SHERBROOKE AND SOCPRA MAKE NO WARRANTY ABOUT THE ACCURACY,
# RELIABILITY, COMPLETENESS, TIMELINESS, SUFFICIENCY OR QUALITY OF THE
# SOFTWARE.  HARVARD, TORONTO AND SHERBROOKE AND SOCPRA DO NOT WARRANT
# THAT THE SOFTWARE WILL OPERATE WITHOUT ERROR OR INTERRUPTION.
#
# 9.  LIMITATIONS OF LIABILITY AND REMEDIES. USE OF THE SOFTWARE IS AT
# END USER’S OWN RISK. IF END USER IS DISSATISFIED WITH THE SOFTWARE,
# ITS EXCLUSIVE REMEDY IS TO STOP USING IT.  IN NO EVENT SHALL
# HARVARD, TORONTO OR SHERBROOKE OR SOCPRA BE LIABLE TO END USER OR
# ITS INSTITUTION, IN CONTRACT, TORT OR OTHERWISE, FOR ANY DIRECT,
# INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR OTHER
# DAMAGES OF ANY KIND WHATSOEVER ARISING OUT OF OR IN CONNECTION WITH
# THE SOFTWARE, EVEN IF HARVARD, TORONTO OR SHERBROOKE OR SOCPRA IS
# NEGLIGENT OR OTHERWISE AT FAULT, AND REGARDLESS OF WHETHER HARVARD,
# TORONTO OR SHERBROOKE OR SOCPRA IS ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGES.
#
# 10. INDEMNIFICATION. To the extent permitted by law, End User shall
# indemnify, defend and hold harmless Harvard, Toronto and Sherbrooke
# and Socpra, their corporate affiliates, current or future directors,
# trustees, officers, faculty, medical and professional staff,
# employees, students and agents and their respective successors,
# heirs and assigns (the "Indemnitees"), against any liability,
# damage, loss or expense (including reasonable attorney's fees and
# expenses of litigation) incurred by or imposed upon the Indemnitees
# or any one of them in connection with any claims, suits, actions,
# demands or judgments arising from End User’s breach of this
# Agreement or its Institution’s use of the Software except to the
# extent caused by the gross negligence or willful misconduct of
# Harvard, Toronto or Sherbrooke or Socpra. This indemnification
# provision shall survive expiration or termination of this Agreement.
#
# 11. GOVERNING LAW. This Agreement shall be construed and governed by
# the laws of the Commonwealth of Massachusetts regardless of
# otherwise applicable choice of law standards.
#
# 12. NON-USE OF NAME.  Nothing in this License and Terms of Use shall
# be construed as granting End Users or their Institutions any rights
# or licenses to use any trademarks, service marks or logos associated
# with the Software.  You may not use the terms “Harvard” or
# “University of Toronto” or “Université de Sherbrooke” or “Socpra
# Sciences et Génie S.E.C.” (or a substantially similar term) in any
# way that is inconsistent with the permitted uses described
# herein. You agree not to use any name or emblem of Harvard, Toronto
# or Sherbrooke, or any of their subdivisions for any purpose, or to
# falsely suggest any relationship between End User (or its
# Institution) and Harvard, Toronto and/or Sherbrooke, or in any
# manner that would infringe or violate any of their rights.
#
# 13. End User represents and warrants that it has the legal authority
# to enter into this License and Terms of Use on behalf of itself and
# its Institution.

import numpy as np
#import scipy.weave
from scipy.spatial.distance import cdist

def dist2(ls, x1, x2=None):
    # Assumes NxD and MxD matrices.
    # Compute the squared distance matrix, given length scales.

    if x2 is None:
        # Find distance with self for x1.

        # Rescale.
        xx1 = x1 / ls
        xx2 = xx1

    else:
        # Rescale.
        xx1 = x1 / ls
        xx2 = x2 / ls

    r2 = cdist(xx1,xx2,'sqeuclidean')

    return r2

def grad_dist2(ls, x1, x2=None):
    if x2 is None:
        x2 = x1

    # Rescale.
    x1 = x1 / ls
    x2 = x2 / ls

    N = x1.shape[0]
    M = x2.shape[0]
    D = x1.shape[1]
    gX = np.zeros((x1.shape[0],x2.shape[0],x1.shape[1]))

    code = \
    """
    for (int i=0; i<N; i++)
      for (int j=0; j<M; j++)
        for (int d=0; d<D; d++)
          gX(i,j,d) = (2/ls(d))*(x1(i,d) - x2(j,d));
    """
    try:
        weave.inline(code, ['x1','x2','gX','ls','M','N','D'], \
                           type_converters=weave.converters.blitz, \
                           compiler='gcc')
    except:
    # The C code weave above is 10x faster than this:
        for i in range(0,x1.shape[0]):
            gX[i,:,:] = 2*(x1[i,:] - x2[:,:])*(1/ls)

    return gX

def dist_Mahalanobis(U, x1, x2=None):
    W = np.dot(U,U.T)

# This function is useful if the data can appear in multiple forms
# but the code is being changed so that the data will always be an array.

# def extract_data(func):
#     """
#     Decorator function.

#     If the input arguments are dicts instead of ndarrays then this extracts
#     the ndarrays at the key 'inputs'. It makes the rest of the kernel cleaner
#     since they don't have to do any bookkeeping.
#     """
#     def inner(cls_instance, *args):
#         new_args = []
#         for data in args:
#             if isinstance(data, dict):
#                 if not data.has_key('inputs'):
#                     raise Exception('Data dict must have key "inputs".')
#                 new_args.append(data['inputs'])
#             elif isinstance(data, np.ndarray):
#                 new_args.append(data)
#             else:
#                 raise Exception('Data of type %s not supported in kernels.' % data.__class__)

#         return func(cls_instance, *new_args)
#     return inner


# Generated by Django 3.0.8 on 2020-07-06 10:58

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('measurements', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='measurement',
            name='diastolic_pressure',
            field=models.SmallIntegerField(default=80, verbose_name='Ciśnienie rozkurczowe'),
        ),
        migrations.AlterField(
            model_name='measurement',
            name='pulse',
            field=models.SmallIntegerField(default=60, verbose_name='Tętno'),
        ),
        migrations.AlterField(
            model_name='measurement',
            name='systolic_pressure',
            field=models.SmallIntegerField(default=120, verbose_name='Ciśnienie skurczowe'),
        ),
    ]


import os
import mlflow
import random
import hashlib
import numpy as np
import pandas as pd

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier

from src.git_autocommit import autocommit

SEED = 0
TRACKING_URI = 'http://localhost:5000'
EXPERIMENT_NAME = 'mnist'
random.seed(SEED)
np.random.seed(SEED)

def train(cfg):
    os.system("conda env export > environment.yaml")
    autocommit(file_paths=['./'], message='Another version of random forest')
    mlflow.set_tracking_uri(TRACKING_URI)
    mlflow.set_experiment(EXPERIMENT_NAME)

    digits = datasets.load_digits()

    n_samples = len(digits.images)
    X = digits.images.reshape((n_samples, -1))
    y = digits.target

    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.8, random_state=SEED)

    # Track hash of data & split
    data_hash = hashlib.md5()
    for df in [X_train, X_test, y_train, y_test]:
        data_hash.update(df)
    data_hash = data_hash.hexdigest()

    clf = RandomForestClassifier(**cfg, random_state=SEED)
    clf.fit(X_train, y_train)
    preds = clf.predict(X_test)

    scores = classification_report(y_test, preds, output_dict=True)

    df = pd.json_normalize(scores, sep='_')
    df = df.to_dict(orient='records')[0]

    with mlflow.start_run():
        mlflow.log_params(cfg)
        mlflow.log_param('data_hash', data_hash)
        mlflow.log_metrics(df)
    print(df['macro avg_f1-score'])

if __name__ == '__main__':
    cfg = {'n_estimators': 500,
           'max_depth': 25,
           'min_samples_split': 2,
           'min_samples_leaf': 1,
           }
    train(cfg)


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling

from .. import models

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union

    T = TypeVar('T')
    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

class VpnGatewaysOperations(object):
    """VpnGatewaysOperations operations.

    You should not instantiate this class directly. Instead, you should create a Client instance that
    instantiates it for you and attaches it as an attribute.

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~azure.mgmt.network.v2020_03_01.models
    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):
        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self._config = config

    def get(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.VpnGateway"
        """Retrieves the details of a virtual wan vpn gateway.

        :param resource_group_name: The resource group name of the VpnGateway.
        :type resource_group_name: str
        :param gateway_name: The name of the gateway.
        :type gateway_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: VpnGateway, or the result of cls(response)
        :rtype: ~azure.mgmt.network.v2020_03_01.models.VpnGateway
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.VpnGateway"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        accept = "application/json"

        # Construct URL
        url = self.get.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize('VpnGateway', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'}  # type: ignore

    def _create_or_update_initial(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        vpn_gateway_parameters,  # type: "models.VpnGateway"
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.VpnGateway"
        cls = kwargs.pop('cls', None)  # type: ClsType["models.VpnGateway"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self._create_or_update_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(vpn_gateway_parameters, 'VpnGateway')
        body_content_kwargs['content'] = body_content
        request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize('VpnGateway', pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize('VpnGateway', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'}  # type: ignore

    def begin_create_or_update(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        vpn_gateway_parameters,  # type: "models.VpnGateway"
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["models.VpnGateway"]
        """Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.

        :param resource_group_name: The resource group name of the VpnGateway.
        :type resource_group_name: str
        :param gateway_name: The name of the gateway.
        :type gateway_name: str
        :param vpn_gateway_parameters: Parameters supplied to create or Update a virtual wan vpn
         gateway.
        :type vpn_gateway_parameters: ~azure.mgmt.network.v2020_03_01.models.VpnGateway
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either VpnGateway or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_03_01.models.VpnGateway]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["models.VpnGateway"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._create_or_update_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                vpn_gateway_parameters=vpn_gateway_parameters,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize('VpnGateway', pipeline_response)

            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'},  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'}  # type: ignore

    def update_tags(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        vpn_gateway_parameters,  # type: "models.TagsObject"
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.VpnGateway"
        """Updates virtual wan vpn gateway tags.

        :param resource_group_name: The resource group name of the VpnGateway.
        :type resource_group_name: str
        :param gateway_name: The name of the gateway.
        :type gateway_name: str
        :param vpn_gateway_parameters: Parameters supplied to update a virtual wan vpn gateway tags.
        :type vpn_gateway_parameters: ~azure.mgmt.network.v2020_03_01.models.TagsObject
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: VpnGateway, or the result of cls(response)
        :rtype: ~azure.mgmt.network.v2020_03_01.models.VpnGateway
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.VpnGateway"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.update_tags.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(vpn_gateway_parameters, 'TagsObject')
        body_content_kwargs['content'] = body_content
        request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize('VpnGateway', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'}  # type: ignore

    def _delete_initial(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        accept = "application/json"

        # Construct URL
        url = self._delete_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 202, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'}  # type: ignore

    def begin_delete(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller[None]
        """Deletes a virtual wan vpn gateway.

        :param resource_group_name: The resource group name of the VpnGateway.
        :type resource_group_name: str
        :param gateway_name: The name of the gateway.
        :type gateway_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._delete_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})

        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'},  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'}  # type: ignore

    def _reset_initial(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> Optional["models.VpnGateway"]
        cls = kwargs.pop('cls', None)  # type: ClsType[Optional["models.VpnGateway"]]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        accept = "application/json"

        # Construct URL
        url = self._reset_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.post(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('VpnGateway', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    _reset_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset'}  # type: ignore

    def begin_reset(
        self,
        resource_group_name,  # type: str
        gateway_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["models.VpnGateway"]
        """Resets the primary of the vpn gateway in the specified resource group.

        :param resource_group_name: The resource group name of the VpnGateway.
        :type resource_group_name: str
        :param gateway_name: The name of the gateway.
        :type gateway_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either VpnGateway or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_03_01.models.VpnGateway]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["models.VpnGateway"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._reset_initial(
                resource_group_name=resource_group_name,
                gateway_name=gateway_name,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize('VpnGateway', pipeline_response)

            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'},  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_reset.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset'}  # type: ignore

    def list_by_resource_group(
        self,
        resource_group_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.ListVpnGatewaysResult"]
        """Lists all the VpnGateways in a resource group.

        :param resource_group_name: The resource group name of the VpnGateway.
        :type resource_group_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ListVpnGatewaysResult or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_03_01.models.ListVpnGatewaysResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ListVpnGatewaysResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list_by_resource_group.metadata['url']  # type: ignore
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ListVpnGatewaysResult', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways'}  # type: ignore

    def list(
        self,
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.ListVpnGatewaysResult"]
        """Lists all the VpnGateways in a subscription.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ListVpnGatewaysResult or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_03_01.models.ListVpnGatewaysResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ListVpnGatewaysResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-03-01"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list.metadata['url']  # type: ignore
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ListVpnGatewaysResult', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnGateways'}  # type: ignore


import os
import shutil

from nose.tools import assert_raises
from paradrop.lib.utils import pdos, pdosq
from paradrop.base import nexus, settings

class TestingNexus(nexus.NexusBase):
    pass

def setup():
    settings.loadSettings(mode="unittest")

def teardown():
    pdos.remove(settings.CONFIG_HOME_DIR)

###############################################################################
# Settings Assignment, Paths
###############################################################################

def testMetaAssignment():
    nex = TestingNexus()
    assert nex.info.version == 1

def testConfigLoadingEmpty():
    nex = TestingNexus()
    assert nex.info.pdid == None

def testConfigLoadingExisting():
    contents = dict(pdid='pd.damouse.aardvark', version=1, pdserver='http://paradrop.org', wampRouter='ws://paradrop.org:9080/ws')
    nexus.writeYaml(contents, settings.CONFIG_FILE)

    nex = TestingNexus()
    assert nex.info.pdid == 'pd.damouse.aardvark'
    assert nex.info.pdserver == 'http://paradrop.org'
    assert nex.info.wampRouter == 'ws://paradrop.org:9080/ws'
    pdos.remove(settings.CONFIG_FILE)

###############################################################################
# AttrWrapper
###############################################################################

def testWrapperDoesntAllowChanges():
    wrapper = nexus.AttrWrapper()

    wrapper.a = 1
    assert wrapper.a == 1

    def s():
        wrapper._lock()
        wrapper.a = 2

    assert_raises(AttributeError, s)

###############################################################################
# Setings Changes
###############################################################################

def testSaveCallbackTriggered():
    class Receiver:

        def __init__(self):
            self.received = False

        def onChange(self, k, v):
            self.received = True

    rec = Receiver()

    wrapper = nexus.AttrWrapper()
    wrapper.a = 1

    wrapper.setOnChange(rec.onChange)

    wrapper.a = 2

    assert wrapper.a == 2
    assert rec.received == True

def testSaveUpdatesYaml():
    nex = TestingNexus()
    nex.info.a = 1

    dic = pdosq.read_yaml_file(settings.CONFIG_FILE)
    assert dic['a'] == 1


from django.core.exceptions import ValidationError
from django.test.client import RequestFactory

from mock import patch
from nose.tools import assert_raises, eq_, ok_
from waffle import Flag

from flicks.base.regions import NORTH_AMERICA
from flicks.base.tests import TestCase
from flicks.videos.forms import VideoSearchForm
from flicks.videos.search import AUTOCOMPLETE_FIELDS

class VideoSearchFormTests(TestCase):
    def setUp(self):
        super(VideoSearchFormTests, self).setUp()
        self.factory = RequestFactory()
        self.request = self.factory.get('/')

    def test_popular_sort_include(self):
        """If the voting-end waffle flag is not set, include the popular option for sorting."""
        Flag.objects.create(name='voting-end', everyone=False)
        form = VideoSearchForm(self.request)
        ok_('popular' in [c[0] for c in form.fields['sort'].choices])

    def test_popular_sort_exclude(self):
        """If the voting-end waffle flag is set, do not include the popular option for sorting."""
        Flag.objects.create(name='voting-end', everyone=True)
        form = VideoSearchForm(self.request)
        ok_('popular' not in [c[0] for c in form.fields['sort'].choices])

    @patch('flicks.videos.forms.search_videos')
    def test_valid_search(self, search_videos):
        form = VideoSearchForm(self.request, {
            'query': 'asdf',
            'field': 'title',
            'region': NORTH_AMERICA,
            'sort': 'popular'
        })

        eq_(form.perform_search(), search_videos.return_value)
        search_videos.assert_called_with(
            query='asdf',
            fields=AUTOCOMPLETE_FIELDS['title'],
            region=NORTH_AMERICA,
            sort='popular'
        )

    @patch('flicks.videos.forms.search_videos')
    def test_empty_field_passes_none(self, search_videos):
        """If the field isn't specified, pass None to the fields parameter."""
        form = VideoSearchForm(self.request, {
            'query': 'asdf',
            'region': NORTH_AMERICA,
            'sort': 'popular'
        })

        eq_(form.perform_search(), search_videos.return_value)
        search_videos.assert_called_with(query='asdf', fields=None,
                                         region=NORTH_AMERICA, sort='popular')

    def test_invalid_form(self):
        """If the form fails validation, throw a ValidationError."""
        form = VideoSearchForm(self.request, {
            'region': -5,
            'sort': 'invalid'
        })

        with assert_raises(ValidationError):
            form.perform_search()

    def test_clean_no_query(self):
        """
        If no search query is specified, do not alter the sort value or
        choices.
        """
        form = VideoSearchForm(self.request, {'region': NORTH_AMERICA, 'sort': 'title'})
        form.full_clean()

        eq_(form.cleaned_data['sort'], 'title')
        choice_values = zip(*form.fields['sort'].choices)[0]
        ok_('' in choice_values)

    def test_clean_query(self):
        """
        If a search query is specified, remove the random option from the sort
        choices and, if the sort is currently set to random, switch to title
        sort.
        """
        form = VideoSearchForm(self.request, {'query': 'blah', 'sort': ''})
        form.full_clean()

        eq_(form.cleaned_data['sort'], 'title')
        choice_values = zip(*form.fields['sort'].choices)[0]
        ok_('' not in choice_values)

        # Check that sort is preserved if it is not random.
        form = VideoSearchForm(self.request, {'query': 'blah', 'sort': 'popular'})
        form.full_clean()

        eq_(form.cleaned_data['sort'], 'popular')
        choice_values = zip(*form.fields['sort'].choices)[0]
        ok_('' not in choice_values)

    def test_invalid_sort(self):
        """
        An invalid value for sort should not break clean.

        Regression test for an issue where a user was attempting to break Flicks by submitting a
        bunch of invalid values for sort.
        """
        form = VideoSearchForm(self.request, {'query': 'blah', 'sort': 'invalid'})
        form.full_clean()
        eq_(form.is_valid(), False)


from abc import ABC, abstractmethod
import os.path
import logging
from exceptions import UnknownCommandError, FailedCommandError
from sym_api_client_python.processors.sym_elements_parser import SymElementsParser
from sym_api_client_python.processors.sym_message_parser import SymMessageParser

# responses and views

class IResponse(ABC):

    @abstractmethod
    def update(self, action):
        pass

class NullResponse(IResponse):

    def update(self, action):
        pass

class IView(ABC):

    @abstractmethod
    def render(self, message):
        pass

# Controller interfaces and classes

class IResponds(ABC):

    @property
    @abstractmethod
    def responds_to(self):
        pass

class IController(ABC):

    @abstractmethod
    def update(self, action):
        pass

    @abstractmethod
    def render(self, message):
        pass

class GeneralController(IController, IResponds):

    def __init__(self, response, view):
        self._response = response
        self._view = view

    def update(self, action):
        self._response.update(action)

    def render(self, message):
        return self._view.render(message)

    @staticmethod
    def make_form_id(cmd):
        return cmd.strip().lower().replace('/', '').replace(' ', '_')

class Controllers(IController):

    def __init__(self, controllers=None):
        self._controllers = controllers if controllers is not None else {}
        self._msg_parser = SymMessageParser()
        self._elements_parser = SymElementsParser()

    def update(self, action):
        ky = self._elements_parser.get_form_id(action)
        try:
            c = self._controllers[ky]
        except KeyError:
            raise UnknownCommandError(ky)
        c.update(action)

    def render(self, message):
        msg = ' '.join(self._msg_parser.get_text(message))
        ky = GeneralController.make_form_id(msg)
        try:
            c = self._controllers[ky]
        except KeyError:
            raise UnknownCommandError(msg)
        return c.render(message)

    def add(self, controller):
        ky = controller.make_form_id(controller.responds_to)
        self._controllers[ky] = controller


import pdf_to_json as p2j

import json

url = "file:data/multilingual/Latn.FON/Serif_16/udhr_Latn.FON_Serif_16.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))


from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField
from wtforms.validators import Required

class GroupForm(FlaskForm):
    '''
    Class to create a wtf form for creating a pitch
    '''
    name =  StringField('Category Name', validators=[Required()])
    submit = SubmitField('Create')

class LineForm(FlaskForm):
    '''
    Class to create a wtf form for creating a pitch
    '''
    line_content =  StringField('One Minute Pitch', validators=[Required()])
    submit = SubmitField('Submit')

class CommentForm(FlaskForm):
    '''
    Class to create a wtf form for creating a feedback on a pitch
    '''
    comment_content =  TextAreaField('Comment', validators=[Required()])
    submit = SubmitField('Submit')

class UpvoteForm(FlaskForm):
    '''
    Class to create a wtf form for upvoting a pitch
    '''
    submit = SubmitField('Upvote')


from ..Qt import QtGui, QtCore, QtWidgets

__all__ = ['BusyCursor']

class BusyCursor(object):
    """Class for displaying a busy mouse cursor during long operations.
    Usage::

        with pyqtgraph.BusyCursor():
            doLongOperation()

    May be nested.
    """
    active = []

    def __enter__(self):
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
        BusyCursor.active.append(self)

    def __exit__(self, *args):
        BusyCursor.active.pop(-1)
        if len(BusyCursor.active) == 0:
            QtWidgets.QApplication.restoreOverrideCursor()


"""
MIT License

Copyright (c) 2020 Airbyte

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from typing import Any, Mapping, Tuple

from base_python import BaseClient

from .api import (
    API,
    AgentsAPI,
    CompaniesAPI,
    ContactsAPI,
    ConversationsAPI,
    FreshdeskError,
    FreshdeskNotFound,
    FreshdeskUnauthorized,
    GroupsAPI,
    RolesAPI,
    SatisfactionRatingsAPI,
    SkillsAPI,
    SurveysAPI,
    TicketsAPI,
    TimeEntriesAPI,
)

class Client(BaseClient):
    def __init__(self, domain, api_key, requests_per_minute: int = None):
        self._api = API(domain=domain, api_key=api_key, requests_per_minute=requests_per_minute)
        self._apis = {
            "agents": AgentsAPI(self._api),
            "companies": CompaniesAPI(self._api),
            "contacts": ContactsAPI(self._api),
            "conversations": ConversationsAPI(self._api),
            "groups": GroupsAPI(self._api),
            "roles": RolesAPI(self._api),
            "skills": SkillsAPI(self._api),
            "surveys": SurveysAPI(self._api),
            "tickets": TicketsAPI(self._api),
            "time_entries": TimeEntriesAPI(self._api),
            "satisfaction_ratings": SatisfactionRatingsAPI(self._api),
        }
        super().__init__()

    def settings(self):
        url = "settings/helpdesk"
        return self._api.get(url)

    def stream_has_state(self, name: str) -> bool:
        """Tell if stream supports incremental sync"""
        return hasattr(self._apis[name], "state")

    def get_stream_state(self, name: str) -> Any:
        """Get state of stream with corresponding name"""
        return self._apis[name].state

    def set_stream_state(self, name: str, state: Any):
        """Set state of stream with corresponding name"""
        self._apis[name].state = state

    def _enumerate_methods(self) -> Mapping[str, callable]:
        return {name: api.list for name, api in self._apis.items()}

    def health_check(self) -> Tuple[bool, str]:
        alive = True
        error_msg = None

        try:
            self.settings()
        except (FreshdeskUnauthorized, FreshdeskNotFound):
            alive = False
            error_msg = "Invalid credentials"
        except FreshdeskError as error:
            alive = False
            error_msg = repr(error)

        return alive, error_msg


from adder.full_adder import FullAdder
from comparator.comparator import Comparator
from decoder.decoder_mxn import Decoder_nxm
from flipflop.d import D_FlipFlop
from gate.and_gate import And
from gate.input_gate import Input
from gate.one_gate import One
from gate.or_gate import Or
from gate.xor_gate import Xor
from gate.zero_gate import Zero
from latch.d import D_Latch
from multiplexer.mux2x1 import Mux2x1
from multiplexer.mux_mxn import Mux_mxn
from multiplexer.mux4x2 import Mux4x2
from runner.circuit_runner import CircuitRunner
from signals.signal import Signal
from gate.not_gate import Not

import sys

sys.setrecursionlimit(1000)  # default is 1000

def turn_off_debug(every_thing=False):
    And.DEBUGMODE = every_thing
    Or.DEBUGMODE = every_thing
    Xor.DEBUGMODE = every_thing
    D_FlipFlop.DEBUGMODE = every_thing
    D_Latch.DEBUGMODE = every_thing
    Not.DEBUGMODE = every_thing
    Mux2x1.DEBUGMODE = every_thing
    Mux4x2.DEBUGMODE = every_thing
    Signal.DEBUGMODE = every_thing

def test1():
    clock = Signal()
    l1 = D_Latch(clock, None, "l1")

    l1.set_input(l1)
    l1.set()

    CircuitRunner.run([l1], clock, 4, [[l1]])

def test2():
    clock = Signal()
    d1 = D_FlipFlop(clock, None, "d1")
    not1 = Not(d1, "not")
    d1.set_input(not1)
    d1.set()

    for _ in range(20):
        clock.pulse()
        d1.logic()
        print(d1)

def johnson_counter(n=100):
    clock = Signal()
    bits = [D_FlipFlop(clock, None, f"d{i}") for i in range(n)]
    for i in range(1, n):
        bits[i].set_input(bits[i - 1])
        bits[i].reset()

    bits[0].set_input(Not(bits[-1], "not"))
    bits[0].reset()

    for _ in range(4 * n):
        clock.pulse()
        bits[0].logic()
        print("".join([str(b.q()) for b in bits]))

def multiplexer_test():
    mux = Mux4x2((One(), Zero(), One(), Zero()), (One(), Zero()), "my_mux")
    CircuitRunner.run([mux], None, None, [[mux]])

def n_bit_adder():
    clock = Signal()
    n = 200
    a, b = "01001" * 40, "01110" * 40

    d1 = [D_FlipFlop(clock, None, f"a{i}") for i in range(n)]
    d2 = [D_FlipFlop(clock, None, f"b{i}") for i in range(n)]

    adder = [FullAdder(None, None, f"adder{i}") for i in range(n)]

    res = [D_FlipFlop(clock, None, f"r{i}") for i in range(n)]

    for i in range(n):
        d1[i].set_input(d1[i])
        d2[i].set_input(d2[i])
        adder[i].set_input((d1[i], d2[i]))
        adder[i].set_cin(Zero() if i == 0 else adder[i - 1].cout)

        res[i].set_input(adder[i].sum)
        res[i].reset()

        if a[n - i - 1] == '0':
            d1[i].reset()
        else:
            d1[i].set()

        if b[n - 1 - i] == '0':
            d2[i].reset()
        else:
            d2[i].set()

    CircuitRunner.run(res, clock, 3, [res])

def bitsToGates(bitString, inputs):
    for i in range(len(bitString)):
        inputs[i].output = 0 if bitString[i] == "0" else 1

def n_multiplexer_test():
    inputs = [Input() for _ in range(32)]
    selectors = [Input() for _ in range(5)]
    mux = Mux_mxn(inputs, selectors, 5)

    bitsToGates("11001110011100111001110011100101", inputs)

    for i in range(32):
        i_bin = bin(i)[2:].zfill(5)
        bitsToGates(i_bin, selectors)

        CircuitRunner.run([mux], display=[[mux]])

def decoder_test():
    inputs = [Input() for _ in range(5)]
    dec = Decoder_nxm(inputs, 5)

    bitsToGates("11101", inputs)
    CircuitRunner.run([dec], display=[dec.outputs])

def comparator_test():
    i1 = [Input() for _ in range(5)]
    i2 = [Input() for _ in range(5)]
    comp = Comparator((i1, i2), 5)

    bitsToGates("11101", i1)
    bitsToGates("11101", i2)

    CircuitRunner.run([comp], display=[[comp]])

turn_off_debug(False)

johnson_counter(800)


import re
import gevent

from gevent.pywsgi import WSGIHandler
from socketio import transports
from geventwebsocket.handler import WebSocketHandler

class SocketIOHandler(WSGIHandler):
    path_re = re.compile(r"^/(?P<resource>[^/]+)/(?P<transport>[^/]+)(/(?P<session_id>[^/]*)/?(?P<rest>.*))?$")

    handler_types = {
        'websocket': transports.WebsocketTransport,
        'flashsocket': transports.FlashSocketTransport,
        'htmlfile': transports.HTMLFileTransport,
        'xhr-multipart': transports.XHRMultipartTransport,
        'xhr-polling': transports.XHRPollingTransport,
        'jsonp-polling': transports.JSONPolling,
    }

    def __init__(self, *args, **kwargs):
        self.socketio_connection = False
        self.allowed_paths = None

        super(SocketIOHandler, self).__init__(*args, **kwargs)

    def handle_one_response(self):
        self.status = None
        self.headers_sent = False
        self.result = None
        self.response_length = 0
        self.response_use_chunked = False

        path = self.environ.get('PATH_INFO')
        parts = SocketIOHandler.path_re.match(path)

        # Is this a valid SocketIO path?
        if parts:
            parts = parts.groupdict()
        else:
            return super(SocketIOHandler, self).handle_one_response()

        resource = parts['resource']
        if resource != self.server.resource:
            return super(SocketIOHandler, self).handle_one_response()

        transport_name = parts['transport']
        transport = SocketIOHandler.handler_types.get(transport_name)
        if transport is None:
            return super(SocketIOHandler, self).handle_one_response()

        session_id = parts.get('session_id')
        request_method = self.environ.get("REQUEST_METHOD")

        # In case this is WebSocket request, switch to the WebSocketHandler
        if transport in (transports.WebsocketTransport, \
                transports.FlashSocketTransport):
            self.__class__ = WebSocketHandler
            self.handle_one_response(call_wsgi_app=False)
            session = self.server.get_session()
        else:
            session = self.server.get_session(session_id)

        # Make the session object available for WSGI apps
        self.environ['socketio'].session = session

        # Create a transport and handle the request likewise
        self.transport = transport(self)
        jobs = self.transport.connect(session, request_method)

        if not session.wsgi_app_greenlet or not bool(session.wsgi_app_greenlet):
            # Call the WSGI application, and let it run until the Socket.IO
            # is *disconnected*, even though many POST/polling requests
            # come through.
            session.wsgi_app_greenlet = gevent.getcurrent()
            session.connected = True
            self.application(self.environ,
                             lambda status, headers, exc=None: None)
            session.connected = False

        gevent.joinall(jobs)


from django.test import TestCase
from .models import Foto,Comment,Follower,Profile
class ProfileTestClass(TestCase):

    # Set up method
    def setUp(self):
        self.profile= Profile(image = 'Jam.jpeg', name ='Muriuki', email ='james@moringaschool.com',bio = 'hdeydfedf')

    # Testing  instance
    def test_instance(self):
        self.assertTrue(self.profile,Follower)

    def tearDown(self):
        Follower.objects.all().delete()

    def test_save(self):
        self.profile.save_profile()
        profile= Profile.objects.all()
        self.assertTrue(len(profile)>=1)

    def test_upd(self):
        profile = Profile.objects.filter(id=1)
        profile.update(image = 'Kam.jpeg', name ='Murki', email ='james@morischool.com',bio = 'hdefedf')
        search = Profile.objects.filter(id=1)
        self.assertNotEqual(search,'Kam.jpeg')

    def test_dele(self):
        self.profile.save_profile()
        profi = Profile.objects.all()
        self.assertTrue(len(profi)>=0)

class CommentTestClass(TestCase):

    # Set up method
    def setUp(self):
        self.comment= Comment(comment = 'Fun')

    # Testing  instance
    def test_instance(self):
        self.assertTrue(self.comment,Comment)

     # Testing Save Method
    def test_save(self):
        self.comment.save_comment()
        comments = Comment.objects.all()
        self.assertTrue(len(comments) >= 1)

    def test_upd(self):
        comment = Comment.objects.filter(id=1)
        comment.update(comment ='Art')
        search = Comment.objects.filter(id=1)
        self.assertNotEqual(search,'Art')

    def test_del(self):
        self.comment.save_comment()
        comments = self.comment.dele_comment()
        comment = Comment.objects.all()
        self.assertTrue(len(comment)<=0)

    def tearDown(self):
        Comment.objects.all().delete()

class FotoTestClass(TestCase):

    def setUp(self):
        self.profile= Profile(image = 'Jam.jpeg', name ='Muriuki', email ='james@moringaschool.com',bio = 'hdeydfedf')
        self.profile.save_profile()

        self.new_comment = Comment(comment = 'Fun')
        self.new_comment.save_comment()

        self.new_photos= Foto(image = 'Jam.jpeg', name ='Muriuki', caption ='jamesmoringaschoolcom',like = "2", comments=self.new_comment)
        self.new_photos.save_pic()

    def tearDown(self):
        Profile.objects.all().delete()
        Comment.objects.all().delete()
        Foto.objects.all().delete()

    def test_save_pick(self):
        self.new_photos= Foto(image = 'Jam.jpeg', name ='Muriuki', caption ='jamesmoringaschoolcom',like = "2", comments=self.new_comment)
        self.new_photos.save_pic()
        picture = Foto.objects.all()
        self.assertTrue(len(picture)>=1)

    def test_dele_pick(self):
        self.new_photos= Foto(image = 'Jam.jpeg', name ='Muriuki', caption ='jamesmoringaschoolcom',like = "2", comments=self.new_comment)
        self.new_photos.save_pic()
        picture = self.new_photos.dele_pic()
        delete = Foto.objects.all()
        self.assertTrue(len(delete)>=0)

    def test_upd_pic(self):
        image = Foto.objects.filter(id=1)
        image.update(name ='lez.jpeg')
        search = Foto.objects.filter(id=1)
        self.assertNotEqual(search,'lez.jpeg')

    def test_pic_id(self):
        self.image = Foto(image = 'Jam.jpeg', name ='Muriuki', caption ='jamesmoringaschoolcom',like = "2", comments=self.new_comment)
        self.image.save_pic()
        search = Foto.image_by_id(self.image.id)
        self.assertNotEqual(search,self.image)


def get_set():
    return set(map(int, input().split()))

def is_super_set(main, sets):
    for set in sets:
        if not main.issuperset(set):
            return False

    return True

A = get_set()
queries = int(input())
sets = []

for _ in range(queries):
    sets.append(get_set())

print(is_super_set(A, sets))


# SPDX-License-Identifier: Apache-2.0

import os
from distutils.version import StrictVersion
import numpy as np
import onnx
from onnxruntime import __version__ as ort_version
from skl2onnx import __max_supported_opset__ as max_opset
from skl2onnx.common._topology import OPSET_TO_IR_VERSION
from .tests_helper import dump_data_and_model  # noqa
from .tests_helper import (  # noqa
    dump_one_class_classification,
    dump_binary_classification,
    dump_multilabel_classification,
    dump_multiple_classification)
from .tests_helper import (  # noqa
    dump_multiple_regression,
    dump_single_regression,
    convert_model,
    fit_classification_model,
    fit_multilabel_classification_model,
    fit_clustering_model,
    fit_regression_model,
    binary_array_to_string,
    path_to_leaf
)

def create_tensor(N, C, H=None, W=None):
    if H is None and W is None:
        return np.random.rand(N, C).astype(np.float32, copy=False)
    elif H is not None and W is not None:
        return np.random.rand(N, C, H, W).astype(np.float32, copy=False)
    else:
        raise ValueError('This function only produce 2-D or 4-D tensor.')

def _get_ir_version(opv):
    if opv >= 15:
        return 8
    if opv >= 12:
        return 7
    if opv >= 11:
        return 6
    if opv >= 10:
        return 5
    if opv >= 9:
        return 4
    if opv >= 8:
        return 4
    return 3

def max_onnxruntime_opset():
    """
    See `Versioning.md
    <https://github.com/microsoft/onnxruntime/blob/
    master/docs/Versioning.md>`_.
    """
    vi = StrictVersion(ort_version.split('+')[0])
    if vi >= StrictVersion("1.9.0"):
        return 15
    if vi >= StrictVersion("1.8.0"):
        return 14
    if vi >= StrictVersion("1.6.0"):
        return 13
    if vi >= StrictVersion("1.3.0"):
        return 12
    if vi >= StrictVersion("1.0.0"):
        return 11
    if vi >= StrictVersion("0.4.0"):
        return 10
    if vi >= StrictVersion("0.3.0"):
        return 9
    return 8

TARGET_OPSET = int(
    os.environ.get(
        'TEST_TARGET_OPSET',
        min(max_onnxruntime_opset(),
            min(max_opset,
                onnx.defs.onnx_opset_version()))))

TARGET_IR = int(
    os.environ.get(
        'TEST_TARGET_IR',
        min(OPSET_TO_IR_VERSION[TARGET_OPSET],
            _get_ir_version(TARGET_OPSET))))