"""Forms, fields, and widgets for gathering and displaying consent."""

from django import forms
from django.contrib import messages
from django.forms.widgets import MultiWidget, Widget
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.html import format_html_join
from django.utils.translation import gettext_lazy as _

from djblets.privacy.consent import (Consent,
                                     get_consent_requirements_registry,
                                     get_consent_tracker)

class ConsentRequirementWidget(Widget):
    """A widget for displaying and gathering consent information.

    This presents the consent requirement in an easy-to-digest form, and
    makes it easy for users to choose to allow or block the thing requiring
    consent.

    This is meant to be used with :py:class:`ConsentRequirementField`.
    """

    def __init__(self, consent_requirement=None, attrs=None):
        """Initialize the widget.

        Args:
            consent_requirement (djblets.privacy.consent.base.
                                 ConsentRequirement, optional):
                The consent requirement information. If not provided, this
                must be directly set on the instance before rendering the
                widget.

            attrs (dict, optional):
                HTML attributes for the widget. This is used only to set an
                ``id`` attribute for the field.
        """
        super(ConsentRequirementWidget, self).__init__(attrs=attrs)

        self.consent_requirement = consent_requirement

    def render(self, name, value, attrs=None, renderer=None):
        """Render the widget.

        Args:
            name (unicode):
                The base name used for the ``<input>`` elements. Specific
                names will be composed from this.

            value (unicode):
                The current value for the field.

            attrs (dict, optional):
                HTML attributes for the widget. This is used only to set an
                ``id`` attribute for the field.

            renderer (django.forms.renderers.BaseRenderer, optional):
                The form renderer.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML for the widget.
        """
        if attrs is None:
            attrs = {}

        return render_to_string(
            'privacy/consent/consent_widget.html',
            context={
                'ALLOW': ConsentRequirementField.ALLOW,
                'BLOCK': ConsentRequirementField.BLOCK,
                'consent_requirement': self.consent_requirement,
                'icons': self.consent_requirement.icons,
                'id': attrs.get('id', ''),
                'name': name,
                'value': value,
            })

    def value_from_datadict(self, data, files, name):
        """Return the field value from the submitted form data.

        Args:
            data (dict):
                The submitted form data.

            files (dict, unused):
                The submitted files data.

            name (unicode):
                The base name for the form fields.

        Returns:
            unicode:
            A value for the fields. This will be one of
            :py:attr:`ConsentRequirementField.ALLOW`,
            :py:attr:`ConsentRequirementField.BLOCK`, or ``None``.
        """
        return data.get('%s_choice' % name)

class MultiConsentRequirementsWidget(MultiWidget):
    """A widget for displaying and gathering multiple consent information.

    This adds a :py:class:`ConsentRequirementWidget` for each consent
    requirement provided to the widget.

    This is meant to be used with :py:class:`MultiConsentRequirementsField`.
    """

    def __init__(self, consent_requirements, attrs=None):
        """Initialize the widget.

        Args:
            consent_requirements (list of djblets.privacy.consent.base.
                                  ConsentRequirement):
                The list of consent requirements.

            attrs (dict, optional):
                HTML attributes for the widget. This is used only to set an
                ``id`` attribute for the field.
        """
        self.consent_requirements = consent_requirements

        super(MultiConsentRequirementsWidget, self).__init__(
            widgets=[
                ConsentRequirementWidget(consent_requirement=requirement)
                for requirement in consent_requirements
            ],
            attrs=attrs)

    def render(self, name, value, attrs=None, renderer=None):
        """Render the widget.

        Args:
            name (unicode):
                The base name used for the ``<input>`` elements. Specific
                names will be composed from this.

            value (list of unicode):
                The current values for the fields.

            attrs (dict, optional):
                HTML attributes for the widget. This is used only to set a
                base ``id`` attribute for the fields.

            renderer (django.forms.renderers.BaseRenderer, optional):
                The form renderer.

        Returns:
            django.utils.safestring.SafeText:
            The rendered HTML for the widget.
        """
        if not isinstance(value, list):
            value = self.decompress(value)

        final_attrs = self.build_attrs(attrs)
        field_id = final_attrs.get('id')
        output = []

        for i, widget in enumerate(self.widgets):
            consent_requirement = widget.consent_requirement
            requirement_id = consent_requirement.requirement_id

            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None

            if field_id:
                final_attrs = dict(final_attrs,
                                   id='%s_%s' % (field_id, requirement_id))

            rendered = widget.render('%s_%s' % (name, requirement_id),
                                     widget_value, final_attrs,
                                     renderer=renderer)
            output.append((rendered,))

        return format_html_join('', '{0}', output)

    def value_from_datadict(self, data, files, name):
        """Return the field values from the submitted form data.

        Args:
            data (dict):
                The submitted form data.

            files (dict, unused):
                The submitted files data.

            name (unicode):
                The base name for the form fields.

        Returns:
            list of unicode:
            A list of values for all the fields, in the order of the list of
            consent requirements provided to the widget. Each item will be
            one of :py:attr:`ConsentRequirementField.ALLOW`,
            :py:attr:`ConsentRequirementField.BLOCK`, or ``None``.
        """
        return [
            widget.value_from_datadict(
                data,
                files,
                '%s_%s' % (name, widget.consent_requirement.requirement_id))
            for widget in self.widgets
        ]

    def decompress(self, value):
        """Decompress a list of values for the widget.

        This is required by the parent class, and is responsible for taking the
        provided data and returning a list of values that can be used for the
        sub-widgets.

        Args:
            value (list):
                The list of values (or ``None``) to normalize and return.

        Returns:
            list of unicode:
            The resulting list of values. This may be empty.
        """
        return value or []

class ConsentRequirementField(forms.ChoiceField):
    """A form field for displaying and gathering consent information.

    This presents the consent requirement in an easy-to-digest form, and
    makes it easy for users to choose to allow or block the thing requiring
    consent.

    The cleaned result from this field is a
    :py:class:`~djblets.privacy.consent.base.ConsentData` instance, which
    can be recorded directly in the tracker.
    """

    ALLOW = 'allow'
    BLOCK = 'block'

    CHOICES = (
        (ALLOW, _('Allow')),
        (BLOCK, _('Block')),
    )

    widget = ConsentRequirementWidget

    default_error_messages = {
        'required': _('You must choose Allow or Block to continue.'),
    }

    def __init__(self, consent_requirement, user=None, consent_source=None,
                 extra_consent_data=None, **kwargs):
        """Initialize the field.

        Args:
            consent_requirement (djblets.privacy.consent.base.
                                 ConsentRequirement):
                The consent requirement information.

            user (django.contrib.auth.models.User, optional):
                The user viewing the form. If provided, the default value
                for the field will be based on the choice already made by
                the user, if any.

            consent_source (unicode, optional):
                The source to record in the consent audit trail for the
                consent choice saved in this field.

            extra_consent_data (dict, optional):
                Extra information to record in the consent audit trail for
                the consent choice saved in this field.

            **kwargs (dict):
                Additional keyword arguments to pass to the parent class.
        """
        super(ConsentRequirementField, self).__init__(
            choices=self.CHOICES,
            label='',
            required=True,
            **kwargs)

        self.consent_requirement = consent_requirement
        self.consent_source = consent_source
        self.extra_consent_data = extra_consent_data
        self.widget.consent_requirement = consent_requirement

        if user and user.is_authenticated:
            self.set_initial_from_user(user)

    def set_initial_from_user(self, user):
        """Set the initial state of the field based on a user's prior consent.

        This is called automatically if passing a user to the constructor.
        Otherwise, it should be called manually when setting up a form.

        Args:
            user (django.contrib.auth.models.User):
                The user viewing the form.
        """
        assert user
        assert user.is_authenticated

        self.initial = self.consent_requirement.get_consent(user)

    def prepare_value(self, value):
        """Prepare a value for use in the field.

        This will convert a :py:class:`~djblets.privacy.consent.base.Consent`
        value to a value suitable for use in the field.

        Args:
            value (djblets.privacy.consent.base.Consent):
                The value to convert.

        Returns:
            unicode:
            A valid value for use in the field.
        """
        return {
            Consent.GRANTED: self.ALLOW,
            Consent.DENIED: self.BLOCK,
        }.get(value)

    def clean(self, value):
        """Clean and return a value from submitted form data.

        Args:
            value (unicode):
                A value submitted by the client.

        Returns:
            djblets.privacy.consent.base.ConsentData:
            The cleaned consent data value, or ``None`` if a suitable value was
            not provided.
        """
        value = super(ConsentRequirementField, self).clean(value)

        # Validators should have already caught this.
        assert value in (self.ALLOW, self.BLOCK)

        return self.consent_requirement.build_consent_data(
            source=self.consent_source,
            extra_data=self.extra_consent_data,
            granted=(value == self.ALLOW))

class MultiConsentRequirementsField(forms.MultiValueField):
    """A form field for displaying and gathering mulltiple consent information.

    This provides a :py:class:`ConsentRequirementField` for each consent
    requirement provided to the field (or all registered ones if an explicit
    list was not provided). It's handy for forms that offer all consent choices
    to the user.

    The cleaned result from this field is a list of
    :py:class:`~djblets.privacy.consent.base.ConsentData` instances, which
    can be recorded directly in the tracker.
    """

    default_error_messages = {
        'required': _('You must choose Allow or Block for all options to '
                      'continue.'),
    }

    widget = MultiConsentRequirementsWidget

    def __init__(self, consent_requirements=None, user=None,
                 consent_source=None, extra_consent_data=None,
                 *args, **kwargs):
        """Initialize the field.

        Args:
            consent_requirements (list of djblets.privacy.consent.base.
                                  ConsentRequirement, optional):
                The list of consent requirements to display. If not provided,
                all registered consent requirements will be used.

            user (django.contrib.auth.models.User, optional):
                The user viewing the form. If provided, the default options
                for each field will be based on the choices already made by
                the user.

            consent_source (unicode, optional):
                The source to record in the consent audit trail for anything
                saved in this field.

            extra_consent_data (dict, optional):
                Extra information to record in the consent audit trail for
                anything saved in this field.

            *args (tuple):
                Additional positional arguments to pass to the parent class.

            **kwargs (dict):
                Additional keyword arguments to pass to the parent class.
        """
        self.consent_requirements = (consent_requirements or
                                     list(get_consent_requirements_registry()))

        super(MultiConsentRequirementsField, self).__init__(
            fields=[
                ConsentRequirementField(consent_requirement,
                                        consent_source=consent_source,
                                        extra_consent_data=extra_consent_data)
                for consent_requirement in self.consent_requirements
            ],
            widget=self.widget(self.consent_requirements),
            *args, **kwargs)

        if user and user.is_authenticated:
            self.set_initial_from_user(user)

    def set_initial_from_user(self, user):
        """Set the initial state of the field based on a user's prior consent.

        This is called automatically if passing a user to the constructor.
        Otherwise, it should be called manually when setting up a form.

        Args:
            user (django.contrib.auth.models.User):
                The user viewing the form.
        """
        assert user
        assert user.is_authenticated

        self.initial = [
            field.consent_requirement.get_consent(user)
            for field in self.fields
        ]

    def prepare_value(self, value):
        """Prepare a value for use in the field.

        This will convert a list of
        :py:class:`~djblets.privacy.consent.base.Consent` values given in the
        order of the field's list of requirements to values suitable for use
        in the field.

        Args:
            value (list of list djblets.privacy.consent.base.Consent):
                The list of values to convert.

        Returns:
            list of unicode:
            A list of values suitable for use in the field.
        """
        return [
            field.prepare_value(value[i])
            for i, field in enumerate(self.fields)
        ]

    def clean(self, value):
        """Clean and return values from submitted form data.

        Args:
            value (list of unicode):
                A list of values submitted by the client.

        Returns:
            list of djblets.privacy.consent.base.ConsentData:
            The list of cleaned consent data values.
        """
        consent_data_list = \
            super(MultiConsentRequirementsField, self).clean(value)

        # Set the timestamp to the same value on each entry.
        now = timezone.now()

        for consent_data in consent_data_list:
            consent_data.timestamp = now

        return consent_data_list

    def compress(self, data_list):
        """Compress cleaned values for the field.

        This is required by the parent class, and is responsible for taking a
        list of cleaned values and returning something that can be validated
        and returned. This implementation returns the data as-is.

        Args:
            data_list (list of djblets.privacy.consent.base.ConsentData):
                The list of cleaned data.

        Returns:
            list of djblets.privacy.consent.base.ConsentData:
            The list of data.
        """
        return data_list

class ConsentFormMixin(object):
    """A mixin for forms that present registered consent requirements.

    This can be mixed into a form to provide consent field initialization and
    saving.
    """

    #: The name of the consent field.
    consent_field_name = 'consent'

    def __init__(self, *args, **kwargs):
        """Initialize the form.

        Args:
            *args (tuple):
                Positional arguments passed to the form.

            **kwargs (dict):
                Keyword arguments passed to the form.
        """
        super(ConsentFormMixin, self).__init__(*args, **kwargs)

        self.fields[self.consent_field_name] = \
            MultiConsentRequirementsField(
                label='',
                user=self.get_consent_user(),
                consent_source=self.get_consent_source(),
                extra_consent_data=self.get_extra_consent_data())

    def get_consent_user(self):
        """Return the user deciding on consent.

        This must be implemented by subclasses.

        Returns:
            django.contrib.auth.models.User:
            The user deciding on consent.
        """
        raise NotImplementedError

    def get_consent_source(self):
        """Return a source to record in the consent audit trail.

        This must be implemented by subclasses.

        Returns:
            unicode:
            The source to record for each consent entry.
        """
        raise NotImplementedError

    def get_extra_consent_data(self):
        """Return extra data to record in the consent audit trail.

        By default, this just returns an empty dictionary.

        Returns:
            dict:
            Extra data to record for each consent entry.
        """
        return {}

    def save_consent(self, user):
        """Save the consent information recorded in the form.

        Args:
            user (django.contrib.auth.models.User):
                The user who made the consent decisions.
        """
        assert self.is_valid()
        assert user
        assert user.is_authenticated

        get_consent_tracker().record_consent_data_list(
            user,
            self.cleaned_data[self.consent_field_name])

class ConsentConfigPageFormMixin(ConsentFormMixin):
    """A mixin for config forms that present registered consent requirements.

    This can be mixed into a config form to provide consent field
    initialization and saving. It would be used instead of
    :py:class:`ConsentFormMixin`.
    """

    form_id = 'privacy_consent'
    form_title = _('Privacy Consent')

    def save(self):
        """Save the form.

        This will save the consent information from the field.
        """
        self.save_consent(self.request.user)

        messages.add_message(
            self.request, messages.INFO,
            _('Your choices have been saved. You can make changes to these '
              'at any time.'))

    def get_consent_user(self):
        """Return the user deciding on consent.

        Returns:
            django.contrib.auth.models.User:
            The user deciding on consent.
        """
        return self.request.user

    def get_consent_source(self):
        """Return a source to record in the consent audit trail.

        By default, this returns the absolute URL for the page.

        Returns:
            unicode:
            The source to record for each consent entry.
        """
        return self.request.build_absolute_uri()


import json
from pathlib import Path
from PIL import Image
from typing import List, Tuple
import tensorflow as tf
import numpy as np
from math import ceil

class DatasetLoader:
    def __init__(self, base_path: Path, num_shards: int = 1, shard_id: int = 0):
        self.img_width = 960
        self.img_height = 720
        # self.img_width = 960 // 4
        # self.img_height = 720 // 4
        self.train_path = base_path / 'train'
        self.train_labels_path = base_path / 'train_labels'
        self.val_path = base_path / 'val'
        self.val_labels_path = base_path / 'val_labels'
        self.test_path = base_path / 'test'
        self.test_labels_path = base_path / 'test_labels'
        self.report_path = base_path / 'report'

        assert num_shards > 0
        assert shard_id >= 0
        assert shard_id < num_shards
        self.num_shards = num_shards
        self.shard_id = shard_id

        self.load_class_dict()

    def load_class_dict(self):
        with open(self.report_path / 'class_dict.json', 'r') as fp:
            self.class_dict = json.load(fp)

    def list_image_files(self, data_path: Path,
                         labels_path: Path) -> List[Tuple[Path, Path]]:
        image_files = []
        for data_file in data_path.glob('*.png'):
            stem = data_file.stem
            label_file = labels_path / f'{stem}_L.png'
            assert label_file.exists()
            image_files.append((data_file, label_file))

        n = len(image_files)
        shard_size = ceil(float(n) / float(self.num_shards))
        # NB: Make sure that every shard has the same number of items.
        # This is important for data parallel since it expects identical
        # numbers of steps (for oob_allreduce).
        start_idx = (self.shard_id * shard_size) % n
        end_idx = (start_idx + shard_size) % n
        if start_idx < end_idx:
            return image_files[start_idx:end_idx]
        else:
            return image_files[start_idx:] + image_files[:end_idx]

    def _load_image(self, file):
        img = Image.open(file)
        if self.img_width != img.width or self.img_height != img.height:
            img = img.resize((self.img_width, self.img_height),
                             resample=Image.NEAREST)
        img = np.array(img)
        return img

    def load_images(self, image_files):
        for image_file, label_file in image_files:
            img = self._load_image(image_file).astype(np.float32)
            img /= 255.0
            lbl = self._load_image(label_file)
            yield (img, lbl)

    def build_tf_dataset(self, data_path: Path, labels_path: Path) -> tf.data.Dataset:
        image_files = self.list_image_files(data_path, labels_path)

        def images(): return self.load_images(image_files)
        dataset = tf.data.Dataset.from_generator(
            images,
            output_signature=(
                tf.TensorSpec(
                    shape=(self.img_height, self.img_width, 3), dtype=tf.float32),
                tf.TensorSpec(
                    shape=(self.img_height, self.img_width), dtype=tf.uint8),
            )
        )
        return dataset

    @property
    def train(self):
        return self.build_tf_dataset(
            self.train_path,
            self.train_labels_path,
        )

    @property
    def val(self):
        return self.build_tf_dataset(
            self.val_path,
            self.val_labels_path,
        )

    @property
    def test(self):
        return self.build_tf_dataset(
            self.test_path,
            self.test_labels_path,
        )

    @property
    def num_classes(self) -> int:
        return len(self.class_dict)


import matplotlib.pyplot as plt

names = ['cotton', 'bajra', 'corn']
diana = [400, 500, 600]
sam = [400, 500, 600]
idx = [i for i, names in enumerate(names)]

plt.bar(idx, diana, color='cyan', hatch="/", label='diana')
plt.bar(idx, sam, bottom=diana,
        color='red', hatch='\\',
        label='sam')
plt.title('crops owned')
plt.ylabel('number of acres')
plt.xlabel('crops')

# set xticks
plt.xticks(idx, names)

# create 'draggable' legend with 2 cols, custom prob size
plt.legend(ncol=2, prop={'size': 14}).draggable()
plt.show()


from sqlalchemy import Column, Index, MetaData, Table
from sqlalchemy import Integer, String, DateTime, Boolean

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    bm_nodes = Table('bm_nodes', meta, autoload=True)

    image_path = Column('image_path', String(length=255))
    pxe_config_path = Column('pxe_config_path', String(length=255))
    deploy_key = Column('deploy_key', String(length=255))
    root_mb = Column('root_mb', Integer())
    swap_mb = Column('swap_mb', Integer())

    for c in [image_path, pxe_config_path, deploy_key, root_mb, swap_mb]:
        bm_nodes.create_column(c)

    deploy_key_idx = Index('deploy_key_idx', bm_nodes.c.deploy_key)
    deploy_key_idx.create(migrate_engine)

    bm_deployments = Table('bm_deployments', meta, autoload=True)
    bm_deployments.drop()

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    bm_nodes = Table('bm_nodes', meta, autoload=True)

    for c in ['image_path', 'pxe_config_path', 'deploy_key', 'root_mb',
              'swap_mb']:
        bm_nodes.drop_column(c)

    bm_deployments = Table('bm_deployments', meta,
        Column('created_at', DateTime),
        Column('updated_at', DateTime),
        Column('deleted_at', DateTime),
        Column('deleted', Boolean),
        Column('id', Integer, primary_key=True, nullable=False),
        Column('bm_node_id', Integer),
        Column('key', String(length=255)),
        Column('image_path', String(length=255)),
        Column('pxe_config_path', String(length=255)),
        Column('root_mb', Integer),
        Column('swap_mb', Integer),
        mysql_engine='InnoDB',
    )
    bm_deployments.create()


import os
import sys
from http.server import SimpleHTTPRequestHandler, HTTPServer

class MyHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        # Enable Cross-Origin Resource Sharing with *
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

    def do_GET(self):
        example_name = sys.argv[1] if len(sys.argv) > 1 else 'simpleform'
        if self.path == '/':
            self.path = '/' + example_name + '/index.html'
        elif self.path.startswith('/pkg/'):
            self.path = '/' + self.path
        else:
            self.path = '/' + example_name + self.path
        return SimpleHTTPRequestHandler.do_GET(self)

if __name__ == '__main__':
    httpd = HTTPServer(('localhost', 8000), MyHandler)
    print('Server is starting...')
    httpd.serve_forever()


from Bio import SeqIO
import sys
import re

seq=str(SeqIO.read(sys.argv[1],'genbank').seq)

out=open(sys.argv[2],'w')

contigs= re.sub("^N|N$","",re.sub('[N]+',"N",seq)).split("N")
k=1
for contig in contigs:
    out.write(">contig_"+str(k)+"\n"+contig+"\n")
    k=k+1

out.close()


import os
from geopy.geocoders import Nominatim

from twitter2 import create_account_users_json

def find_location_from_name(location_account):
    """
    str -> list
    :param location_account: an inputed account
    :return: a list of lists with follower screen_name, latitude and longitude
    """
    try:
        dir_name = os.getcwd()
        if location_account + "_data" + ".json" not in os.listdir(dir_name):
            create_account_users_json(location_account)

        location_account_json = create_account_users_json(location_account)

        geolocator = Nominatim(user_agent="specify_your_app_name_here", timeout=5)
        all_followers_location = []
        from geopy.extra.rate_limiter import RateLimiter
        geocode = RateLimiter(geolocator.geocode, min_delay_seconds=10, error_wait_seconds=15)
        for follower in location_account_json["users"]:
            try:
                location = geolocator.geocode(follower["location"])
                all_followers_location.append([follower["screen_name"],
                                               {"lat": location.latitude,
                                                "lng": location.longitude}])
            except:
                all_followers_location.append([follower["screen_name"], {"lat": 0, "lng": 0}])

        return all_followers_location

    except TypeError:
        print("Something went wrong. Try to input other account")


# -*- coding: utf-8 -*-

from imio.smartweb.core.contents.sections.views import SECTION_ITEMS_HASH_KEY
from imio.smartweb.core.testing import IMIO_SMARTWEB_CORE_FUNCTIONAL_TESTING
from imio.smartweb.core.testing import ImioSmartwebTestCase
from imio.smartweb.core.tests.utils import get_json
from plone import api
from plone.app.testing import setRoles
from plone.app.testing import TEST_USER_ID
from time import sleep
from z3c.relationfield import RelationValue
from zope.annotation.interfaces import IAnnotations
from zope.component import getUtility
from zope.component import queryMultiAdapter
from zope.intid.interfaces import IIntIds

import json
import requests_mock

class TestSectionNews(ImioSmartwebTestCase):
    layer = IMIO_SMARTWEB_CORE_FUNCTIONAL_TESTING

    def setUp(self):
        self.request = self.layer["request"]
        self.portal = self.layer["portal"]
        setRoles(self.portal, TEST_USER_ID, ["Manager"])
        self.portalpage = api.content.create(
            container=self.portal,
            type="imio.smartweb.PortalPage",
            id="Portal page",
        )
        self.json_news = get_json("resources/json_rest_news.json")
        self.json_specific_news = get_json("resources/json_rest_specific_news.json")
        self.rest_news_view = api.content.create(
            container=self.portal,
            type="imio.smartweb.NewsView",
            title="Rest news view",
        )
        self.news = api.content.create(
            container=self.portalpage,
            type="imio.smartweb.SectionNews",
            title="My news",
        )

    @requests_mock.Mocker()
    def test_news(self, m):
        intids = getUtility(IIntIds)
        self.news.related_news = "64f4cbee9a394a018a951f6d94452914"
        self.news.linking_rest_view = RelationValue(intids.getId(self.rest_news_view))
        self.news.link_text = "Voir toutes les actualités"
        view = queryMultiAdapter((self.portalpage, self.request), name="full_view")
        self.assertIn("My news", view())
        news_view = queryMultiAdapter((self.news, self.request), name="carousel_view")
        self.assertEqual(news_view.items, [])
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text=json.dumps(self.json_news))
        self.assertEqual(news_view.items[0][0].get("title"), "Première actualité")
        self.assertEqual(len(news_view.items[0]), 3)

        self.news.specific_related_newsitems = [
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "bfe2b4391a0f4a8db6d8b7fed63d1c4a",
        ]
        url = "http://localhost:8080/Plone/@search?UID=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&UID=bfe2b4391a0f4a8db6d8b7fed63d1c4a&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1"
        m.get(url, text=json.dumps(self.json_specific_news))
        self.assertEqual(len(news_view.items[0]), 2)
        self.assertEqual(
            news_view.items[0][0].get("title"), "Restauration de la piscine"
        )

        self.news.specific_related_newsitems = [
            "bfe2b4391a0f4a8db6d8b7fed63d1c4a",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        ]
        m.get(url, text=json.dumps(self.json_specific_news))
        self.assertEqual(
            news_view.items[0][0].get("title"), "Restauration de la Bibliothèque"
        )

    @requests_mock.Mocker()
    def test_news_modified(self, m):
        intids = getUtility(IIntIds)
        self.news.related_news = "64f4cbee9a394a018a951f6d94452914"
        self.news.linking_rest_view = RelationValue(intids.getId(self.rest_news_view))
        annotations = IAnnotations(self.news)
        self.assertIsNone(annotations.get(SECTION_ITEMS_HASH_KEY))

        news_view = queryMultiAdapter((self.news, self.request), name="carousel_view")
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text=json.dumps(self.json_news))
        self.assertEqual(len(news_view.items[0]), 3)
        hash_1 = annotations.get(SECTION_ITEMS_HASH_KEY)
        self.assertIsNotNone(hash_1)
        first_modification = self.portalpage.ModificationDate()

        sleep(1)
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text="{}")
        self.assertEqual(len(news_view.items), 0)
        next_modification = self.portalpage.ModificationDate()
        hash_2 = annotations.get(SECTION_ITEMS_HASH_KEY)
        self.assertNotEqual(hash_1, hash_2)
        self.assertNotEqual(first_modification, next_modification)

        sleep(1)
        self.assertEqual(len(news_view.items), 0)
        last_modification = self.portalpage.ModificationDate()
        hash_3 = annotations.get(SECTION_ITEMS_HASH_KEY)
        self.assertEqual(hash_2, hash_3)
        self.assertEqual(next_modification, last_modification)

    @requests_mock.Mocker()
    def test_orientation(self, m):
        intids = getUtility(IIntIds)
        self.news.related_news = "64f4cbee9a394a018a951f6d94452914"
        self.news.linking_rest_view = RelationValue(intids.getId(self.rest_news_view))
        annotations = IAnnotations(self.news)
        self.assertIsNone(annotations.get(SECTION_ITEMS_HASH_KEY))

        news_view = queryMultiAdapter((self.news, self.request), name="carousel_view")
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text=json.dumps(self.json_news))

        self.assertIn("paysage_vignette", news_view.items[0][0]["image"])
        self.news.orientation = "portrait"
        self.assertIn("portrait_vignette", news_view.items[0][0]["image"])


from utils.node_utils import list_to_link

def getIntersectionNode(headA, headB):
    n1 = n2 = 0
    node1 = headA
    node2 = headB
    while node1 or node2:
        if node1:
            node1 = node1.next
            n1 += 1
        if node2:
            node2 = node2.next
            n2 += 1

    diff = abs(n1 - n2)
    if n1 > n2:
        for i in range(diff):
            headA = headA.next
    else:
        for i in range(diff):
            headB = headB.next

    while headA is not headB:
        headA = headA.next
        headB = headB.next

    return headA

if __name__ == '__main__':
    l1 = list_to_link([4, 1])
    l2 = list_to_link([5, 6, 1])
    intersection = list_to_link([8, 4, 5])
    l1.next.next = intersection
    l2.next.next.next = intersection
    assert getIntersectionNode(l1, l2) is intersection


from django.urls import path
from .views import contacto, contratacion, galeria, home, quienessomos, vercontrataciones, form_del_solicitud, form_mod_solicitud

urlpatterns = [
    path('', home,name="home"),
    path('galeria/', galeria, name='galeria'),
    path('quienessomos/', quienessomos, name='quienessomos'),
    path('contacto/', contacto, name='contacto'),
    path('contratacion/', contratacion, name='contratacion'),
    path('vercontrataciones/', vercontrataciones, name='vercontrataciones'),
    path('form_mod_solicitud/<id>', form_mod_solicitud, name="form_mod_solicitud"),
    path('form_del_solicitud/<id>', form_del_solicitud, name="form_del_solicitud")
]


import os, datetime, time, sys, pickle
from random import randint
import re
import osascript
import requests
import random

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, ElementNotVisibleException, \
    UnexpectedAlertPresentException, WebDriverException
from pip._vendor.distlib.util import proceed
import constants
from commons import myprint

checkout_video_pattern = re.compile("check out.*")
watch_pattern = re.compile("watch.*|video entry bonus|comment.*youtube.*")

is_not_available_pattern = re.compile("sorry.*is not available.*")
has_ended_pattern = re.compile(".*competition.*has.*ended")

def get_time():
    return datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')

#Type4
def type4_click_continue(driver, element, patt=''):
    continue_buttons = element.find_elements_by_css_selector("div > div > form > div.form-actions.center > button")
    if len(continue_buttons) == 0:
        myprint("Continue button not found")
        return False
    click_button = continue_buttons[0]
    try:
        if len(continue_buttons)>=2:
            if continue_buttons[0].text == 'Continue':
                click_button = continue_buttons[0]
                click_button.get_attribute("class").split(' ').index('disabled')
            else:
                click_button = continue_buttons[1]
                click_button.get_attribute("class").split(' ').index('disabled')
        else:
            click_button = continue_buttons[0]
            click_button.get_attribute("class").split(' ').index('disabled')
        myprint("Still disabled")
        return False
    except:
        action = ActionChains(driver)
        action.move_to_element(click_button)
        action.click().perform()
        myprint(patt, 'type4_click_continue: continue clicked')
        return True

#Type5
def type5_click_continue(driver, element, patt = ''):
    continue_buttons = element.find_elements_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form > div > span:nth-child(1) > button")
    if len(continue_buttons) == 0:
        return False
    action = ActionChains(driver)
    action.move_to_element(continue_buttons[0])
    action.click().perform()
    myprint(constants.CGREEN + patt, 'type5_click_continue: continue clicked' + constants.CEND)
    return True

video_url_arr = []
with open(f'data/video_page_links.txt') as infile:
    for line in infile:
        video_url_arr.append(str(line))
random.shuffle(video_url_arr)

def load_cookie(driver, path):
    with open(path, 'rb') as cookies_file:
        cookies = pickle.load(cookies_file)
        for cookie in cookies:
            driver.add_cookie(cookie)

def is_logged_in(driver):
    prelogin_status = driver.find_elements_by_css_selector("body > div.body-widget > div > div > div.popup-blocks-container > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(3) > div > span > div:nth-child(2) > div")
    if len(prelogin_status)>0 and prelogin_status[0].text=="Login with:":
        return False

    loggedin_status = driver.find_elements_by_css_selector("body > div.body-widget > div > div > div.popup-blocks-container > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(3) > div > span > div.small-bar.contestant-logged-in.center.ng-scope > div.small-bar--text.ng-binding")
    if len(loggedin_status)>0 and loggedin_status[0].text.split('\n')[0]=="Entering as":
        return True
    return False

def login(driver):
    time.sleep(2)
    login_options = driver.find_elements_by_css_selector("div > div.popup-blocks-container > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form > fieldset.center > div > ul > li")
    for element in login_options:
        children  = element.find_elements_by_css_selector("*")
        for child in children:
            if('facebook-background' in child.get_attribute("class").split(' ')):
                try:
                    element.click()
                    time.sleep(2)
                    # myprint("login: 1st fb login succeeded")
                except Exception:
                    # myprint("1st fb login method failed, trying 2nd way")
                    try:
                        fbs = driver.find_elements_by_css_selector("body > div.body-widget > div > div > div.popup-blocks-container > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(3) > div > span > div:nth-child(2) > ul > li > a.facebook-background")
                        fbs[0].click()
                        time.sleep(2)
                        # myprint("login: 2nd fb login succeeded")
                    except Exception:
                        myprint("login: Exception:(suppressed)")
                        return False
                if is_logged_in(driver):
                    return True

    for element in login_options:
        children  = element.find_elements_by_css_selector("*")
        for child in children:
            if('twitter-background' in child.get_attribute("class").split(' ')):
                try:
                    element.click()
                    time.sleep(2)
                    # myprint("login: 1st twitter login succeeded")
                except Exception:
                    # myprint("1st twitter login method failed, trying 2nd way")
                    try:
                        twtr = driver.find_elements_by_css_selector("body > div.body-widget > div > div > div.popup-blocks-container > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(3) > div > span > div:nth-child(2) > ul > li:nth > a.twitter-background")
                        twtr[0].click()
                        time.sleep(2)
                        # myprint("login: 2nd twitter login succeeded")
                    except Exception:
                        myprint("login: Exception:")
                        return False
                if is_logged_in(driver):
                    return True

    myprint(constants.CRED + "login: FAILED:" + constants.CEND)
    return False

def is_youtube(element):
    potential_checks  = element.find_elements_by_css_selector("span i")
    for child in potential_checks:
        if('fa-youtube' in child.get_attribute("class").split(' ')):
            return True
    return False

def is_done(element):
    potential_checks  = element.find_elements_by_css_selector("span i")
    for child in potential_checks:
        if('fa-check' in child.get_attribute("class").split(' ')):
            return True
    return False

def fill_global_form(driver):
    global_forms = driver.find_elements_by_css_selector("body > div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form")

    if len(global_forms) > 0:
        try:
            name_boxes = global_forms[0].find_elements_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form > fieldset.inputs > div.form-horizontal > div > div > div:nth-child(1) > div > input")
            if len(name_boxes) > 0:
                name_boxes[0].clear()
                name_boxes[0].send_keys(constants.FULL_NAME)

            email_boxes = global_forms[0].find_elements_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form > fieldset.inputs > div.form-horizontal > div > div > div:nth-child(2) > div > input")
            if len(email_boxes)  > 0:
                email_boxes[0].clear()
                email_boxes[0].send_keys(constants.GOOG_ID + "@gmail.com")

            dob_boxes = global_forms[0].find_elements_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form > fieldset.inputs > div.form-horizontal > div > div > div:nth-child(3) > div > div > input")
            dob_formats = global_forms[0].find_elements_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div > form > fieldset.inputs > div.form-horizontal > div > div > div:nth-child(3) > div > div > div")
            if len(dob_boxes) > 0:
                dob_boxes[0].clear()
                if dob_formats[0].text.strip() == 'MM/DD/YYYY':
                    dob_boxes[0].send_keys(constants.DOB_MMDDYY)
                else:
                    dob_boxes[0].send_keys(constants.DOB)

            mandatory_checkboxes = global_forms[0].find_elements_by_css_selector("div > form > fieldset.inputs > div.form-horizontal > div > div > div:nth-child(3) > div > div > label > span.icon")
            if len(mandatory_checkboxes) > 0:
                mandatory_checkboxes[0].click()

            if type5_click_continue(driver, global_forms[0], "global_forms") == False:
                myprint("Form can not be saved")

            time.sleep(5)

            fb_account_selection = driver.find_elements_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(2) > div > ul > li:nth-child(1) > a.facebook-border")
            if len(fb_account_selection) == 0:
                fb_account_selection = driver.find_elements_by_css_selector("div.body-widget > div > div > div.popup-blocks-container > div > div:nth-child(1) > div > div > ul > li > a.facebook-border")

            if len(fb_account_selection) > 0:
                fb_account_selection[0].click()
                time.sleep(5)
            else:
                myprint("FB account not found")
        except Exception:
            pass

def is_not_abailable(driver):
    try:
        is_not_available =  driver.find_element_by_css_selector("div.body-widget > div > div > div.popup-blocks-container > div > div:nth-child(1) > div:nth-child(6) > div.center.massive-message.light-grey-bg.ng-scope > h2")
        if is_not_available_pattern.match(is_not_available.text.lower().strip()) != None:
            return True
    except Exception:
        pass
    return False

def has_ended(driver):
    try:
        has_ended =  driver.find_element_by_css_selector("div.body-widget > div > div > div > div > div:nth-child(1) > div:nth-child(6) > div:nth-child(2) > div:nth-child(1) > div > h2")
        if has_ended_pattern.match(has_ended.text.lower().strip()) != None:
            return True
    except Exception:
        pass
    return False

def watch(driver, element):
    element.click()
    time.sleep(2)

    sharelinks = element.find_elements_by_css_selector("div.cover-video-container > iframe")
    if len(sharelinks) == 0:
        sharelinks = element.find_elements_by_css_selector("divdiv > div > form > div.form-compact__content > div.form-compact__part.user-fragment.center.ng-binding.ng-scope > p > a")
    sharelinks[0].click()# play it
    osascript.osascript("set volume output volume 0")
    time.sleep(constants.RETRY_VIDEO_CONTINUE_WAIT)
    osascript.osascript("set volume output volume 20")

    #In case video has comments box
    input_boxes = element.find_elements_by_css_selector("div > div > form > div.form-compact__content > div:nth-child(2) > div > div > div > input")
    if len(input_boxes) == 0:
        input_boxes = element.find_elements_by_css_selector("div > div > form > div.form-compact__content > div:nth-child(2) > div > div > textarea")
    if len(input_boxes) > 0:
        input_boxes[0].clear()
        input_boxes[0].send_keys(constants.GOOG_ID + " . I'm loving it")
        time.sleep(2)

    has_clicked = False
    while has_clicked == False:
        has_clicked = type4_click_continue(driver, element,'watch_pattern')
        time.sleep(constants.RETRY_VIDEO_CONTINUE_WAIT)

    element.click()

def loop_video_elements_only(driver):
    elements = driver.find_elements_by_css_selector("div.entry-method")
    cnt = 0
    for ctr, element in enumerate(elements):
        action = ActionChains(driver)
        action.move_to_element(element).perform()
        children  = element.find_elements_by_css_selector("a > span.text")
        txt = children[0].text.lower().strip()
        if is_done(element) == False:
            try:
                if (watch_pattern.match(txt) != None or checkout_video_pattern.match(txt) != None) and is_youtube(element):
                    watch(driver, element)
            except Exception as e:
                myprint('Must be due to inner form case somwhere', e)
            try:
                driver.execute_script("document.getElementsByClassName('expandable')[" + str(ctr) + "].style.visibility='hidden';")
            except Exception as e:
                myprint('Seems there was no expandable here', e)
        if is_done(element) == True:
            cnt = cnt + 1
    if cnt == len(elements):
        return True
    return False

def open_url(driver, d, url, cnt):
    if 'sleep' in d:
        time.sleep(random.randint(10, constants.ANTIFRAUD_FUZZY_SLEEP_LIMIT))
    else:
        time.sleep(2)
    driver.get(url)
    myprint(driver.current_url)
    if is_not_abailable(driver):
        myprint("Is NOT AVAILABLE in your region")
        return
    if has_ended(driver):
        myprint("This Competition has ended")
        return
    if login(driver) == False:
        fill_global_form(driver)
    if loop_video_elements_only(driver) == True:
        myprint("DONE:", url)
        with open("data/video_page_links_done.txt", "a") as myfile:
            myfile.write(url + '\n')

def crawl(d):
    if 'sleep' in d:
        time.sleep(random.randint(100, constants.ANTIFRAUD_FUZZY_SLEEP_LIMIT*10))
    else:
        time.sleep(2)
    cnt = 0
    driver = webdriver.Chrome(constants.CHROME_DRIVER_PATH)
    driver.get("https://google.com")

    load_cookie(driver, '/tmp/gleam_fb_cookie')
    load_cookie(driver, '/tmp/gleam_google_cookie')
    load_cookie(driver, '/tmp/gleam_twitter_cookie')
    load_cookie(driver, '/tmp/gleam_instagram_cookie')
    load_cookie(driver, '/tmp/gleam_soundcloud_cookie')
    load_cookie(driver, '/tmp/gleam_steampowered_cookie')

    for href in video_url_arr:
        try:
            myprint("==", href.replace('\n',''), "==")
            try:
                open_url(driver, d, href, cnt)
            except Exception as e:
                myprint(constants.CRED + "do:" + constants.CEND, e)
                pass
        except Exception:
            pass

    driver.quit()

if __name__ == "__main__":
    argv = sys.argv[1:]
    d = {}
    for i in range(0, len(argv), 2):
        d[argv[i].replace('-', '')] = argv[i + 1]
    myprint(d)
    crawl(d)
    myprint(constants.CGREEN + 'Main PEACEFULLY terminated' + constants.CEND)


from django.shortcuts import render, get_object_or_404
from rest_framework import views
from rest_framework.response import Response
from datetime import date, timedelta, datetime
from news.serializers import *
from events.serializers import *
from .serializers import *

class AllTrends(views.APIView):
    def get(self, request):
        serializerTrends = TrendSerializer(Trend.objects.all(), many=True)
        return Response(serializerTrends.data)

class TrendDetail(views.APIView):
    def get(self, request, pk):
        id = int(pk)
        trend = get_object_or_404(Trend, id=id)
        serializerTrend = TrendDetailSerializer(trend).data
        serializerTrend["directions"] = DirectionSerializer(Direction.objects.filter(id_fk=trend), many=True).data
        serializerTrend["documents"] = TrendsDocumentsSerializer(TrendsDocuments.objects.filter(id_fk=trend), many=True).data
        return Response(serializerTrend)

class TrendDetailNews(views.APIView):
    def get(self, request, pk, page):
        id = int(pk)
        offset = int(page)
        trend = get_object_or_404(Trend, id=id)
        news = News.objects.filter(directions__id_fk = trend).distinct()[offset:offset+6]
        serializerDirectionNews = NewsPartBlockSerializer(news, many=True)
        dataDirectionNews = serializerDirectionNews.data
        from image_cropping.utils import get_backend
        for news in dataDirectionNews:
            ID = news.get("id")
            obj = News.objects.get(id=ID)
            image = get_backend().get_thumbnail_url(
                obj.imageOld,
                {
                    'size': (300, 300),
                    'box': obj.image,
                    'crop': True,
                    'detail': True,
                }
            )
            news['image'] = image
        return Response(dataDirectionNews)

class TrendDetailEvents(views.APIView):
    def get(self, request, pk, page):
        id = int(pk)
        offset = int(page)
        trend = get_object_or_404(Trend, id=id)
        events = Event.objects.filter(directions__id_fk = trend).distinct()[offset:offset+6]
        serializerDirectionEvents = EventBlockSerializer(events, many=True)
        dataDirectionEvents = serializerDirectionEvents.data
        from image_cropping.utils import get_backend
        for event in dataDirectionEvents:
            ID = event.get("id")
            obj = Event.objects.get(id=ID)
            image = get_backend().get_thumbnail_url(
                obj.imageOld,
                {
                    'size': (390, 280),
                    'box': obj.image,
                    'crop': True,
                    'detail': True,
                }
            )
            event['image'] = image
        return Response(dataDirectionEvents)


__author__ = 'tanmch791115'
from itertools import combinations,permutations
def main(digits='123456789',total=100):
    result=set()
    length=len(digits)
    for k in range(1,length):
        for item in combinations(range(1,length),k):
            tempDigits=digits
            operands=[]
            for i in item[::-1]:
                operands.append(tempDigits[i:])
                tempDigits=tempDigits[:i]
            operands.append(tempDigits)
            operands.reverse()
            for operator in permutations('+-'*k,k):
                exp=''.join((d+o for d,o in zip(operands,operator))) +operands[-1]
                if exp not in result and eval(exp)==total:
                    print (exp,'=',total)
                    result.add(exp)

if __name__=="__main__":
    main()


"""Python wrapper for getting weather data from AccueWeather API."""

from __future__ import annotations

import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Any

import orjson
from aiohttp import ClientSession

from .const import (
    ATTR_CURRENT_CONDITIONS,
    ATTR_FORECAST_DAILY,
    ATTR_FORECAST_HOURLY,
    ATTR_GEOPOSITION,
    HTTP_HEADERS,
    LANGUAGE_MAP,
    REMOVE_FROM_CURRENT_CONDITION,
    REMOVE_FROM_FORECAST,
    REQUESTS_EXCEEDED,
)
from .exceptions import (
    ApiError,
    InvalidApiKeyError,
    InvalidCoordinatesError,
    RequestsExceededError,
)
from .utils import (
    construct_url,
    parse_current_condition,
    parse_daily_forecast,
    parse_hourly_forecast,
    valid_api_key,
    valid_coordinates,
)

_LOGGER = logging.getLogger(__name__)

class AccuWeather:
    """Main class to perform AccuWeather API requests."""

    def __init__(  # noqa: PLR0913
        self,
        api_key: str,
        session: ClientSession,
        latitude: float | None = None,
        longitude: float | None = None,
        location_key: str | None = None,
        language: str = "en",
    ) -> None:
        """Initialize."""
        if not valid_api_key(api_key):
            raise InvalidApiKeyError(
                "Your API Key must be a 32-character hexadecimal string"
            )
        if not location_key and not valid_coordinates(latitude, longitude):
            raise InvalidCoordinatesError("Your coordinates are invalid")

        self.latitude = latitude
        self.longitude = longitude
        self.language = LANGUAGE_MAP.get(language, "en-us")
        self._api_key = api_key
        self._session = session
        self._location_key = location_key
        self._location_name: str | None = None
        self._requests_remaining: int | None = None

    async def _async_get_data(self, url: str) -> Any:
        """Retrieve data from AccuWeather API."""
        async with self._session.get(url, headers=HTTP_HEADERS) as resp:
            if resp.status == HTTPStatus.UNAUTHORIZED.value:
                raise InvalidApiKeyError("Invalid API key")

            if resp.status != HTTPStatus.OK.value:
                error_text = orjson.loads(await resp.text())
                if error_text["Message"] == REQUESTS_EXCEEDED:
                    raise RequestsExceededError(
                        "The allowed number of requests has been exceeded"
                    )
                raise ApiError(f"Invalid response from AccuWeather API: {resp.status}")

            _LOGGER.debug("Data retrieved from %s, status: %s", url, resp.status)
            data = await resp.json()

        if resp.headers["RateLimit-Remaining"].isdigit():
            self._requests_remaining = int(resp.headers["RateLimit-Remaining"])

        if "hourly" in url:
            return data

        return data if isinstance(data, dict) else data[0]

    async def async_get_location(self) -> None:
        """Retrieve location data from AccuWeather."""
        url = construct_url(
            ATTR_GEOPOSITION,
            api_key=self._api_key,
            lat=str(self.latitude),
            lon=str(self.longitude),
            language=self.language,
        )
        data = await self._async_get_data(url)
        self._location_key = data["Key"]
        self._location_name = data["LocalizedName"]

    async def async_get_current_conditions(self) -> dict[str, Any]:
        """Retrieve current conditions data from AccuWeather."""
        if not self._location_key:
            await self.async_get_location()

        if TYPE_CHECKING:
            assert self._location_key is not None

        url = construct_url(
            ATTR_CURRENT_CONDITIONS,
            api_key=self._api_key,
            location_key=self._location_key,
            language=self.language,
        )
        data = await self._async_get_data(url)
        return parse_current_condition(data, REMOVE_FROM_CURRENT_CONDITION)

    async def async_get_daily_forecast(
        self, days: int = 5, metric: bool = True
    ) -> list[dict[str, Any]]:
        """Retrieve daily forecast data from AccuWeather."""
        if not self._location_key:
            await self.async_get_location()

        if TYPE_CHECKING:
            assert self._location_key is not None

        url = construct_url(
            ATTR_FORECAST_DAILY,
            api_key=self._api_key,
            location_key=self._location_key,
            days=str(days),
            metric=str(metric).lower(),
            language=self.language,
        )
        data = await self._async_get_data(url)
        return parse_daily_forecast(data, REMOVE_FROM_FORECAST)

    async def async_get_hourly_forecast(
        self, hours: int = 12, metric: bool = True
    ) -> list[dict[str, Any]]:
        """Retrieve hourly forecast data from AccuWeather."""
        if not self._location_key:
            await self.async_get_location()

        if TYPE_CHECKING:
            assert self._location_key is not None

        url = construct_url(
            ATTR_FORECAST_HOURLY,
            api_key=self._api_key,
            location_key=self._location_key,
            hours=str(hours),
            metric=str(metric).lower(),
            language=self.language,
        )
        data = await self._async_get_data(url)
        return parse_hourly_forecast(data, REMOVE_FROM_FORECAST)

    @property
    def location_name(self) -> str | None:
        """Return location name."""
        return self._location_name

    @property
    def location_key(self) -> str | None:
        """Return location key."""
        return self._location_key

    @property
    def requests_remaining(self) -> int | None:
        """Return number of remaining allowed requests."""
        return self._requests_remaining


"""
    Main driver program for the CoppeliaSim Demo. Creates a process for each Sim subroutine and then
    threads within the process
"""
from linkStart import *
import multiprocessing as mproc

NUM_ROBOTS = 6  # Defines how many threads we create based on the number of robots in the scene

def main():
    processes = []  # Stores the simulation processes

    # Set up 1 wanderer
    if NUM_ROBOTS == 1:
        robotName = "/dr20"  # for only 1 robot
    else:
        robotName = "/dr20[0]"
    routine = subroutine(0, robotName, "wanderer")
    simProc = mproc.Process(target=routine.driver())
    processes.append(simProc)

    for i in range(1, NUM_ROBOTS):
        """Setting up the connection threads for each robot in excess of 1"""
        robotName = "/dr20[" + str(i) + "]"

        routine = subroutine(i, robotName, "wanderer")
        simProc = mproc.Process(target=routine.driver())
        processes.append(simProc)
        print(f"Main: starting subroutine {i}")
        simProc.start()
        sleep(.1)

if __name__ == "__main__":
    main()


from rest_framework.views import APIView
from rest_framework.response import Response
import requests

githubUrl = "https://api.github.com/search/repositories?q="

class GithubApiView(APIView):

    def get(self, request):
        try:
            min_stars = request.GET.get('min_stars', '')
            max_stars = request.GET.get('max_stars', '')
            programing_languages = request.GET.get('programing_languages', '')
            lastUpdateRepository = request.GET.get('lastUpdateRepository', '')
            searchResults = self.handle_search(
                githubUrl, min_stars, max_stars, programing_languages, lastUpdateRepository)

            if(searchResults and 'items' in searchResults):
                returnedData = []
                searchResults = searchResults['items'][0:10]
                for searchItem in searchResults:
                    name = searchItem['full_name']
                    description = searchItem['description']
                    created_at = searchItem['created_at']
                    open_issues = searchItem['open_issues']
                    language = searchItem['language']
                    url = searchItem['url']
                    prSize = requests.get(url+'/pulls')
                    prSize = prSize.json()
                    prSize = len(prSize)
                    output = {"name": name, "description": description, "created_at": created_at,
                              "open_issues": open_issues, "language": language, "prSize": prSize}
                    returnedData.append(output)

                return Response(returnedData)
            else:
                return Response({})
        except Exception as e:
            explanation = e.explanation
            return Response(explanation)

    def handle_search(self, url, min_stars, max_stars, programing_languages, lastUpdateRepository):
        searchQuery = ''
        if(min_stars and not max_stars):
            searchQuery += 'stars:>='+min_stars

        if(min_stars and max_stars):
            searchQuery = 'stars:'+min_stars+'..'+max_stars

        if(lastUpdateRepository):
            searchQuery += '+created:'+lastUpdateRepository

        if(programing_languages):
            programingLanguagesList = programing_languages.replace(
                ' ', '').split(',')

            if(len(programingLanguagesList) > 1):
                for programing_language in programingLanguagesList:
                    searchQuery += '+language:'+programing_language
            else:
                searchQuery += '+language:'+programingLanguagesList[0]

        finalUrl = url+searchQuery+'&sort=stars&order=desc'
        print(finalUrl)
        data = requests.get(finalUrl)
        return data.json()


__all__ = ['DBpediaResource', 'NTripleParser',
           "DEFAULT_LANGUAGE", "DEFAULT_VERSION",
           "datasets"]

from resource import DBpediaResource
from ntparser import NTripleParser

import urls, download, resource, ntparser, datasets

from datasets import DEFAULT_LANGUAGE, DEFAULT_VERSION

if __name__ == "__main__":
    import sys
    import logging

    logging.basicConfig(level=logging.INFO)
    log = logging.getLogger('dbpedia')

    # empty the cache before we begin
    download.clean_all()

    to_test = [urls, download, resource, ntparser, datasets]

    for module in to_test:
        try:
            log.info("Testing %s" % str(module))
            module._test()

            log.info("Tests Passed")
        except AssertionError as e:
            log.error("ERROR: TESTS FAILED IN %s", str(module))
            log.error(e)


# =========================================================================== #
#                                GRIDSEARCH                                   #
# =========================================================================== #
"""Plots results of sklearn gridsearches"""
# --------------------------------------------------------------------------- #
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
import pandas as pd
import seaborn as sns

from .basic_plots import BasicPlots
from ..utils.filemanager import save_fig
# --------------------------------------------------------------------------- #
def _format_string(s):
    if "__" in s:
        s = s.split("__")[1]
    return s.replace("_", " ").capitalize()

class VisualCV:

    def _plot(self, pipelines, x, y, z=None, kind='line',
              title='GridSearchCV Scores', height=1, width=1,
              log=False, directory=None, filename=None, show=True):

        # Obtain class containing standard plotting functions
        plot = BasicPlots()

        # Extract results from pipeline and concatenate
        results = []
        for _, v in pipelines.items():
            result = pd.DataFrame.from_dict(v.cv_results_)
            results.append(result)
        results = pd.concat(results, axis=0)

        # Remove unwanted prefixes from results column names
        results.columns = results.columns.str.split('__').str[-1]
        try:
            x_param = results.filter(like=x).columns[0]
            if z is not None:
                z_param = results.filter(like=z).columns[0]
                # Convert z_param to categorical since it is used in seaborn
                # line plot hue parameter
                results[z_param] = pd.Categorical(results[z_param])
            else:
                z_param = None
        except:
            print("Invalid parameter name")

        # Obtain and initialize matplotlib figure
        fig_width = math.floor(12*width)
        fig_height = math.floor(4*height)
        fig, ax = plt.subplots(figsize=(fig_width, fig_height))

        # Set Title
        title_plot = title + '\n' + 'By ' + _format_string(x_param)

        # Render Plot
        if kind == 'line':
            ax = plot.lineplot(x=x_param, y=y, z=z_param, data=results, ax=ax, title=title_plot)
        else:
            ax = plot.barplot(x=x_param, y=y, z=z_param, data=results, ax=ax, title=title_plot)

        # Change to log scale if requested
        if log: ax.set_xscale('log')

        # Finalize, show and save
        fig.tight_layout()
        if show:
            plt.show()
        if directory is not None:
            if filename is None:
                filename = title + '.png'
            save_fig(fig, directory, filename)
        plt.close(fig)

    def scores(self, pipelines, x, y='train', z=None, kind='line', height=1, width=1,
               log=False, directory=None, filename=None, show=True):
        """Plots training scores for one or more GridSearchCV Objects"""
        y = 'mean_train_score' if y == 'train' else "mean_test_score"
        title = 'GridSearchCV Training Scores' if y == 'train' else 'GridSearchCV Validation Scores'
        self._plot(pipelines, x, y, z, kind, title,
                        height, width, log, directory, filename, show)

    def times(self, pipelines, x, y=None, z=None, kind='line', height=1, width=1,
                log=False, directory=None, filename=None, show=True):
        """Plots fit times for one or more GridSearchCV Objects"""
        y = 'mean_fit_time'
        title = 'GridSearchCV Fit Times'
        self._plot(pipelines, x, y, z, kind, title,
                        height, width, log, directory, filename, show)

class Selection():

    def validation_curves(self, models, log=False, directory=None, filename=None,
                       xlim=None, ylim=None, subtitle=None, show=True):
        """Plots validation scores for multiple models."""

        # Extract data
        results = []
        for name, model in models.items():
            d = {'Epoch': np.arange(1,model.epochs+1),
                 'Model': name,
                 'Validation Score': model.val_scores}
            result = pd.DataFrame(data=d)
            results.append(result)
        results = pd.concat(results, axis=0)

        # Format title
        title = "Validation Scores"
        if subtitle is not None:
            title = title + "\n" + subtitle

        # Render Plot
        fig, ax = plt.subplots(figsize=(12,4))
        plot = BasicPlots()
        ax = plot.lineplot(x='Epoch', y='Validation Score', z='Model', data=results, title=title, ax=ax)
        # Set x and y limits
        if xlim is not None:
            ax.set_xlim(left = xlim[0], right=xlim[1])
        if ylim is not None:
            ax.set_xlim(bottom=ylim[0], top=ylim[1])
        # Change to log scale if requested
        if log: ax.set_xscale('log')
        # Finalize, show and save
        fig.tight_layout()
        if show:
            plt.show()
        if directory is not None:
            if filename is None:
                filename = title + '.png'
            save_fig(fig, directory, filename)
        plt.close(fig)

    def learning_curves(self, models, z="name", log=False, directory=None, filename=None,
                       xlim=None, ylim=None,show=True):
        """For fixed learning rates, plots learning curves for multiple models."""

        # Extract data
        results = []
        for _, v in models.items():
            params = v.get_params()
            result = pd.DataFrame({z: params[z], "Epoch": np.arange(1,v.epochs+1),
                                   "Cost": v.train_costs})
            results.append(result)
        results = pd.concat(results, axis=0)

        # Render Plot
        fig, ax = plt.subplots(figsize=(12,4))
        plot = BasicPlots()
        title = "Learning Curve(s)"
        ax = plot.lineplot(x='Epoch', y='Cost', z=z, data=results, title=title, ax=ax)
        # Set x and y limits
        if xlim is not None:
            ax.set_xlim(left = xlim[0], right=xlim[1])
        if ylim is not None:
            ax.set_ylim(bottom=ylim[0], top=ylim[1])
        # Change to log scale if requested
        if log: ax.set_xscale('log')
        # Finalize, show and save
        fig.tight_layout()
        if show:
            plt.show()
        if directory is not None:
            if filename is None:
                filename = title + '.png'
            save_fig(fig, directory, filename)
        plt.close(fig)


from typing import Dict, List

def get_template() -> Dict:
    return {
        "properties": {
            "Year": {"number": 2021},
            "Overview": {"rich_text": [{"text": {"content": ""}}]},
            "Actors": {"multi_select": []},
            "Genres": {"multi_select": []},
            "Rating": {"number": 0},
            "Language": {"select": {"name": "en"}},
        },
        "cover": {"type": "external", "external": {"url": ""}},
    }

def patch_year(template: Dict = {}, year: int = 0000):
    template["properties"]["Year"]["number"] = year
    return template

def patch_overview(template: Dict = {}, overview: str = "N/A"):
    if not overview:
        overview = "N/A"
    template["properties"]["Overview"]["rich_text"] = [{"text": {"content": overview}}]
    return template

def patch_actors(template: Dict = {}, cast_list: List[Dict] = []):
    if cast_list == []:
        template["properties"]["Actors"]["multi_select"].append({"name": "N/A"})
        return template
    for actor in cast_list:
        template["properties"]["Actors"]["multi_select"].append({"name": actor["name"]})
    return template

def patch_genres(template: Dict = {}, genres_list: List[Dict] = []):
    if genres_list == []:
        template["properties"]["Genres"]["multi_select"].append({"name": "N/A"})
        return template
    for genre in genres_list:
        template["properties"]["Genres"]["multi_select"].append({"name": genre["name"]})
    return template

def patch_cover(template: Dict = {}, filepath: str = ""):
    if filepath is None:
        filepath = ""
    template["cover"]["external"]["url"] = "https://image.tmdb.org/t/p/w500" + filepath
    return template

def patch_rating(template: Dict = {}, rating: int = -1):
    template["properties"]["Rating"]["number"] = rating
    return template

def patch_language(template: Dict = {}, language: str = "en"):
    if not language:
        language = "N/A"
    template["properties"]["Language"]["select"]["name"] = language
    return template

def patch_all(template: Dict = {}, **kwargs):
    template = patch_year(template, kwargs.get("year", 0000))
    template = patch_overview(template, kwargs.get("overview", "N/A"))
    template = patch_actors(template, kwargs.get("cast_list", []))
    template = patch_genres(template, kwargs.get("genres", []))
    template = patch_cover(template, kwargs.get("cover", ""))
    template = patch_rating(template, kwargs.get("rating", -1))
    template = patch_language(template, kwargs.get("language", "N/A"))
    return template


#
#  Date  : 2022-05-30
#  URL   : https://programmers.co.kr/learn/courses/30/lessons/92342
#
#  풀이에 걸린 시간 : 1시간

from itertools import combinations_with_replacement
def solution(n, info):
    answer = [0]*11

    # 0~11 중복조합
    comb = list(combinations_with_replacement([i for i in range(0,11)],n))

    max_score_diff = 0
    rion = []
    info = info[::-1]

    for c in comb:
        score_rion = 0
        score_apeach = 0
        # 점수별로 맞춘 횟수 세기
        for i in range(1,11):
            cnt = c.count(i)
            # 맞춘 개수가 어피치보다 많을 경우
            if cnt > info[i]:
                score_rion += i
            # 해당 점수를 어파치가 더 많이 맞췄거나, 동등하게 맞췄을 경우
            if cnt <= info[i] and info[i] != 0 :
                score_apeach += i

        # 점수 차이가 최대값일 경우, 기록
        if score_rion - score_apeach > max_score_diff:
            max_score_diff = score_rion - score_apeach
            rion = c

    for i in rion:
        answer[10-i] += 1

    if max_score_diff == 0:
        answer = [-1]

    return answer

# BFS 를 사용하여 풀면, 수행시간을 단축 시킬 수 있다.


from dataclasses import dataclass
from math import ceil
import random
from typing import Optional
from rsa_logic.errors import KeyGenError
from utils.primes import PrimeGenerator

DEFAULT_EXPONENT = 65537

@dataclass
class PrivateKey:
    """
    Private key class
    """
    d: int
    p: int
    q: int
    n: int
    e: int

    @property
    def exp1(self) -> int:
        return int(self.d % (self.p-1))

    @property
    def exp2(self) -> int:
        return int(self.d % (self.q-1))

    @property
    def coef(self) -> int:
        return KeyGenerator.inverse(self.q, self.p)

    @property
    def n_octet_length(self)->int:
        """ reuturns the key length in bytes """
        assert ceil(self.n.bit_length()/8)==int(self.n.bit_length()/8)==self.n.bit_length()//8
        return self.n.bit_length()//8

@dataclass
class PublicKey:
    """
    Public key class
    """
    n: int      # n = p*q RSA Modulus
    e :int      # e = public exponent

    @property
    def n_octet_length(self) -> int:
        """ return the length in octets of the RSA modulus n """
        return self.n.bit_length() // 8

class KeyGenerator:
    def __init__(self):
        self.private_key = None
        self.prime_generator = PrimeGenerator()

    def euclid(self, a: int, b: int) -> int:
        """
        Calculates the greatest common divisor of a and b.
        """
        while b != 0:
            a, b = b, a % b
        return a

    def gen_keypair(self, q: int, p:int, exponent: Optional[int] = DEFAULT_EXPONENT) -> tuple:
        """Generate RSA keys of nbits bits. Returns (privateKey, publicKey)."""

        # Regenerate p and q values, until calculate_keys doesn't raise a
        # ValueError.

        n = p * q
        phi = (p - 1) * (q - 1)

        if exponent != None:
            assert self.euclid(phi,exponent) == 1
        else:
            while True:
                exponent = random.randrange(1,phi)
                if self.euclid(phi, exponent) == 1:
                    break
        d = self.inverse(exponent, phi)
        assert exponent*d % phi == 1
        return PrivateKey(d=d,p=p,q=q,n=n,e=exponent), PublicKey(n, e=exponent)

    @staticmethod
    def extend_euclid(a: int, b: int) -> tuple[int, int, int]:
        """
        Calculates the extended Euclid algorithm for two integers a and b.
        """

        if b == 0:
            return 1,0,a

        x, y, q = KeyGenerator.extend_euclid(b, a % b)

        return y, x - (a // b) * y, q

    @staticmethod
    def inverse(a: int, b: int) -> int:
        '''Calculate the Modular Inverse'''
        # d * e = 1 (mod phi) <=> d * e + k * phi = 1
        x, y, q = KeyGenerator.extend_euclid(a, b)
        if q != 1:
            raise KeyGenError("not relative prime")
        else:
            return x % b

    def new_keys(self, n_bits: int, exponent: Optional[int] = DEFAULT_EXPONENT, n_processes: int = 8) -> tuple:
        """Generate a new pair of RSA keys of nbits bits. Returns (privateKey, publicKey)."""
        if n_processes < 1:
            raise KeyGenError("n_processes must be at least 1")
        p,q = self.prime_generator.primes(n_bits//2, n_processes=n_processes)
        return self.gen_keypair(p, q, exponent)

if __name__ == "__main__":

    rsa = KeyGenerator()
    nbits = 2048
    pub_key, prv_key = rsa.new_keys(n_bits=nbits, exponent=DEFAULT_EXPONENT, n_processes=8)

    print(pub_key.n_octet_length)


import sys
sys.path.append('C:/Users/Pipo/python-grpc/audio')

import grpc
from concurrent import futures
import audio_pb2
import audio_pb2_grpc
from pydub import AudioSegment

class AudioStreamerServicer(audio_pb2_grpc.AudioServiceServicer):
    def __init__(self):
        self.audio_chunks = []  # Almacena los chunks de audio

    def StreamAudio(self, request_iterator, context):
        for chunk in self.audio_chunks:
            yield audio_pb2.AudioChunk(data=chunk)

def serve():
    servicer = AudioStreamerServicer()  # Crea una instancia de AudioStreamerServicer
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    audio_pb2_grpc.add_AudioServiceServicer_to_server(servicer, server)
    server.add_insecure_port("[::]:50051")
    server.start()
    print("Servidor gRPC en ejecución en el puerto 50051")

    # Leer el archivo MP3 y dividirlo en chunks
    audio = AudioSegment.from_mp3("C:/Users/Pipo/python-grpc/audio/meme.mp3")
    chunk_size_ms = 1000  # Tamaño de cada chunk en milisegundos
    for i in range(0, len(audio), chunk_size_ms):
        chunk = audio[i:i+chunk_size_ms]
        chunk_bytes = chunk.raw_data
        servicer.audio_chunks.append(chunk_bytes)  # Utiliza la instancia de servicer

    server.wait_for_termination()

if __name__ == "__main__":
    serve()


from collections import defaultdict

def search(start, node, count, nodes):
    global sum_, visited
    if node in visited:
        return
    visited.add(node)
    if node > start and node % start == 0:
        sum_ += count
    for neighbor in nodes[node]:
        search(start, neighbor, count + 1, nodes)

while True:

    try:
        nodes = defaultdict(list)
        n = int(input())
        for _ in range(1, n):
            from_, to_ = map(int, input().strip().split(' '))
            nodes[from_].append(to_)
            nodes[to_].append(from_)

        sum_ = 0
        for i in range(1, n):
            visited = set()
            search(i, i, 1, nodes)

        print(sum_)

    except EOFError:
        break


"""
Sbr+: Doppler Setup
-------------------
This example shows how you can use PyAEDT to create a Multipart Scenario in SBR+ and setup a doppler Analysis.
"""

###############################################################################
# Launch AEDT in Graphical Mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This examples launches AEDT 2022R1 in graphical mode.
import os
import tempfile
import pyaedt
from pyaedt import examples, generate_unique_name

# Start Electronics Desktop
aedt_version = "2022.1"
projectname = "MicroDoppler_with_ADP"
designname = "doppler"
library_path = examples.download_multiparts()

##########################################################
# Set Non Graphical Mode.
# Default is False

non_graphical = os.getenv("PYAEDT_NON_GRAPHICAL", "False").lower() in ("true", "1", "t")

###############################################################################
# Open Project
# ~~~~~~~~~~~~
# Download Project, opens it and save to TEMP Folder.

tmpfold = tempfile.gettempdir()

temp_folder = os.path.join(tmpfold, generate_unique_name("Example"))
if not os.path.exists(temp_folder):
    os.makedirs(temp_folder)

# Instantiate the application.
app = pyaedt.Hfss(
    specified_version=aedt_version,
    solution_type="SBR+",
    new_desktop_session=True,
    projectname=projectname,
    close_on_exit=True,
    non_graphical=non_graphical
)

app.autosave_disable()

###############################################################################
# Create Design
# ~~~~~~~~~~~~~
# Save project and rename design

app.save_project(project_file=os.path.join(temp_folder, projectname + ".aedt"))
app.rename_design(designname)

###############################################################################
# Libraries
# ~~~~~~~~~~~~~~~
# Setup Library Path to 3d Components

actor_lib = os.path.join(library_path, "actor_library")
env_lib = os.path.join(library_path, "environment_library")
radar_lib = os.path.join(library_path, "radar_modules")
env_folder = os.path.join(env_lib, "road1")
person_folder = os.path.join(actor_lib, "person3")
car_folder = os.path.join(actor_lib, "vehicle1")
bike_folder = os.path.join(actor_lib, "bike1")
bird_folder = os.path.join(actor_lib, "bird1")

###############################################################################
# Environment
# ~~~~~~~~~~~~~~
# Define background environment

road1 = app.modeler.add_environment(env_folder=env_folder, environment_name="Bari")
prim = app.modeler

###############################################################################
# Actors
# ~~~~~~~~~~~~~~~~~~~~~
# Put Actors in environment. This example has persons, birds, bikes and cars.

person1 = app.modeler.add_person(
    actor_folder=person_folder, speed=1.0, global_offset=[25, 1.5, 0], yaw=180, actor_name="Massimo"
)
person2 = app.modeler.add_person(
    actor_folder=person_folder, speed=1.0, global_offset=[25, 2.5, 0], yaw=180, actor_name="Devin"
)
car1 = app.modeler.add_vehicle(actor_folder=car_folder, speed=8.7, global_offset=[3, -2.5, 0], actor_name="LuxuryCar")
bike1 = app.modeler.add_vehicle(
    actor_folder=bike_folder, speed=2.1, global_offset=[24, 3.6, 0], yaw=180, actor_name="Alberto_in_bike"
)
bird1 = app.modeler.add_bird(
    actor_folder=bird_folder,
    speed=1.0,
    global_offset=[19, 4, 3],
    yaw=120,
    pitch=-5,
    flapping_rate=30,
    actor_name="Pigeon",
)
bird2 = app.modeler.add_bird(
    actor_folder=bird_folder, speed=1.0, global_offset=[6, 2, 3], yaw=-60, pitch=10, actor_name="Eagle"
)

###############################################################################
# Radar
# ~~~~~~~~~~~~~~~~~~~~~
# Put radar on car. The radar will be created relative to the car coordinate system.

radar1 = app.create_sbr_radar_from_json(
    radar_file=radar_lib,
    radar_name="Example_1Tx_1Rx",
    offset=[2.57, 0, 0.54],
    use_relative_cs=True,
    relative_cs_name=car1.cs_name,
)

###############################################################################
# Setup and validation
# ~~~~~~~~~~~~~~~~~~~~~
# Create setup and validate it. This command will create a setup and a parametric sweep on the time variable of the
# duration of 2 seconds. the step is computed automatically from CPI.

setup, sweep = app.create_sbr_pulse_doppler_setup(sweep_time_duration=2)
app.set_sbr_current_sources_options()
app.validate_simple()

###############################################################################
# Plot the model
# ~~~~~~~~~~~~~~

app.plot(show=False, export_path=os.path.join(app.working_directory, "Image.jpg"), plot_air_objects=True)

###############################################################################
# Solve and release desktop
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Solves problem and close it. Uncomment the next command to activate the simulation

# app.analyze_setup(sweep.name)
app.save_project()
app.release_desktop(close_projects=True, close_desktop=True)


import curses
from curses import wrapper # it is used to initializes the curses module to use the terminal
import time
import random

def start_screen(stdscr):
    stdscr.clear()
    stdscr.addstr("Welcome to the Speed Typing Test!") # 1 and 0 is basically saying that go 1 line down and start from 0 (row,column)
    stdscr.addstr("\nPress any key to begin!")
    # and if we copy the above line and put a coordinates which are on the same row then they can be overright on the previous mssg
    stdscr.refresh()
    stdscr.getkey()

def display_text(stdscr, target, current, wpm=0):
    stdscr.addstr(target)
    stdscr.addstr(1, 0, f"WPM: {wpm}")

    for i, char in enumerate(current):
        correct_char = target[i]
        color = curses.color_pair(1)
        if char != correct_char:
            color = curses.color_pair(2)

        stdscr.addstr(0, i, char, color)

def load_text():
    with open("text.txt", "r") as f:
        lines = f.readlines()
        return random.choice(lines).strip()

def wpm_test(stdscr):
    target_text = load_text()
    current_text = []
    wpm = 0
    start_time = time.time() # its keeping track of the start time which is basically a large set of no. generally called as 'epoch'
    stdscr.nodelay(True)

    while True:
        time_elapsed = max(time.time() - start_time, 1)
        wpm = round((len(current_text) / (time_elapsed / 60)) / 5) # to calculate the Words Per Minute(WPM)
        #        this above is characters per min. and if we divide it by 5 then it becomes WPM

        stdscr.erase()
        display_text(stdscr, target_text, current_text, wpm)
        stdscr.refresh()

        if "".join(current_text) == target_text:
            stdscr.nodelay(False)
            break

        try:
            key = stdscr.getkey() # cause if we didnt press any keys it will throw exception so we handled it
        except:
            continue

        if current_text == []: # this will start the wpm counter only when the user types
            start_time = time.time()

        #if ord(key) == 27: (this doesn't work maybe on this version or os) # ord is basically a ordinal value which is like ascii or unicode value of any character i.e. in this 27 is for esc key
        if key in ["\x1b"]:
            break

        if key in ("KEY_BACKSPACE", '\b', '\x7f'):
            if len(current_text) > 0:
                current_text.pop()
        elif len(current_text) < len(target_text):
            current_text.append(key)

def main(stdscr): #std screen
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK)

    start_screen(stdscr)
    while True:
        wpm_test(stdscr)
        stdscr.addstr(2, 0, "You completed the text! Press any key to continue....")
        key = stdscr.getkey()

        if key in ["\x1b"]:
            break

wrapper(main)


#--------------------------------------------------------------------------------
# viscosity.py, Dec 2021, Yunguo Li @ USTC
# This script can calculate stress autocorrelation function (SACF) and
# bulk/shear viscosity
# VASP OUTCAR needed as input file.
#--------------------------------------------------------------------------------

import os, sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft, fftfreq, fftshift, rfft

# Boltzmann Constant in [eV/K]
kb = 8.617332478E-5
# electron volt in [Joule]
ev = 1.60217733E-19
# ev to A^3*GPa
ev2pv = 160.21766208

#--------------------------------------------------------------------------------
class viscosity:

    def __init__(self,File=None):
        if File is None:
            self.outcar = 'OUTCAR'
        else:
            self.outcar = File

        self.potim    = None          # time step of MD
        self.nblock   = None          # trajectory writting interval
        self.Nions    = None          # total no. of ions
        self.volume   = None          # volume of system
        self.Niter    = 0             # no. of interations
        self.stress   = np.zeros(6)   # stresses each step;
                                      # direction:XX,YY,ZZ,XY,YZ,ZX
        self.Press    = 0             # average pressure
        self.Temp     = None          # temperature each step
        self.TypeName = ['xx','yy','zz','xy','yz','zx']
        # Velocity Autocorrelation Function
        self.ACF = None
        self.ACF2= None

        self.readoutcar()

    def readoutcar(self):
        print("Reading stresses from OUTCAR ......")
        if os.path.isfile(self.outcar):
            outcar = [line.strip() for line in open(self.outcar)]
            lm=0; lb=0; li=0; lv=0; lk=0; lp=0
            for ll, line in enumerate(outcar):
                if 'POTIM' in line:    # read POTIM
                    lm=ll
                    self.potim = float(outcar[ll].split()[2])
                if 'NBLOCK' in line:    # XDATCAR writting interval
                    lb=ll
                    self.nblock = float(outcar[ll].split()[2].replace(';',''))
                if 'number of ions ' in line:    # read number of ions
                    li=ll
                    self.Nions = float(outcar[ll].split()[11])
                if 'volume of cell' in line:    # read volume
                    lv=ll
                    self.volume = np.array(outcar[ll].split()[4], dtype=float)
                if 'EKIN_LAT=' in line:    # read T
                    self.Temp = np.array(outcar[ll].split()[5], dtype=float)
                    lk=ll
                    self.Niter += 1
                if 'Total+kin.' in line:    # read stresses
                    self.stress = np.array(outcar[ll].split()[1:], dtype=float)
                    lp=ll
                if lm and lb and li and lv and lk and lp:
                    break

            for ll, line in enumerate(outcar):
                if 'EKIN_LAT=' in line:    # read T
                    self.Temp = np.append(self.Temp,
                                np.array(outcar[ll].split()[5], dtype=float))
                if 'Total+kin.' in line:    # read stresses
                    self.stress = np.append(self.stress,
                                  np.array(outcar[ll].split()[1:], dtype=float) )
                    self.Niter += 1
        else:
            print("ERROR reading OUTCAR !!!")

        self.stress = np.reshape(self.stress, (self.Niter, 6)) / 10    # in GPa
        self.Press = np.average(np.average(self.stress[:,0:3]))      # average P

        return

    def getACF(self, method=None):

        #---- Cross-correlation ----
        # in this function, numpy.correlate is used to calculate the ACF
        if method == 'correlate':
            print("Calculating stress auto-correlation function ......")
            self.stress[:,0:3] = self.stress[:,0:3] - self.Press
            # np.correlate(a[:n],a[:m],'full') returns the number of
            # n+m-1 elements
            self.ACF2 = np.zeros((6, self.Niter*2 - 1))
            # we have 5 independent shear stresses
            # self.stress in direction:XX,YY,ZZ,XY,YZ,ZX
            self.ACF2[0,:] = np.correlate((self.stress[:,0]+self.stress[:,1]
                             + self.stress[:,2])/3, (self.stress[:,0]
                             + self.stress[:,1]+self.stress[:,2])/3,'full')
            self.ACF2[1,:] = self.ACF2[0,:]  ; self.ACF2[2,:] = self.ACF2[0,:]
            for i in range(3,6):
                self.ACF2[i,:] = np.correlate(self.stress[:,i],
                                        self.stress[:,i],'full')

            # average: np.correlate(a,a,'full') returns 2*n-1 elements,
            # which in total performs v(t1+t2)*v(t2) the times of n**2
            self.ACF2[:,:] /=self.Niter
            self.ACF = self.ACF2[:,self.Niter-1:]

        #---- alternatively, in explicite ----
        else:
            print("SACF is calculated straightforwardly ...")
            self.ACF2 = np.zeros((6, self.Niter*2 - 1))
            self.ACF = np.zeros((6, self.Niter))
            for i in range(self.Niter):
                self.ACF[0,i] = self.stress[i,0]*self.stress[0,0]    # XY
                self.ACF[1,i] = self.stress[i,1]*self.stress[0,1]    # YZ
                self.ACF[2,i] = self.stress[i,2]*self.stress[0,2]    # ZX
                self.ACF[3,i] = (np.average(self.stress[i,3:6]) - self.Press) \
                                * (np.average(self.stress[0,3:6])- self.Press)/9
                self.ACF[4,i] = self.ACF[3,i]
                self.ACF[5,i] = self.ACF[3,i]
            # unit GPa^2
            self.ACF2[:,:self.Niter] = self.ACF[:,:]

        return self.ACF

    def visco(self, method='fft',acf_method='correlate'):
        print("Calculating viscosity from stress auto-correlation "
              + "function ......")

        # Frequency in THz: omega[0]=0, omega[self.Niter-1]=
        # fft tranformation has the frequency of Fn=(n-1)*Fs/N for N point
        # input data, and n<=N/2
        omega = fftfreq( self.Niter, self.potim*self.nblock ) * 1E3
        #print(omega[0],omega[self.Niter-1],omega[self.Niter])

        #---- fft ----
        if method == 'fft':
            if self.ACF is None:
                self.getACF(acf_method)      # (method='correlate') or ()
            vis = np.zeros_like(self.ACF)    # pdos shape
            # viscosity in unit of Pa*S; here self.ACF should be used other than
            #  VSF2, otherwise,
            # vis should be normalised with a factor of
            # len(self.ACF)/len(self.ACF2)
            vis[:,:] = np.abs(fft(self.ACF[:,:])) \
                       * self.volume/kb/np.average(self.Temp)/ev2pv *1E-6
        #---- integrate ----
        elif method == 'integrate':
            if self.ACF is None:
                self.getACF(acf_method)      # (method='correlate') or ()
            from scipy.integrate import cumtrapz
            vis = cumtrapz(self.ACF, self.potim*self.nblock \
                          * np.arange(1,self.Niter+1)) * \
                           self.volume/kb/np.average(self.Temp)/ev2pv *1E-6
            # note: integration cumtrapz returns one date less than input.
            return np.arange(2,self.Niter+1), vis

        else:
            print("Chosen spectrum analysis method not found ...")
            sys.exit()

        return omega[:self.Niter//2], vis[:,:self.Niter//2]

#-------------------------------------------------------------------------------


from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences

from keras.models import Sequential,Model
from keras.layers import LSTM, Flatten, Dense, Bidirectional,Input,Dropout

from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers,regularizers, constraints
import math

class ModelC:

    def __init__(self):

        pass

    def create_model(self, SEQ_LEN ):

        print("Creating Model ......................")
        model = Sequential()
        model.add(Bidirectional(LSTM(10, return_sequences = True),input_shape = (SEQ_LEN,300)))
        model.add(Bidirectional(LSTM(4)))
        model.add(Dense(8,activation = 'relu'))
        model.add(Dense(2,activation = 'softmax'))
        model.compile(loss='binary_crossentropy',
                    optimizer='adam',
                    metrics=['accuracy'])

        print("Model Created ")
        print(model.summary())

        return model

    def train(self, model, mg, train_df, batch_size, stopWords, emb, SEQ_LEN, preProcessor):

        print("Starting the model training ........................")
        mg = preProcessor.batch_gen(train_df,batch_size,SEQ_LEN,stopWords,emb)
        model.fit_generator(mg, epochs=5,
                            steps_per_epoch=32,
                            verbose=True)

        print("Model Trained")
        return model

    def predict(self, model, mg, testQ, stopWords, emb, SEQ_LEN, preProcessor):

        test_questions = preProcessor.batch_gen_test(testQ,SEQ_LEN,stopWords,emb)

        for ques in test_questions:
            pred = model.predict(ques)

        i = 0

        for prediction in pred:
            print("Question : ",testQ[i])
            i = i+1
            if(prediction[0] >= 0.5):
                print("Question belongs to Political Category")
                print("Confidence : ",prediction[0]*100,"%")
            else:
                print("Question belongs to Movies Category")
                print("Confidence : ",prediction[1]*100,"%")

    def save_model(self, model, name):

        print("Saving the model")
        model.save('data/'+name+'.h5')
        print("Model saved")