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

# Create your models here.
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
import datetime
from django.utils.translation import ugettext as _

class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)
    is_parent = models.BooleanField(default=False)

class UserType(models.Model):
    user_type = models.CharField(max_length=100, primary_key=True)

GENDER_CHOICES = (
    (1, _("Male")),
    (2, _("Female"))
)

class Parent(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    first_name = models.CharField(max_length=100, null=True)
    last_name = models.CharField(max_length=100, null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)
    email = models.EmailField(max_length=100, null=True)
    address = models.CharField(max_length=200, null=True)

    city = models.CharField(max_length=100, null=True)

    def __str__(self):
        if self.first_name and not self.last_name:
            return self.first_name
        elif self.first_name and self.last_name:
            return self.first_name + ' ' + self.last_name
        else:
            return 'Parent'

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    first_name = models.CharField(max_length=100, null=True)
    last_name = models.CharField(max_length=100, null=True)
    email = models.EmailField(max_length=100, null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)
    address = models.CharField(max_length=200, null=True)
    city = models.CharField(max_length=100, null=True)
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE,null=True , blank=True)

    def __str__(self):
        if self.first_name and not self.last_name:
            return self.first_name
        elif self.first_name and self.last_name:
            return self.first_name + ' ' + self.last_name
        else:
            return 'Student'

    def get_unanswered_questions(self, exam):
        answered_questions = self.exam_question_logs \
            .filter(exam=exam) \
            .values_list('question__pk', flat=True)
        questions = exam.questions.exclude(pk__in=answered_questions).order_by('question_text')
        return questions

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    first_name = models.CharField(max_length=100, null=True)
    last_name = models.CharField(max_length=100, null=True)
    email = models.EmailField(max_length=100, null=True)
    address = models.CharField(max_length=200, null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)
    city = models.CharField(max_length=100, null=True)
    qualification = models.CharField(max_length=100, null=True)

    def __str__(self):
        if self.first_name and not self.last_name:
            return self.first_name
        elif self.first_name and self.last_name:
            return self.first_name + ' ' + self.last_name
        else:
            return 'Teacher'

class Department(models.Model):
    department_name = models.CharField(max_length=100)
    description = models.CharField(max_length=200, null=True)

    def __str__(self):
        if self.department_name:
            return self.department_name
        else:
            return 'Department'

class Course(models.Model):
    course = models.CharField(max_length=100)
    dept_description = models.CharField(max_length=200, null=True)
    department = models.ForeignKey(Department, on_delete=models.CASCADE)

    def __str__(self):
        if self.course:
            return self.course
        else:
            return 'Course'

class Subject(models.Model):
    subject = models.CharField(max_length=100)
    subject_description = models.CharField(max_length=200, null=True)
    course = models.ForeignKey(Course, on_delete=models.CASCADE,related_name='subjects')

    def __str__(self):
        if self.subject:
            return self.subject
        else:
            return 'Subject'

class Exam(models.Model):
    exam_name = models.CharField(max_length=100,null=True)
    description = models.CharField(max_length=200, null=True,blank=True)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE,related_name='exams')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='exams')

    def __str__(self):
        if self.exam_name:
            return self.exam_name
        else:
            return 'Exam'

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE,null=True,related_name='questions')
    pub_date = models.DateTimeField('date published',auto_now_add=True)
    weightage = models.IntegerField(default=5)

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class StudentCourse(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    student = models.ForeignKey(Student, on_delete=models.CASCADE,related_name='student_courses')

class ExamResult(models.Model):
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE,related_name='exam_results')
    student = models.ForeignKey(Student, on_delete=models.CASCADE,related_name='exam_results')
    score = models.FloatField(null=True)
    evaluated = models.BooleanField(default=False)
    date = models.DateTimeField(auto_now_add=True)

class ExamLog(models.Model):
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE,related_name='exam_question_logs')
    student = models.ForeignKey(Student, on_delete=models.CASCADE,related_name='exam_question_logs')
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    weightage = models.IntegerField(default=5)
    score = models.FloatField(null=True)
    evaluated = models.BooleanField(default=False)
    answer = models.CharField(max_length=200,default=False)
    date = models.DateTimeField(auto_now_add=True)

class Attendance(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE,related_name='student_attendances')
    attendance_date = models.DateField('attendance date')
    attendance_status = models.BooleanField('Present',default=False)
    reason_for_absentee = models.CharField(max_length=200, null=True, blank=True)
    attendance_marked_by = models.ForeignKey(Teacher, on_delete=models.CASCADE)


# -*- coding: utf-8 -*-
from wrappers.auth import get_spotify
from wrappers.spotify_playlist import get_all_playlists, create_playlist, cache_playlists, add_to_playlist
from wrappers.spotify_tracks import get_all_tracks_from_playlist, append_audio_features, sort_list_by_attribute, \
    AudioAttribute

def list_matching_playlists(find_target_playlist: callable):
    """This will print all the playlist variants that were created."""
    spotify = get_spotify()

    playlists = get_all_playlists(spotify)
    matching_playlists = []
    for playlist in playlists:
        print(f"Looking through the playlist: {playlist.name}", end="\r", flush=True)
        if not find_target_playlist(playlist.name):
            continue

        matching_playlists.append(playlist)
        print(f"- {playlist.name} ({playlist.external_urls['spotify']})")

    return matching_playlists

def main(find_target_playlist: callable, create_playlists: bool):
    spotify = get_spotify()

    playlists = get_all_playlists(spotify)

    cache_playlists(playlists=playlists)

    tracks = []

    target_playlist_name = ""
    for playlist in playlists:
        print(f"Looking through the playlist: {playlist.name}", end="\r", flush=True)
        if not find_target_playlist(playlist.name):
            continue
        target_playlist_name = playlist.name
        print(f"Found target playlist: {target_playlist_name}")

        tracks = get_all_tracks_from_playlist(spotify, playlist.id)
        break

    full_tracks = append_audio_features(spotify, tracks)
    for attr in [attr for attr in AudioAttribute]:
        sorted_playlist_name = attr.value
        for is_reverse in [True, False]:
            sorted_tracks = sort_list_by_attribute(tracks=full_tracks, attribute=attr, reverse=is_reverse)
            variant_name = f"{sorted_playlist_name}__{'DESC' if is_reverse else 'ASC'}"
            with open(f"playlist_{variant_name}.txt", mode="w", encoding="utf-8") as file:
                file.writelines([f"{s_track.title} - {s_track.artist.name}\n" for s_track in sorted_tracks])

            if not create_playlists:
                continue
            spotify_playlist_name = f"{target_playlist_name} - {variant_name.replace('_', ' ')}".replace("  ", " ")
            sorted_playlist, from_cache = create_playlist(
                spotify=spotify,
                name=spotify_playlist_name,
                description="Created automatically using Python. 🤓🐍 "
                            "-- https://github.com/brenordv/spotify-playlist-sorter")

            add_to_playlist(spotify=spotify, playlist_id=sorted_playlist.id,
                            tracks=sorted_tracks, update_playlist=from_cache)

if __name__ == '__main__':
    # Change the lambda below to something that will match the playlist you want. You can simply change the text.
    main(find_target_playlist=lambda x: "2022" in x,
         create_playlists=True)


from typing import List
from pathlib import Path

from build_assets.selenium_runner.SeleniumRunner import SeleniumRunner
from build_assets.selenium_runner.enums import IcomoonPage, IcomoonAlerts

class PeekSeleniumRunner(SeleniumRunner):
    def peek(self, svgs: List[str], screenshot_folder: str, icon_info: dict):
        """
        Upload the SVGs and peek at how Icomoon interpret its SVGs and
        font versions.
        :param svgs: a list of svg Paths that we'll upload to icomoon.
        :param screenshot_folder: the name of the screenshot_folder.
        :param icon_info: a dictionary containing info on an icon. Taken from the devicon.json.
        :return an array of svgs with strokes as strings. These show which icon
        contains stroke.
        """
        messages = self.peek_svgs(svgs, screenshot_folder)
        self.peek_icons(screenshot_folder, icon_info)
        return messages

    def peek_svgs(self, svgs: List[str], screenshot_folder: str):
        """
        Peek at the SVGs provided in svgs. This will look at how Icomoon
        interprets the SVGs as a font.
        :param svgs: a list of svg Paths that we'll upload to icomoon.
        :param screenshot_folder: the name of the screenshot_folder.
        :return an array of svgs with strokes as strings. These show which icon
        contains stroke.
        """
        print("Peeking SVGs...", file=self.log_output)

        import_btn = self.driver.find_element_by_css_selector(
            SeleniumRunner.GENERAL_IMPORT_BUTTON_CSS
        )

        svgs_with_strokes = []
        for i in range(len(svgs)):
            import_btn.send_keys(svgs[i])
            print(f"Uploaded {svgs[i]}", file=self.log_output)

            alert = self.test_for_possible_alert(self.SHORT_WAIT_IN_SEC)
            if alert == None:
                pass  # all good
            elif alert == IcomoonAlerts.STROKES_GET_IGNORED_WARNING:
                print(f"- This icon contains strokes: {svgs[i]}", file=self.log_output)
                svg = Path(svgs[i])
                svgs_with_strokes.append(f"- {svg.name}")
                self.click_alert_button(self.ALERTS[alert]["buttons"]["DISMISS"])
            else:
                raise Exception(f"Unexpected alert found: {alert}")

            self.edit_svg(screenshot_folder, i)

        # take a screenshot of the svgs that were just added
        self.select_all_icons_in_top_set()
        new_svgs_path = str(Path(screenshot_folder, "new_svgs.png").resolve())
        icon_set_xpath = "/html/body/div[4]/div[1]/div[2]/div[1]"
        icon_set = self.driver.find_element_by_xpath(icon_set_xpath)
        icon_set.screenshot(new_svgs_path)

        print("Finished peeking the svgs...", file=self.log_output)
        return svgs_with_strokes

    def peek_icons(self, screenshot_folder: str, icon_info: dict):
        """
        Peek at the icon versions of the SVGs that were uploaded.
        :param screenshot_folder: the name of the screenshot_folder.
        :param icon_info: a dictionary containing info on an icon. Taken from the devicon.json.
        """
        print("Begin peeking at the icons...", file=self.log_output)
        # ensure all icons in the set is selected.
        self.select_all_icons_in_top_set()
        self.go_to_page(IcomoonPage.GENERATE_FONT)
        alert = self.test_for_possible_alert(self.MED_WAIT_IN_SEC)
        if alert == None:
            pass  # all good
        elif alert == IcomoonAlerts.DESELECT_ICONS_CONTAINING_STROKES:
            self.click_alert_button(self.ALERTS[alert]["buttons"]["CONTINUE"])
        else:
            raise Exception(f"Unexpected alert found: {alert}")

        # take an overall screenshot of the icons that were just added
        # also include the glyph count
        new_icons_path = str(Path(screenshot_folder, "new_icons.png").resolve())
        main_content_xpath = "/html/body/div[4]/div[2]/div/div[1]"
        main_content = self.driver.find_element_by_xpath(main_content_xpath)
        main_content.screenshot(new_icons_path);

        # go in reverse order so we get the oldest icon first
        icon_divs_xpath = f'//div[@id="glyphSet0"]/div'
        icon_divs = self.driver.find_elements_by_xpath(icon_divs_xpath)
        icon_divs.reverse()
        i = 0
        for icon_div in icon_divs:
            if not icon_div.is_displayed():
                continue

            icon_screenshot = str(
                Path(screenshot_folder, f"new_icon_{i}.png").resolve()
            )
            icon_div.screenshot(icon_screenshot)

            i += 1

        # test the colors
        style = "#glyphSet0 span:first-of-type {color: " + icon_info["color"] + "}"
        script = f"document.styleSheets[0].insertRule('{style}', 0)"
        self.driver.execute_script(script)
        i = 0
        for icon_div in icon_divs:
            if not icon_div.is_displayed():
                continue

            icon_screenshot = str(
                Path(screenshot_folder, f"new_colored_icon_{i}.png").resolve()
            )
            icon_div.screenshot(icon_screenshot)

            i += 1

        print("Finished peeking the icons...", file=self.log_output)


"""Combination operators."""

import asyncio
import builtins

from ..aiter_utils import AsyncExitStack, anext
from ..core import operator, streamcontext

from . import create
from . import select
from . import advanced
from . import aggregate

__all__ = ["chain", "zip", "map", "merge", "ziplatest"]

@operator(pipable=True)
async def chain(*sources):
    """Chain asynchronous sequences together, in the order they are given.

    Note: the sequences are not iterated until it is required,
    so if the operation is interrupted, the remaining sequences
    will be left untouched.
    """
    for source in sources:
        async with streamcontext(source) as streamer:
            async for item in streamer:
                yield item

@operator(pipable=True)
async def zip(*sources):
    """Combine and forward the elements of several asynchronous sequences.

    Each generated value is a tuple of elements, using the same order as
    their respective sources. The generation continues until the shortest
    sequence is exhausted.

    Note: the different sequences are awaited in parrallel, so that their
    waiting times don't add up.
    """
    async with AsyncExitStack() as stack:
        # Handle resources
        streamers = [
            await stack.enter_async_context(streamcontext(source)) for source in sources
        ]
        # Loop over items
        while True:
            try:
                coros = builtins.map(anext, streamers)
                items = await asyncio.gather(*coros)
            except StopAsyncIteration:
                break
            else:
                yield tuple(items)

@operator(pipable=True)
async def smap(source, func, *more_sources):
    """Apply a given function to the elements of one or several
    asynchronous sequences.

    Each element is used as a positional argument, using the same order as
    their respective sources. The generation continues until the shortest
    sequence is exhausted. The function is treated synchronously.

    Note: if more than one sequence is provided, they're awaited concurrently
    so that their waiting times don't add up.
    """
    if more_sources:
        source = zip(source, *more_sources)
    async with streamcontext(source) as streamer:
        async for item in streamer:
            yield func(*item) if more_sources else func(item)

@operator(pipable=True)
def amap(source, corofn, *more_sources, ordered=True, task_limit=None):
    """Apply a given coroutine function to the elements of one or several
    asynchronous sequences.

    Each element is used as a positional argument, using the same order as
    their respective sources. The generation continues until the shortest
    sequence is exhausted.

    The results can either be returned in or out of order, depending on
    the corresponding ``ordered`` argument.

    The coroutines run concurrently but their amount can be limited using
    the ``task_limit`` argument. A value of ``1`` will cause the coroutines
    to run sequentially.

    If more than one sequence is provided, they're also awaited concurrently,
    so that their waiting times don't add up.
    """

    def func(*args):
        return create.call(corofn, *args)

    if ordered:
        return advanced.concatmap.raw(
            source, func, *more_sources, task_limit=task_limit
        )
    return advanced.flatmap.raw(source, func, *more_sources, task_limit=task_limit)

@operator(pipable=True)
def map(source, func, *more_sources, ordered=True, task_limit=None):
    """Apply a given function to the elements of one or several
    asynchronous sequences.

    Each element is used as a positional argument, using the same order as
    their respective sources. The generation continues until the shortest
    sequence is exhausted. The function can either be synchronous or
    asynchronous (coroutine function).

    The results can either be returned in or out of order, depending on
    the corresponding ``ordered`` argument. This argument is ignored if the
    provided function is synchronous.

    The coroutines run concurrently but their amount can be limited using
    the ``task_limit`` argument. A value of ``1`` will cause the coroutines
    to run sequentially. This argument is ignored if the provided function
    is synchronous.

    If more than one sequence is provided, they're also awaited concurrently,
    so that their waiting times don't add up.

    It might happen that the provided function returns a coroutine but is not
    a coroutine function per se. In this case, one can wrap the function with
    ``aiostream.async_`` in order to force ``map`` to await the resulting
    coroutine. The following example illustrates the use ``async_`` with a
    lambda function::

        from aiostream import stream, async_
        ...
        ys = stream.map(xs, async_(lambda ms: asyncio.sleep(ms / 1000)))
    """
    if asyncio.iscoroutinefunction(func):
        return amap.raw(
            source, func, *more_sources, ordered=ordered, task_limit=task_limit
        )
    return smap.raw(source, func, *more_sources)

@operator(pipable=True)
def merge(*sources):
    """Merge several asynchronous sequences together.

    All the sequences are iterated simultaneously and their elements
    are forwarded as soon as they're available. The generation continues
    until all the sequences are exhausted.
    """
    return advanced.flatten.raw(create.iterate.raw(sources))

@operator(pipable=True)
def ziplatest(*sources, partial=True, default=None):
    """Combine several asynchronous sequences together, producing a tuple with
    the lastest element of each sequence whenever a new element is received.

    The value to use when a sequence has not procuded any element yet is given
    by the ``default`` argument (defaulting to ``None``).

    The producing of partial results can be disabled by setting the optional
    argument ``partial`` to ``False``.

    All the sequences are iterated simultaneously and their elements
    are forwarded as soon as they're available. The generation continues
    until all the sequences are exhausted.
    """
    n = len(sources)

    # Custom getter
    def getter(dct):
        return lambda key: dct.get(key, default)

    # Add source index to the items
    new_sources = [
        smap.raw(source, lambda x, i=i: {i: x}) for i, source in enumerate(sources)
    ]

    # Merge the sources
    merged = merge.raw(*new_sources)

    # Accumulate the current state in a dict
    accumulated = aggregate.accumulate.raw(merged, lambda x, e: {**x, **e})

    # Filter partial result
    filtered = (
        accumulated
        if partial
        else select.filter.raw(accumulated, lambda x: len(x) == n)
    )

    # Convert the state dict to a tuple
    return smap.raw(filtered, lambda x: tuple(builtins.map(getter(x), range(n))))


import os, shutil, re

prefix = 'spam'
folder = 'D:\\PythonLab\\test'

numRegex = re.compile(r'^.*?00(\d+)')

# list files in the folder
files = os.listdir('D:\\PythonLab\\test')
files.sort()

number = 1

# rename files to fill the gaps by renaming files
for file in files:
    if not file.startswith(prefix) or not file.endswith('txt'):
        continue

    file_temp = prefix + '00' + str(number) + '.txt'

    if file == file_temp:
        number = number + 1
        continue
    else:
        path_old = os.path.join(folder,file)
        path_new = os.path.join(folder, file_temp)

        print(path_old + ' to ' + path_new)

        shutil.move(path_old, path_new)
        number = number + 1


import pygame
from Levels import Level_01, Level_02, Level_03, Level_04, Level_05, END_GAME
from Properties.Record import *

LEVEL_LIST = [Level_01, Level_02, Level_03, Level_04, Level_05, END_GAME]
corentFloors = []
corentWalls = []
corentCrates = []
corentSpecial = []
corentOrea = []
# records
corentRecord = None
corentPlayer = None
index_character = 0
# next level triger
exitOrea = None

def loadLevel(win, num):
    global corentFloors, corentWalls, corentCrates, corentSpecial, corentPlayer, corentRecord, index_character, corentOrea, exitOrea, NEXT_LEVEL
    num -= 1
    corentFloors = LEVEL_LIST[num].createFloor(win)
    corentWalls = LEVEL_LIST[num].createWall(win)
    corentCrates = LEVEL_LIST[num].createCrate(win)
    corentSpecial = LEVEL_LIST[num].createSpecial(win)
    corentOrea = LEVEL_LIST[num].creatOrea(win)

    corentPlayer = LEVEL_LIST[num].creatPlayer(win)
    # ready record engein
    corentPlayer.reset_record()
    corentRecord = TapeRecorder()  # creat tape for the retocrds
    index_character = 0

    # next level triger
    for orea in corentOrea:
        if orea.name == "exit":
            exitOrea = orea

def cleanLevel():
    global corentFloors, corentWalls, corentCrates, corentSpecial, corentPlayer, corentRecord, index_character, corentOrea, exitOrea
    corentFloors = []
    corentWalls = []
    corentCrates = []
    corentSpecial = []
    corentOrea = []
    # records
    corentRecord = None
    corentPlayer = None
    index_character = 0
    # next level
    exitOrea = None

def next_level():
    if exitOrea is not None:
        return exitOrea.state
    else:
        return False

def blitLevel():
    for object in corentSpecial + corentFloors + corentWalls + corentCrates + [corentRecord, corentPlayer] + corentOrea:
        object.blit()

def update():
    for object in corentSpecial + corentCrates + corentOrea:
        object.update()

def reset():
    for object in corentCrates + corentSpecial:
        object.reset()


from qsp_v1 import *
import numpy as np
from random import *

#V = [1/np.sqrt(2),0,0,0,0,0,0,1/np.sqrt(2)]
n=8
A=[]
B=[]
for i in range(n):
	A.append(random())
	B.append(random())

SA = np.sum(A)
SB = np.sum(B)

VA = A/SA
VB = B/SB

A = np.sqrt(VA)
B = np.sqrt(VB)

print("A = ",A)

print("B = ",B)

V = tensorproduct(A,B)

print("V = ",V)

Angulos = gen_angles(V)

print("Árvore de Ângulos")
angles_tree(Angulos)


from rest_framework import serializers
from drf_queryfields import QueryFieldsMixin

from .models import FriendRequest, Friends
from user.serializers import UserSerializer
from user.models import UserActivity

class FriendRequestSerializer(QueryFieldsMixin, serializers.ModelSerializer):

    from_user = serializers.SerializerMethodField()
    to_user = serializers.SerializerMethodField()

    class Meta:
        model = FriendRequest
        fields = ['id', 'to_user', 'from_user', 'created_on']

    def get_from_user(self, obj):
        curr_user = self.context['curr_user']
        return UserSerializer(obj.from_user,
                              context={'curr_user': curr_user}).data

    def get_to_user(self, obj):
        curr_user = self.context['curr_user']
        return UserSerializer(obj.to_user,
                              context={'curr_user': curr_user}).data

class FriendsSerializer(QueryFieldsMixin, serializers.ModelSerializer):

    user = UserSerializer()
    friends_list = serializers.SerializerMethodField()

    class Meta:
        model = Friends
        fields = ['id', 'user', 'friends_list', 'updated_on']

    def get_friends_list(self, obj):
        curr_user = self.context['curr_user']
        return UserSerializer(obj.friends_list, many=True,
                              context={'curr_user': curr_user}).data

class FriendActivitesSerializer(QueryFieldsMixin, serializers.ModelSerializer):
    """
    This serializer module is for serializing the UserActivity model
    and getting all the required response
    """

    target = serializers.SerializerMethodField()

    class Meta:
        model = UserActivity
        fields = ['id', 'user', 'action', 'target']

    def get_target(self, obj):
        target_dict = {'type': str(obj.content_type.model_class()),
                       'id': obj.object_id}
        return target_dict


import unittest
from datetime import datetime, timedelta
from unittest.mock import patch

from spaceone.core.unittest.result import print_data
from spaceone.core.unittest.runner import RichTestRunner
from spaceone.core import config
from spaceone.core import utils
from spaceone.core.transaction import Transaction
from spaceone.monitoring.error import *
from spaceone.monitoring.connector.aws_boto_connector import AWSBotoConnector
from spaceone.monitoring.service.metric_service import MetricService
from spaceone.monitoring.info.metric_info import MetricsInfo, MetricDataInfo

class TestMetricService(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        config.init_conf(package='spaceone.monitoring')
        cls.transaction = Transaction({
            'service': 'monitoring',
            'api_class': 'DataSource'
        })
        super().setUpClass()

    @classmethod
    def tearDownClass(cls) -> None:
        super().tearDownClass()

    @patch.object(AWSBotoConnector, '__init__', return_value=None)
    @patch.object(AWSBotoConnector, 'create_session', return_value=None)
    @patch.object(AWSBotoConnector, 'list_metrics')
    def test_list_metrics(self, mock_list_metrics, *args):
        mock_list_metrics.return_value = {
            'metrics': [
                {
                    'key': 'StatusCheckFailed_System',
                    'name': 'StatusCheckFailed_System',
                    'unit': {'x': 'Timestamp', 'y': 'Count'},
                    'metric_query': {
                        'Dimensions': [{'Name': 'HostedZoneId', 'Value': 'Z01028552THR4GSCEJ9E3'}],
                        'MetricName': 'DNSQueries',
                        'Namespace': 'AWS/Route53'
                    }
                }, {
                    'key': 'EBSReadOps',
                    'name': 'EBSReadOps',
                    'unit': {'x': 'Timestamp', 'y': 'Count'},
                    'metric_query': {
                        'Dimensions': [{'Name': 'HostedZoneId', 'Value': 'Z01028552THR4GSCEJ9E3'}],
                        'MetricName': 'DNSQueries',
                        'Namespace': 'AWS/Route53'
                    }
                }
            ]
        }

        params = {
            'options': {},
            'secret_data': {},
            'query': {
                "region_name": "ap-southeast-1",
                "metrics_info": [
                    {
                        "Namespace": "AWS/EC2",
                        "Dimensions": [
                            {
                                "Name": "InstanceId",
                                "Value": "i-0ecbd2feb6ae4ee65"
                            }
                        ]
                    },
                    {
                        "Dimensions": [
                            {
                                "Name": "InstanceId",
                                "Value": "i-0ecbd2feb6ae4ee65"
                            }
                        ],
                        "Namespace": "CWAgent"
                    }
                ]
            }
        }

        self.transaction.method = 'list'
        metric_svc = MetricService(transaction=self.transaction)
        response = metric_svc.list(params.copy())
        print_data(response, 'test_list_metrics')
        MetricsInfo(response)

    @patch.object(AWSBotoConnector, '__init__', return_value=None)
    @patch.object(AWSBotoConnector, 'create_session', return_value=None)
    @patch.object(AWSBotoConnector, 'get_metric_data')
    def test_get_metric_data(self, mock_get_metric_data, *args):
        end = datetime.utcnow()
        start = end - timedelta(days=1)
        mock_get_metric_data.return_value = {
            'labels': [
                {'seconds': 1586988300},
                {'seconds': 1586988000},
                {'seconds': 1586987700},
                {'seconds': 1586987400},
                {'seconds': 1586987100},
                {'seconds': 1586986800},
                {'seconds': 1586986500},
                {'seconds': 1586986200},
                {'seconds': 1586985900},
                {'seconds': 1586985600},
                {'seconds': 1586985300},
                {'seconds': 1586985000}
            ],
            'values': [4.0, 4.0, 4.0, 4.0, 4.4, 4.4, 4.0, 4.0, 6.0, 4.0, 4.0, 4.4]
        }

        params = {
            'options': {},
            'secret_data': {},
            'resource': {
                "namespace": "AWS/EC2",
                "dimensions": [
                    {
                        "Name": "InstanceId",
                        "Value": "i-011e8d755568b446b"
                    }
                ],
                "region_name": "ap-northeast-2"
            },
            'metric': 'CPUUtilization',
            'start': start.isoformat(),
            'end': end.isoformat()
        }

        self.transaction.method = 'get_data'
        metric_svc = MetricService(transaction=self.transaction)
        response = metric_svc.get_data(params.copy())
        print_data(response, 'test_get_metric_data')
        MetricDataInfo(response)

if __name__ == "__main__":
    unittest.main(testRunner=RichTestRunner)


from kazoo.client import KazooClient
import time

zk = KazooClient(hosts="127.0.0.1:2182")

zk.start()

# print('111111111111')

# time.sleep(10)

def test_ensure():
    print(__name__)
    zk.ensure_path("/my/path")

def test_create():
    print(__name__)
    nodename = "/my/path/node"
    index = 1
    while index < 10:
        zk.create(
            nodename,
            "10.0.0.1_{index}".format(index=index).encode(),
            ephemeral=True,
            sequence=True,
        )
        # time.sleep(10)
        index += 1

if __name__ == "__main__":
    # test_ensure()
    test_create()
    time.sleep(100)

    zk.stop()


# 3. Реализовать программу работы с органическими клетками.
# Необходимо создать класс Клетка. В его конструкторе инициализировать параметр, соответствующий количеству клеток (целое число).
# В классе должны быть реализованы методы перегрузки арифметических операторов:
# сложение (__add__()), вычитание (__sub__()), умножение (__mul__()), деление (__truediv__()).
# Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение, умножение и обычное (не целочисленное) деление клеток, соответственно.
# В методе деления должно осуществляться округление значения до целого числа.
# В классе необходимо реализовать метод make_order(), принимающий экземпляр класса и количество ячеек в ряду. Данный метод позволяет организовать ячейки по рядам.
# Метод должен возвращать строку вида *****\n*****\n*****..., где количество ячеек между \n равно переданному аргументу.
# Если ячеек на формирование ряда не хватает, то в последний ряд записываются все оставшиеся.

class Cell():
    def __init__(self, number=1):
        # решаем проблему с отрицательным количеством ячеек :-)
        self.__number = abs(number)

    @property
    def number(self):
        return self.__number

    def __add__(self, other):
        return Cell(self.number + other.number)

    def __sub__(self, other):
        return Cell(self.number - other.number)

    def __mul__(self, other):
        return Cell(self.number * other.number)

    def __truediv__(self, other):
        try:
            return Cell(round(self.number / other.number))
        except ZeroDivisionError as zd:
            print(zd)
            return Cell()

    def make_order(self, cells_in_row):
        rows = self.__number // cells_in_row
        rem = self.__number % cells_in_row
        res = ('@ ' * cells_in_row + '\n') * rows + '@ ' * rem
        return res

a = Cell(20)
b = Cell(5)
c = a + b
print(c.number)
print(c.make_order(7))
print()

d = a - b
print(d.number)
print(d.make_order(8))
print()

e = a * b
print(e.number)
print(e.make_order(10))
print()

f = a / b
print(f.number)
print(f.make_order(7))
print()

g = Cell(10) / Cell(0)
print(g.make_order(10))


from __future__ import annotations

from typing import TYPE_CHECKING

from poetry.core.masonry.utils.include import Include

if TYPE_CHECKING:
    from pathlib import Path

class PackageInclude(Include):
    def __init__(
        self,
        base: Path,
        include: str,
        formats: list[str] | None = None,
        source: str | None = None,
    ) -> None:
        self._package: str
        self._is_package = False
        self._is_module = False
        self._source = source

        if source is not None:
            base = base / source

        super().__init__(base, include, formats=formats)
        self.check_elements()

    @property
    def package(self) -> str:
        return self._package

    @property
    def source(self) -> str | None:
        return self._source

    def is_package(self) -> bool:
        return self._is_package

    def is_module(self) -> bool:
        return self._is_module

    def refresh(self) -> PackageInclude:
        super().refresh()

        return self.check_elements()

    def is_stub_only(self) -> bool:
        # returns `True` if this a PEP 561 stub-only package,
        # see [PEP 561](https://www.python.org/dev/peps/pep-0561/#stub-only-packages)
        return (self.package or "").endswith("-stubs") and all(
            el.suffix == ".pyi" or el.name == "py.typed"
            for el in self.elements
            if el.is_file()
        )

    def has_modules(self) -> bool:
        # Packages no longer need an __init__.py in python3, but there must
        # at least be one .py file for it to be considered a package
        return any(element.suffix == ".py" for element in self.elements)

    def check_elements(self) -> PackageInclude:
        if not self._elements:
            raise ValueError(
                f"{self._base / self._include} does not contain any element"
            )

        root = self._elements[0]
        if len(self._elements) > 1:
            # Probably glob
            self._is_package = True
            self._package = root.parent.name

            if not (self.is_stub_only() or self.has_modules()):
                raise ValueError(f"{root.name} is not a package.")

        elif root.is_dir():
            # If it's a directory, we include everything inside it
            self._package = root.name
            self._elements: list[Path] = sorted(root.glob("**/*"))

            if not (self.is_stub_only() or self.has_modules()):
                raise ValueError(f"{root.name} is not a package.")

            self._is_package = True
        else:
            self._package = root.stem
            self._is_module = True

        return self


from gnuradio import gr, digital
from gnuradio import filter
from gnuradio import blocks
from gnuradio.fft import window
import sys
import numpy

try:
    from gnuradio import channels
except ImportError:
    print("Error: Program requires gr-channels.")
    sys.exit(1)

try:
    from matplotlib import pyplot
except ImportError:
    print("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).")
    sys.exit(1)

fftlen = 8192

def main():
    N = 10000
    fs = 2000.0
    Ts = 1.0 / fs
    t = numpy.arange(0, N * Ts, Ts)

    # When playing with the number of channels, be careful about the filter
    # specs and the channel map of the synthesizer set below.
    nchans = 10

    # Build the filter(s)
    bw = 1000
    tb = 400
    proto_taps = filter.firdes.low_pass_2(1, nchans * fs,
                                          bw, tb, 80,
                                          window.WIN_BLACKMAN_hARRIS)
    print("Filter length: ", len(proto_taps))

    # Create a modulated signal
    npwr = 0.01
    data = numpy.random.randint(0, 256, N)
    rrc_taps = filter.firdes.root_raised_cosine(1, 2, 1, 0.35, 41)

    src = blocks.vector_source_b(data.astype(numpy.uint8).tolist(), False)
    mod = digital.psk_mod(samples_per_symbol=2)
    chan = channels.channel_model(npwr)
    rrc = filter.fft_filter_ccc(1, rrc_taps)

    # Split it up into pieces
    channelizer = filter.pfb.channelizer_ccf(nchans, proto_taps, 2)

    # Put the pieces back together again
    syn_taps = [nchans * t for t in proto_taps]
    synthesizer = filter.pfb_synthesizer_ccf(nchans, syn_taps, True)
    src_snk = blocks.vector_sink_c()
    snk = blocks.vector_sink_c()

    # Remap the location of the channels
    # Can be done in synth or channelizer (watch out for rotattions in
    # the channelizer)
    synthesizer.set_channel_map([0, 1, 2, 3, 4,
                                 15, 16, 17, 18, 19])

    tb = gr.top_block()
    tb.connect(src, mod, chan, rrc, channelizer)
    tb.connect(rrc, src_snk)

    vsnk = []
    for i in range(nchans):
        tb.connect((channelizer, i), (synthesizer, i))

        vsnk.append(blocks.vector_sink_c())
        tb.connect((channelizer, i), vsnk[i])

    tb.connect(synthesizer, snk)
    tb.run()

    sin = numpy.array(src_snk.data()[1000:])
    sout = numpy.array(snk.data()[1000:])

    # Plot original signal
    fs_in = nchans * fs
    f1 = pyplot.figure(1, figsize=(16, 12), facecolor='w')
    s11 = f1.add_subplot(2, 2, 1)
    s11.psd(sin, NFFT=fftlen, Fs=fs_in)
    s11.set_title("PSD of Original Signal")
    s11.set_ylim([-200, -20])

    s12 = f1.add_subplot(2, 2, 2)
    s12.plot(sin.real[1000:1500], "o-b")
    s12.plot(sin.imag[1000:1500], "o-r")
    s12.set_title("Original Signal in Time")

    start = 1
    skip = 2
    s13 = f1.add_subplot(2, 2, 3)
    s13.plot(sin.real[start::skip], sin.imag[start::skip], "o")
    s13.set_title("Constellation")
    s13.set_xlim([-2, 2])
    s13.set_ylim([-2, 2])

    # Plot channels
    nrows = int(numpy.sqrt(nchans))
    ncols = int(numpy.ceil(float(nchans) / float(nrows)))

    f2 = pyplot.figure(2, figsize=(16, 12), facecolor='w')
    for n in range(nchans):
        s = f2.add_subplot(nrows, ncols, n + 1)
        s.psd(vsnk[n].data(), NFFT=fftlen, Fs=fs_in)
        s.set_title("Channel {0}".format(n))
        s.set_ylim([-200, -20])

    # Plot reconstructed signal
    fs_out = 2 * nchans * fs
    f3 = pyplot.figure(3, figsize=(16, 12), facecolor='w')
    s31 = f3.add_subplot(2, 2, 1)
    s31.psd(sout, NFFT=fftlen, Fs=fs_out)
    s31.set_title("PSD of Reconstructed Signal")
    s31.set_ylim([-200, -20])

    s32 = f3.add_subplot(2, 2, 2)
    s32.plot(sout.real[1000:1500], "o-b")
    s32.plot(sout.imag[1000:1500], "o-r")
    s32.set_title("Reconstructed Signal in Time")

    start = 0
    skip = 4
    s33 = f3.add_subplot(2, 2, 3)
    s33.plot(sout.real[start::skip], sout.imag[start::skip], "o")
    s33.set_title("Constellation")
    s33.set_xlim([-2, 2])
    s33.set_ylim([-2, 2])

    pyplot.show()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass


class Node:
    def __init__(self, val):
        self.val = val

    def say_hello(self):
        print("hello", self.val)

if __name__ == "__main__":
    arr = [1, 5, 2, 0, 23]
    arr.sort()
    print(arr)
    arr2 = [14, 2, 66, 23, 1]
    arr3 = sorted(arr2, reverse=True)
    print(arr2)
    print("descending", arr3)
    # custom sort
    # descending
    descending_list = sorted(arr2, key=lambda x: -x)
    # sort objects
    arr4 = [Node(2), Node(21), Node(12), Node(3), Node(45), Node(33)]
    sorted_node = sorted(arr4, key=lambda x: x.val) # Sort with key
    print("descending", descending_list)
    for x in sorted_node:
        x.say_hello()


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 2019

@author: Jiapeng Liu, Francesco Ciucci (francesco.ciucci@ust.hk)
"""

"""
Modified by Jake Huang on July 2 2020

Liu and Ciucci based the code on the relation tau = 1/freq. This should have been tau = 1/(2*pi*freq).
This error results in the estimated DRT being distorted, as the estimated DRT comes out as a function of tau/(2*pi) instead of tau.
Modifications made to fix this:
	-Assume that xi = ln(2*pi*freq), rather than xi = ln(freq)
	-In integrand_L2_im and integrand_der_ell_L2_im, change f = exp(xi) to f = exp(xi)/(2*pi)
	 and f_prime = exp(xi_prime) to f_prime = exp(xi_prime)/(2*pi) (lines 61-62, 76-77)
	-In matrix_L_im_K, change delta_xi = xi_vec[n]-xi_vec[0] + log(2*pi) to delta_xi = xi_vec[n]-xi_vec[0]
	 and delta_xi = xi_n_vec[n]-xi_m_vec[m] + log(2*pi) to delta_xi = xi_n_vec[n]-xi_m_vec[m] (lines 108, 112, 122)

Additional modifications:
	-Add 1e-5 to diagonal of L2_im_K to ensure Cholesky decomposition is stable as sigma_n approaches zero (lines 183, 207)
"""

######################################################################################
# This python file includes all necessary functions for GP-DRT model implemented in  #
# the paper "Liu, J., & Ciucci, F. (2019). The Gaussian process distribution of      #
# relaxation times: A machine learning tool for the analysis and prediction of       #
# electrochemical impedance spectroscopy data. Electrochimica Acta, 135316."         #
#                                                                                #
# If you find it is useful, please feel free to use it, modify it, and develop based #
# on this code. Please cite the paper if you utlize this code for academic useage.   #
######################################################################################

# imports
from math import exp
from math import pi
from math import log
from scipy import integrate
import numpy as np

print('reloaded GP_DRT')

# Define squared exponential kernel, $\sigma_f^2 \exp\left(-\frac{1}{2 \ell^2}\left(\xi-\xi^\prime\right)^2 \right)$
def kernel(xi, xi_prime, sigma_f, ell):
    return (sigma_f**2)*exp(-0.5/(ell**2)*((xi-xi_prime)**2))

# the function to be integrated in eq (65) of the main text, omitting the constant part and minus sign!!!
# $\frac{\displaystyle e^{\Delta\xi_{mn}-\chi}}{1+\left(\displaystyle e^{\Delta\xi_{mn}-\chi}\right)^2} \frac{k(\chi)}{\sigma_f^2}$
def integrand_L_im(x, delta_xi, sigma_f, ell):
    kernel_part = 0.0
    sqr_exp = exp(-0.5/(ell**2)*(x**2))
    a = delta_xi-x
    if a>0:
        kernel_part = exp(-a)/(1.+exp(-2*a))
    else:
        kernel_part = exp(a)/(1.+exp(2*a))
    return kernel_part*sqr_exp

# the function to be integrated in eq (76) of the main text, omitting the constant part
# $\frac{1}{2} \left(\chi+\Delta\xi_{mn}\right){\rm csch}\left(\chi+\Delta\xi_{mn}\right) \frac{k(\chi)}{\sigma_f^2}$
def integrand_L2_im(x, xi, xi_prime, sigma_f, ell):
    f = exp(xi)/(2*pi)
    f_prime = exp(xi_prime)/(2*pi)
    numerator = exp(x-0.5/(ell**2)*(x**2))*(x+xi_prime-xi)
    if x<0:
        numerator = exp(x-0.5/(ell**2)*(x**2))*(x+xi_prime-xi)
        denominator = (-1+((f_prime/f)**2)*exp(2*x))
    else:
        numerator = exp(-x-0.5/(ell**2)*(x**2))*(x+xi_prime-xi)
        denominator = (-exp(-2*x)+((f_prime/f)**2))
    return numerator/denominator

# the derivative of the integrand in eq (76) with respect to \ell
# $\frac{1}{2} \left(\chi+\Delta\xi_{mn}\right){\rm csch}\left(\chi+\Delta\xi_{mn}\right) \frac{k(\chi)}{\sigma_f^2}\chi^2$
# omitting the $\ell^3$ in the denominator
def integrand_der_ell_L2_im(x, xi, xi_prime, sigma_f, ell):
    f = exp(xi)/(2*pi)
    f_prime = exp(xi_prime)/(2*pi)
    if x<0:
        numerator = (x**2)*exp(x-0.5/(ell**2)*(x**2))*(x+xi_prime-xi)
        denominator = (-1+((f_prime/f)**2)*exp(2*x))
    else:
        numerator = (x**2)*exp(-x-0.5/(ell**2)*(x**2))*(x+xi_prime-xi)
        denominator = (-exp(-2*x)+((f_prime/f)**2))
    return numerator/denominator

# assemble the covariance matrix K as shown in eq (18a), which calculates the kernel distance between $\xi_n$ and $\xi_m$
def matrix_K(xi_n_vec, xi_m_vec, sigma_f, ell):
    N_n_freqs = xi_n_vec.size
    N_m_freqs = xi_m_vec.size
    K = np.zeros([N_n_freqs, N_m_freqs])

    for n in range(0, N_n_freqs):
        for m in range(0, N_m_freqs):
            K[n,m] = kernel(xi_n_vec[n], xi_m_vec[m], sigma_f, ell)
    return K

# assemble the matrix of eq (18b), added the term of $\frac{1}{\sigma_f^2}$ and factor $2\pi$ before $e^{\Delta\xi_{mn}-\chi}$
def matrix_L_im_K(xi_n_vec, xi_m_vec, sigma_f, ell):
    if np.array_equal(xi_n_vec, xi_m_vec):
        # considering the case that $\xi_n$ and $\xi_m$ are identical, i.e., the matrice are symmetry square
        xi_vec = xi_n_vec
        N_freqs = xi_vec.size
        L_im_K = np.zeros([N_freqs, N_freqs])

        for n in range(0, N_freqs):
            delta_xi = xi_vec[n]-xi_vec[0] #+ log(2*pi)
            integral, tol = integrate.quad(integrand_L_im, -np.inf, np.inf, epsabs=1E-12, epsrel=1E-12, args=(delta_xi, sigma_f, ell))
            np.fill_diagonal(L_im_K[n:, :], (sigma_f**2)*(integral))

            delta_xi = xi_vec[0]-xi_vec[n] #+ log(2*pi)
            integral, tol = integrate.quad(integrand_L_im, -np.inf, np.inf, epsabs=1E-12, epsrel=1E-12, args=(delta_xi, sigma_f, ell))
            np.fill_diagonal(L_im_K[:, n:], (sigma_f**2)*(integral))
    else:
        N_n_freqs = xi_n_vec.size
        N_m_freqs = xi_m_vec.size
        L_im_K = np.zeros([N_n_freqs, N_m_freqs])

        for n in range(0, N_n_freqs):
            for m in range(0, N_m_freqs):
                delta_xi = xi_n_vec[n]-xi_m_vec[m] #+ log(2*pi)
                integral, tol = integrate.quad(integrand_L_im, -np.inf, np.inf, epsabs=1E-12, epsrel=1E-12, args=(delta_xi, sigma_f, ell))
                L_im_K[n,m] =  (sigma_f**2)*(integral);
    return L_im_K

# assemble the matrix of eq (18d), added the term of $\frac{1}{\sigma_f^2}$ and factor $2\pi$ before $e^{\Delta\xi_{mn}-\chi}$
def matrix_L2_im_K(xi_n_vec, xi_m_vec, sigma_f, ell):
    if np.array_equal(xi_n_vec, xi_m_vec):
        # considering the case that $\xi_n$ and $\xi_m$ are identical, i.e., the matrice are symmetry square
        xi_vec = xi_n_vec
        N_freqs = xi_vec.size
        L2_im_K = np.zeros([N_freqs, N_freqs])

        for n in range(0, N_freqs):
            xi = xi_vec[n]
            xi_prime = xi_vec[0]
            integral, tol = integrate.quad(integrand_L2_im, -np.inf, np.inf, epsabs=1E-12, epsrel=1E-12, args=(xi, xi_prime, sigma_f, ell))

            np.fill_diagonal(L2_im_K[n:, :], exp(xi_prime-xi)*(sigma_f**2)*integral)
            np.fill_diagonal(L2_im_K[:, n:], exp(xi_prime-xi)*(sigma_f**2)*integral)
    else:
        N_n_freqs = xi_n_vec.size
        N_m_freqs = xi_m_vec.size
        L2_im_K = np.zeros([N_n_freqs, N_m_freqs])

        for n in range(0, N_n_freqs):
            xi = xi_n_vec[n]
            for m in range(0, N_m_freqs):
                xi_prime = xi_m_vec[m]
                integral, tol = integrate.quad(integrand_L2_im, -np.inf, np.inf, epsabs=1E-12, epsrel=1E-12, args=(xi, xi_prime, sigma_f, ell))
                L2_im_K[n,m] = exp(xi_prime-xi)*(sigma_f**2)*integral
    return L2_im_K

# assemble the matrix corresponding to the derivative of eq (18d) with respect to $\ell$, similar to the above implementation
def der_ell_matrix_L2_im_K(xi_vec, sigma_f, ell):
    N_freqs = xi_vec.size
    der_ell_L2_im_K = np.zeros([N_freqs, N_freqs])

    for n in range(0, N_freqs):
        xi = xi_vec[n]
        xi_prime = xi_vec[0]
        integral, tol = integrate.quad(integrand_der_ell_L2_im, -np.inf, np.inf, epsabs=1E-12, epsrel=1E-12, args=(xi, xi_prime, sigma_f, ell))

        np.fill_diagonal(der_ell_L2_im_K[n:, :], exp(xi_prime-xi)*(sigma_f**2)/(ell**3)*integral)
        np.fill_diagonal(der_ell_L2_im_K[:, n:], exp(xi_prime-xi)*(sigma_f**2)/(ell**3)*integral)
    return der_ell_L2_im_K

# calculate the negative marginal log-likelihood (NMLL) of eq (31)
def NMLL_fct(theta, Z_exp, xi_vec):
    # load the initial value for parameters needed to optimize
    sigma_n = theta[0] #+ 1e-8
    sigma_f = theta[1]
    ell = theta[2]
    # print(sigma_n,sigma_f,ell)
    N_freqs = xi_vec.size
    Sigma = (sigma_n**2)*np.eye(N_freqs)                    # $\sigma_n^2 \mathbf I$

    L2_im_K = matrix_L2_im_K(xi_vec, xi_vec, sigma_f, ell)  # $\mathcal L^2_{\rm im} \mathbf K$
    K_im_full = L2_im_K + Sigma                             # $\mathbf K_{\rm im}^{\rm full} = \mathcal L^2_{\rm im} \mathbf K + \sigma_n^2 \mathbf I$
    L = np.linalg.cholesky(K_im_full)                       # Cholesky decomposition to get the inverse of $\mathbf K_{\rm im}^{\rm full}$

    # solve for alpha
    alpha = np.linalg.solve(L, Z_exp.imag)
    alpha = np.linalg.solve(L.T, alpha)                     # $(\mathcal L^2_{\rm im} \mathbf K + \sigma_n^2 \mathbf I)^{-1} \mathbf Z^{\rm exp}_{\rm im}$

    # return the final result of $L(\bm \theta)$, i.e., eq (32). Note that $\frac{N}{2} \log 2\pi$
    # is not included as it is constant. The determinant of $\mathbf K_{\rm im}^{\rm full}$ is
    # easily calculated as the product of the diagonal element of L
    return 0.5*np.dot(Z_exp.imag,alpha) + np.sum(np.log(np.diag(L)))

# gradient of the negative marginal log-likelihhod (NMLL) $L(\bm \theta)$
def grad_NMLL_fct(theta, Z_exp, xi_vec):
    # load the initial value for parameters needed to optimize
    sigma_n = theta[0] #+ 1e-8
    sigma_f = theta[1]
    ell = theta[2]

    N_freqs = xi_vec.size
    Sigma = (sigma_n**2)*np.eye(N_freqs)                    # $\sigma_n^2 \mathbf I$

    L2_im_K = matrix_L2_im_K(xi_vec, xi_vec, sigma_f, ell)  # $\mathcal L^2_{\rm im} \mathbf K$
    K_im_full = L2_im_K + Sigma                             # $\mathbf K_{\rm im}^{\rm full} = \mathcal L^2_{\rm im} \mathbf K + \sigma_n^2 \mathbf I$
    L = np.linalg.cholesky(K_im_full)                       # Cholesky decomposition to get the inverse of $\mathbf K_{\rm im}^{\rm full}$

    # solve for alpha
    alpha = np.linalg.solve(L, Z_exp.imag)
    alpha = np.linalg.solve(L.T, alpha)

    # compute inverse of K_im_full
    inv_L = np.linalg.inv(L)
    inv_K_im_full = np.dot(inv_L.T, inv_L)

    # calculate the derivative of matrices with respect to parameters including $sigma_n$, $sigma_f$, and $\ell$
    der_mat_sigma_n = (2.*sigma_n)*np.eye(N_freqs)              # derivative of $\sigma_n^2 \mathbf I$ to $sigma_n$
    der_mat_sigma_f = (2./sigma_f)*L2_im_K                      # note that the derivative is 2*sigma_f*L2_im_K/(sigma_f**2)
    der_mat_ell = der_ell_matrix_L2_im_K(xi_vec, sigma_f, ell)  # derivative w.r.t $\ell$

    # calculate the derivative of $L(\bm \theta)$ w.r.t $sigma_n$, $sigma_f$, and $\ell$ according to eq (78)
    d_K_im_full_d_sigma_n = - 0.5*np.dot(alpha.T, np.dot(der_mat_sigma_n, alpha)) \
        + 0.5*np.trace(np.dot(inv_K_im_full, der_mat_sigma_n))

    d_K_im_full_d_sigma_f = - 0.5*np.dot(alpha.T, np.dot(der_mat_sigma_f, alpha)) \
        + 0.5*np.trace(np.dot(inv_K_im_full, der_mat_sigma_f))

    d_K_im_full_d_ell     = - 0.5*np.dot(alpha.T, np.dot(der_mat_ell, alpha)) \
        + 0.5*np.trace(np.dot(inv_K_im_full, der_mat_ell))

    grad = np.array([d_K_im_full_d_sigma_n, d_K_im_full_d_sigma_f, d_K_im_full_d_ell])
    return grad


#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import os
import subprocess

from rally.task import atomic

class OcpOnOspDynamicScenario():
    def install_ocp_cluster(self):
        """Installs openshift cluster on openstack"""

        ansible_log_file = "ocp_ansible_iter_{}.log".format(self.context["iteration"])
        cmd = ("ansible-playbook -vvv /home/stack/browbeat/ocp_on_osp/ocp_on_osp.yml &> "
               "/home/stack/ocp_ansible_logs/{}").format(ansible_log_file)

        aname = "ocp_on_osp"
        with atomic.ActionTimer(self, aname):
            proc = subprocess.run(cmd, shell=True)

            msg = "openshift cluster installation has failed"
            if proc.returncode != 0:
                self.assertTrue(False, err_msg=msg)

    def run_kube_burner_workload(self, workload, job_iterations, qps, burst, kubeconfig):
        """Run kube-burner workloads through e2e-benchmarking
        :param workload: str, kube-burner workload to run
        :param job_iterations: int, number of job iterations
        :param qps: int, queries per second
        :param burst: int, burst value to throttle
        :param kubeconfig: str, path to kubeconfig file
        """
        os.chdir(
            self.browbeat_dir + "/ansible/gather/e2e-benchmarking/workloads/kube-burner"
        )
        e2e_benchmarking_dir = os.getcwd()

        script_file_name = "run_" + workload + "_test_fromgit.sh"
        script_file_path = e2e_benchmarking_dir + "/" + script_file_name
        script_file = open(script_file_path, "r")

        updated_file_content = ""

        if workload == "poddensity":
            job_iters_param = "PODS"
        elif workload == "clusterdensity":
            job_iters_param = "JOB_ITERATIONS"
        elif workload == "maxnamespaces":
            job_iters_param = "NAMESPACE_COUNT"
        elif workload == "maxservices":
            job_iters_param = "SERVICE_COUNT"

        for line in script_file:
            if "/usr/bin/bash" in line:
                updated_file_content += line
                updated_file_content += "export KUBECONFIG=${KUBECONFIG:-"+kubeconfig+"}\n"
            elif "TEST_JOB_ITERATIONS" in line:
                first_part_of_line = line.split("TEST")[0]
                updated_file_content += (
                    first_part_of_line + "TEST_JOB_ITERATIONS=${" + job_iters_param +
                    ":-" + str(job_iterations) + "}\n"
                )
                updated_file_content += "export QPS=" + str(qps) + "\n"
                updated_file_content += "export BURST=" + str(burst) + "\n"
                updated_file_content += "export CLEANUP_WHEN_FINISH=true\n"
            elif ("export KUBECONFIG" not in line and "export QPS" not in line and
                  "export BURST" not in line and "export CLEANUP_WHEN_FINISH" not in line):
                updated_file_content += line

        with open(script_file_path, "w") as script_file_writer:
            script_file_writer.write(updated_file_content)

        subprocess.run("./" + script_file_name + " 2>&1 | tee -a log.txt && exit ${PIPESTATUS}",
                       shell=True, check=True, executable="/bin/bash")

        os.chdir(self.browbeat_dir)


class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        most = 0
        current = 0
        for i in nums:
            if i == 1:
                current += 1
            else:
                current = 0
            most = max(most, current)
        return most


# -*- coding: utf-8 -*-
from aap_election import app, db
from aap_election.cron import Cron
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand

manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

manager.add_command("runserver", Server(use_debugger=app.config['DEBUG'],
                                        use_reloader=app.config['RELOAD'],
                                        host=app.config['HOST'],
                                        port=int(app.config['PORT'])))
manager.add_command('cron', Cron)

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


__author__ = 'student'

class automat:
    def __init__(self, start,rule):
        """
        :param start: name of txt file with the 1-st condition of the field
        :param rule: name of txt file with the Wolfram code
        :return:
        """
        self.field = [None]
        with open(start) as f:
            line = f.readline().strip()
            self.n = len(line)
            self.field.extend([int(x) for x in line])
            self.field[0] = self.field[-1]
            self.field.append(self.field[1])
        self.print_field()
        n_wolfram = int(open(rule).readline().strip())
        line = bin(n_wolfram)[2:]
        line = line[::-1]
        if len(line) < 8:
            line = line + '0' * (8 - len(line))
        self.rules = [int(x) for x in line]
        # print('rules:', self.rules)

    def cell_calculate(self, left, current, right):
        return self.rules[int(str(left) + str(current) + str(right), base=2)]

    def calculate_field(self):
        new_field = [0] * (self.n + 2)
        for i in range(1, self.n + 1):
            new_field[i] = self.cell_calculate(self.field[i - 1], self.field[i], self.field[i + 1])
        new_field[-1] = new_field[1]
        new_field[0] = new_field[-2]

        self.field[:] = new_field
        # print('self:',self.field)
        # print('new: ', new_field)

    def print_field(self):
        for x in self.field[1:self.n + 1]:
            if x == 1:
                print('*', end='')
            else:
                print(' ', end='')
        print()

    def update(self):
        self.calculate_field()
        self.print_field()

def modelling():
    """ цикл моделирования клеточного автомата """
    field = automat('start_wolfram_code.txt', 'rules_wolfram_code.txt')
    for t in range(50):
        field.update()

if __name__ == '__main__':
    modelling()


import json
from os import abort, readlink
from difflib import get_close_matches
print("Welcome to the Dictionary World")

with open("data.json") as json_file:
    data=json.load(json_file)

turn_on=True

while turn_on:
    word=input("Enter the word to search:").lower()
    if word in data:
            print("....."+word+".....")
            for i,element in enumerate(data[word],1):
                print(i,element)

    else:
        word_check=str(get_close_matches(word,data.keys())[0])
        conditions=input("Did you mean:"+word_check+" yes or no:").lower()
        if conditions=="yes":
            if word_check in data:
                print("....."+word_check+".....")
                for i,element in enumerate(data[word_check],1):
                    print(i,element)
        else:
            print("Sorry the Word not found. Recheck the words.....!")


#Embedded file name: eve/client/script/ui/services\tutorialWindow.py
import math
from carbonui import const as uiconst, const
from carbonui.primitives.sprite import Sprite
from eve.client.script.ui.control.buttons import Button
from eve.client.script.ui.control.eveWindowUnderlay import WindowUnderlay, BlurredSceneUnderlay
from eve.client.script.ui.services.tutoriallib import TutorialColor, TutorialConstants, TutorialPageState
from eve.client.script.ui.shared.neocom.help import HelpWindow
from eve.common.lib import appConst as const, appConst
import localization
import uthread
import uicontrols
import service
import uiprimitives
import blue
import log
import util
import uicls
RESUME_TUTORIAL_HINT_DURATION_SEC = 60

class TutorialWindow(uicontrols.Window):
    __guid__ = 'form.TutorialWindow'
    default_windowID = 'aura9'
    default_width = 350
    default_height = 240
    defaultClipperHeight = 132
    default_iconNum = 'res:/UI/Texture/WindowIcons/tutorial.png'

    def ApplyAttributes(self, attributes):
        uicontrols.Window.ApplyAttributes(self, attributes)
        self.scope = 'all'
        self.sr.browser = uicontrols.Edit(parent=self.sr.main, padding=const.defaultPadding, readonly=1)
        self.sr.browser.HideBackground(True)
        self.sr.browser.AllowResizeUpdates(0)
        self.sr.browser.sr.window = self
        m = uicls.UtilMenu(menuAlign=uiconst.TOPRIGHT, parent=self.sr.topParent, align=uiconst.TOPRIGHT, left=const.defaultPadding, top=18, GetUtilMenu=self.SettingMenu, texturePath='res:/UI/Texture/Icons/73_16_50.png')
        self.nextFunc = attributes.nextFunc
        self.backFunc = attributes.backFunc
        self.onStartScalingWidth = None
        self.onStartScalingHeight = None
        self.constrainScreen = True
        if self.sr.stack is not None:
            self.sr.stack.RemoveWnd(self, 0, 0)
        if sm.GetService('tutorial').IsTutorialWindowUnkillable():
            self.MakeUnKillable()
            repairSysSkill = sm.GetService('skills').HasSkill(const.typeRepairSystems)
            shieldOpsSkill = sm.GetService('skills').HasSkill(const.typeShieldOperations)
            if repairSysSkill or shieldOpsSkill:
                self.MakeKillable()
        Sprite(parent=self.sr.topParent, name='mainicon', pos=(0, 2, 64, 64), texturePath='res:/UI/Texture/Icons/74_64_13.png')
        self.HideHeader()
        self.MakeUnstackable()
        self.SetMinSize([350, 220])
        self.imgpar = uiprimitives.Container(name='imgpar', parent=self.sr.main, align=uiconst.TOLEFT, width=64, idx=4, state=uiconst.UI_HIDDEN, clipChildren=1)
        imgparclipper = uiprimitives.Container(name='imgparclipper', parent=self.imgpar, align=uiconst.TOALL, left=5, top=5, width=5, height=5, clipChildren=1)
        self.img = uiprimitives.Sprite(parent=imgparclipper, align=uiconst.RELATIVE, left=1, top=1)
        self.bottomCont = uiprimitives.Container(name='bottom', parent=self.sr.maincontainer, align=uiconst.TOBOTTOM, height=32, idx=0)
        self.backBtn = Button(parent=self.bottomCont, label=localization.GetByLabel('UI/Commands/Back'), name='tutorialBackBtn', func=self.backFunc, align=uiconst.TOLEFT, padding=(8, 0, 0, 6))
        self.nextBtn = Button(parent=self.bottomCont, label=localization.GetByLabel('UI/Commands/Next'), name='tutorialNextBtn', func=self.nextFunc, align=uiconst.TORIGHT, padding=(0, 0, 8, 6), btn_default=1)
        self.Confirm = self.nextFunc
        self.sr.text = uicontrols.EveLabelMedium(text='', parent=self.bottomCont, state=uiconst.UI_DISABLED, align=uiconst.CENTER)
        top = self.tTop = uiprimitives.Container(name='tTop', parent=self.sr.topParent, align=uiconst.TOALL, padding=(64, 0, 24, 0), idx=0)
        self.captionText = uicontrols.EveLabelLarge(text='', parent=top, align=uiconst.TOTOP, top=10, state=uiconst.UI_DISABLED)
        self.captionText.OnSizeChanged = self.CheckTopHeight
        self.subcaption = uicontrols.Label(text='', parent=top, align=uiconst.TOTOP, state=uiconst.UI_DISABLED, fontsize=18, color=TutorialColor.HINT_FRAME)
        self.sr.browser.AllowResizeUpdates(1)
        self.SetParent(uicore.layer.abovemain)
        uicore.animations.SpSwoopBlink(self.blinkFill, rotation=math.pi - 0.5, duration=3.0, loops=TutorialConstants.NUM_BLINKS)
        uicore.animations.SpSwoopBlink(self.blinkBorder, rotation=math.pi - 0.5, duration=3.0, loops=TutorialConstants.NUM_BLINKS)

    def Prepare_Background_(self):
        self.sr.underlay = WindowUnderlay(parent=self, name='underlay', state=uiconst.UI_DISABLED)
        self.blinkFill = uiprimitives.Sprite(bgParent=self.sr.underlay, name='blinkFill', texturePath='res:/UI/Texture/classes/Tutorial/fill_no_border.png', state=uiconst.UI_DISABLED, color=(1, 1, 1, 0.5))
        self.blinkBorder = uiprimitives.Sprite(bgParent=self.sr.underlay, name='blinkBorder', texturePath='res:/UI/Texture/classes/Tutorial/border.png', state=uiconst.UI_DISABLED, color=TutorialColor.HINT_FRAME)
        uicontrols.Frame(name='frame', bgParent=self.sr.underlay, color=TutorialColor.WINDOW_FRAME, frameConst=uiconst.FRAME_BORDER1_CORNER0)
        BlurredSceneUnderlay(bgParent=self.sr.underlay)

    def RegisterPositionAndSize(self, key = None, windowID = None):
        uicontrols.Window.RegisterPositionAndSize(self, key, windowID)
        self.currentBottom = self.top + self.height

    def SettingMenu(self, menuParent):
        shouldAutoReszie = settings.char.windows.Get('tutorialShouldAutoReszie', 1)
        menuParent.AddCheckBox(text=localization.GetByLabel('UI/Tutorial/AutoResizeTutorialWindow'), checked=shouldAutoReszie, callback=(self.ChangeAutoResize, not shouldAutoReszie))
        menuParent.AddDivider()
        menuParent.AddIconEntry(icon='res:/UI/Texture/Icons/38_16_190.png', text=localization.GetByLabel('UI/Tutorial/OpenTutorialsMenu'), callback=self.OpenTutorialList)

    def OpenTutorialList(self):
        wnd = HelpWindow.GetIfOpen()
        if wnd:
            wnd.Maximize()
            wnd.sr.mainTabs.ShowPanelByName(localization.GetByLabel('UI/Help/Tutorials'))
        else:
            wnd = HelpWindow.Open(showPanel=localization.GetByLabel('UI/Help/Tutorials'))

    def ChangeAutoResize(self, shouldAutoReszie):
        settings.char.windows.Set('tutorialShouldAutoReszie', shouldAutoReszie)
        self.CheckHeight()

    def ToggleMinimize(self):
        """
        The method is overridden for the tutorial window since it lives in a different layer and can't stack
        If window is minimized, maximize it
        If window is not minimized and in front, minimize it
        """
        if not self.IsMinimizable():
            return
        if self.IsMinimized():
            self.Maximize()
        else:
            self.Minimize()

    @staticmethod
    def default_top(*args):
        return uicore.desktop.height - 270

    @staticmethod
    def default_left(*args):
        leftpush, rightpush = uicontrols.Window.GetSideOffset()
        return uicore.desktop.width - 360 - rightpush

    def _OnClose(self, *args):
        uthread.new(sm.GetService('tutorial').Cleanup)

    def OnStartScale_(self, wnd, *args):
        self.onStartScalingWidth = self.width
        self.onStartScalingHeight = self.height

    def OnEndScale_(self, wnd, *args):
        uicontrols.Window.OnEndScale_(self, wnd, *args)
        if abs(self.onStartScalingHeight - self.height) > 5 or abs(self.onStartScalingWidth - self.width) > 5:
            settings.char.windows.Set('tutorialShouldAutoReszie', 0)

    def CloseByUser(self, *args):
        tutorialSvc = sm.GetService('tutorial')
        tut = tutorialSvc.GetCurrentTutorial()
        if tut is not None:
            if hasattr(self, 'startTime'):
                totaltime = (blue.os.GetWallclockTime() - self.startTime) / const.SEC
            else:
                totaltime = 0
            timeSpentInPage = (blue.os.GetWallclockTime() - tutorialSvc.pageTime) / const.SEC
            try:
                numClicks = uicore.uilib.GetGlobalClickCount() - tutorialSvc.numMouseClicks
                numKeys = uicore.uilib.GetGlobalKeyDownCount() - tutorialSvc.numKeyboardClicks
            except:
                numClicks = numKeys = 0

            if not getattr(self, 'done', 0):
                tutorialSvc.SetSequenceStatus(tut.sequenceID, tut.tutorialID, tut.pageNo, 'aborted')
                with util.ExceptionEater('eventLog'):
                    tutorialSvc.LogTutorialEvent(['tutorialID',
                     'pageNo',
                     'sequenceID',
                     'timeInTutorial',
                     'numMouseClicks',
                     'numKeyboardClicks',
                     'reason',
                     'timeInPage'], 'Closed', tut.tutorialID, tut.pageNo, tut.sequenceID, totaltime, numClicks, numKeys, 'aborted', timeSpentInPage)
            else:
                tutorialSvc.SetSequenceStatus(tut.sequenceID, tut.tutorialID, tut.pageNo, 'done')
                with util.ExceptionEater('eventLog'):
                    tutorialSvc.LogTutorialEvent(['tutorialID',
                     'pageNo',
                     'sequenceID',
                     'timeInTutorial',
                     'numMouseClicks',
                     'numKeyboardClicks',
                     'reason',
                     'timeInPage'], 'Closed', tut.tutorialID, tut.pageNo, tut.sequenceID, totaltime, numClicks, numKeys, 'done', timeSpentInPage)
        tutorialSvc.Cleanup()
        if settings.char.windows.Get('tutorialShouldAutoReszie', 1):
            self.display = False
            cw, currentClipperHeight = self.sr.browser.sr.clipper.GetAbsoluteSize()
            self.ChangeWindowHeight(currentClipperHeight, self.defaultClipperHeight)
            self.RegisterPositionAndSize()
        self.Close()
        if getattr(self, 'showTutorialReminder', True):
            uthread.new(self._TutorialReminder)

    def _TutorialReminder(self):
        blue.pyos.synchro.SleepWallclock(1000)
        tutorialSvc = sm.GetService('tutorial')
        tutorialSvc.uipointerSvc.PointTo('neocom.tutorial', localization.GetByLabel('UI/Tutorial/ResumeTutorialPointer'))
        blue.pyos.synchro.SleepWallclock(RESUME_TUTORIAL_HINT_DURATION_SEC * 1000)
        browser = tutorialSvc.GetTutorialBrowser(create=False)
        if browser is None:
            tutorialSvc.uipointerSvc.ClearPointers()

    def CheckTopHeight(self):
        h = 0
        for each in self.tTop.children:
            if each.state != uiconst.UI_HIDDEN:
                h += each.height + each.top

        self.SetTopparentHeight(max(74, h))

    def CheckHeight(self, *args):
        browser = self.sr.browser
        shouldAutoReszie = settings.char.windows.Get('tutorialShouldAutoReszie', 1)
        if shouldAutoReszie:
            cw, currentClipperHeight = browser.sr.clipper.GetCurrentAbsoluteSize()
            if not currentClipperHeight:
                cw, currentClipperHeight = browser.sr.clipper.GetAbsoluteSize()
            contentHeight = browser.GetContentHeight()
            self.ChangeWindowHeight(currentClipperHeight, contentHeight + 10)
            browser.scrollEnabled = 1
        else:
            browser.scrollEnabled = 1
            uthread.new(self.ShowScrollControlIfNeeded)

    def ChangeWindowHeight(self, currentClipperHeight, contentHeight):
        if self.defaultClipperHeight is None:
            return
        if self.defaultClipperHeight > contentHeight and self.defaultClipperHeight <= currentClipperHeight:
            diff = currentClipperHeight - self.defaultClipperHeight
            uicore.animations.MorphScalar(self, 'height', startVal=self.height, endVal=self.height - diff, duration=0.2, loops=1, curveType=2, callback=None, sleep=False)
            uicore.animations.MorphScalar(self, 'top', startVal=self.top, endVal=max(self.top + diff, 0), duration=0.2, loops=1, curveType=2, callback=None, sleep=True)
        else:
            diff = currentClipperHeight - max(contentHeight, self.defaultClipperHeight)
            uicore.animations.MorphScalar(self, 'height', startVal=self.height, endVal=self.height - diff, duration=0.2, loops=1, curveType=2, callback=None, sleep=False)
            uicore.animations.MorphScalar(self, 'top', startVal=self.top, endVal=max(self.top + diff, 0), duration=0.2, loops=1, curveType=2, callback=None, sleep=True)

    def ShowScrollControlIfNeeded(self, *args):
        if self.sr.browser.scrollingRange:
            self.sr.browser.sr.scrollcontrols.state = uiconst.UI_NORMAL

    def LoadImage(self, imagePath):
        if not blue.ResFile().Open(imagePath):
            log.LogError('Image not found in res:', imagePath)
            return
        texture, tWidth, tHeight, bw, bh = sm.GetService('photo').GetTextureFromURL(imagePath, sizeonly=1, dontcache=1)
        self.img.state = uiconst.UI_NORMAL
        self.img.SetTexturePath(imagePath)
        self.img.width = tWidth
        self.img.height = tHeight
        self.imgpar.width = min(128, tWidth) + self.img.left + 5
        if self.imgpar.state != uiconst.UI_DISABLED:
            self.imgpar.state = uiconst.UI_DISABLED

    def LoadAndGiveGoodies(self, goodies, tutorialID, pageID, pageNo):
        goodieHtml = ''
        if len(goodies) != 0:
            if goodies[0] == -1:
                goodieHtml += '\n
\n                        %s\n

\n                ' % localization.GetByLabel('UI/Tutorial/TutorialGoodie/AlreadyReceived')
                return goodieHtml
            for goodie in goodies:
                invtype = cfg.invtypes.Get(goodie.invTypeID)
                goodieHtml += '\n
\n
\n                        \n                        %s\n                        \n

\n
\n                    ' % (goodie.invTypeID,
                 invtype.typeName,
                 goodie.invTypeID,
                 localization.GetByLabel('UI/Commands/ShowInfo'))

            sm.GetService('tutorial').GiveGoodies(tutorialID, pageID, pageNo)
            return goodieHtml

    def LoadTutorial(self, tutorialID = None, pageNo = None, pageID = None, sequenceID = None, force = 0, VID = None, skipCriteria = False, checkBack = 0, diffMouseClicks = 0, diffKeyboardClicks = 0):
        self.sr.browser.scrollEnabled = 0
        self.backBtn.state = uiconst.UI_HIDDEN
        self.nextBtn.state = uiconst.UI_HIDDEN
        self.backBtn.Blink(0)
        self.nextBtn.Blink(0)
        self.sr.text.text = ''
        self.done = 0
        self.reverseBack = 0
        imagePath = None
        pageCount = None
        body = '\n            \n            \n            <LINK REL="stylesheet" TYPE="text/css" HREF="res:/ui/css/tutorial.css">\n            \n            '
        tutData = None
        if VID:
            tutData = sm.RemoteSvc('tutorialSvc').GetTutorialInfo(VID)
        elif tutorialID:
            tutData = sm.GetService('tutorial').GetTutorialInfo(tutorialID)
        if tutData:
            fadeOut = uicore.animations.FadeOut(self.sr.browser.sr.clipper, duration=0.05, loops=1, curveType=2, callback=None, sleep=False)
            if self and self.destroyed:
                return
            pageCount = len(tutData.pages)
            if pageNo == -1:
                pageNo = pageCount
            else:
                pageNo = pageNo or 1
            if pageNo > pageCount:
                log.LogWarn('Open Tutorial Page Failed:, have page %s but max %s pages. falling back to page 1 :: tutorialID: %s, sequenceID: %s, VID: %s' % (pageNo,
                 pageCount,
                 tutorialID,
                 sequenceID,
                 VID))
                pageNo = 1
            with util.ExceptionEater('eventLog'):
                sm.GetService('tutorial').LogTutorialEvent(['tutorialID', 'pageNo', 'openedByUser'], 'OpenTutorial', tutorialID, pageNo, force)
            dispPageNo, dispPageCount = pageNo, pageCount
            pageData = tutData.pages[pageNo - 1]
            caption = self.captionText
            loop = 1
            while 1:
                captionTextParts = localization.GetByMessageID(tutData.tutorial[0].tutorialNameID).split(':')
                if len(captionTextParts) > 1:
                    tutorialNumber = captionTextParts[0]
                    rest = ':'.join(captionTextParts[1:]).strip()
                    captionText = '%s: %s' % (tutorialNumber, rest)
                else:
                    captionText = localization.GetByMessageID(tutData.tutorial[0].tutorialNameID)
                caption.text = captionText
                if pageData and pageData.pageNameID:
                    self.subcaption.text = localization.GetByMessageID(pageData.pageNameID)
                    self.subcaption.state = uiconst.UI_DISABLED
                else:
                    self.subcaption.state = uiconst.UI_HIDDEN
                if caption.textheight < 52 or not loop:
                    break
                caption.fontsize = 13
                caption.letterspace = 0
                caption.last = (0, 0)
                loop = 0

            if sequenceID:
                check = []
                seqTutData = sm.GetService('tutorial').GetTutorialInfo(tutorialID)
                for criteria in seqTutData.criterias:
                    cd = sm.GetService('tutorial').GetCriteria(criteria.criteriaID)
                    if cd is None:
                        continue
                    check.append(criteria)

                closeToEnd = 0
                for criteria in seqTutData.pagecriterias:
                    if criteria.pageID == pageData.pageID:
                        check.append(criteria)
                        closeToEnd = 1
                    elif not closeToEnd:
                        cd = sm.GetService('tutorial').GetCriteria(criteria.criteriaID)
                        if cd is None:
                            continue
                        if not cd.criteriaName.startswith('rookieState'):
                            continue
                        check.append(criteria)

                actionData = seqTutData.actions
                pageActionData = seqTutData.pageactions
            else:
                check = [ c for c in tutData.criterias ]
                for criteria in tutData.pagecriterias:
                    if criteria.pageID == pageData.pageID:
                        check.append(criteria)

                actionData = tutData.actions
                pageActionData = tutData.pageactions
            actions = [ sm.GetService('tutorial').GetAction(action.actionID) for action in actionData ]
            actions += [ sm.GetService('tutorial').GetAction(action.actionID) for action in pageActionData if action.pageID == pageData.pageID ]
            preRookieState = eve.rookieState
            if skipCriteria:
                criteriaCheck = None
            else:
                criteriaCheck = sm.GetService('tutorial').ParseCriterias(check, 'tut', self, tutorialID)
            if not self or getattr(self, 'sr', None) is None:
                return
            if criteriaCheck:
                if preRookieState:
                    eve.SetRookieState(preRookieState)
                body += '
' + localization.GetByMessageID(criteriaCheck.messageTextID)
                with util.ExceptionEater('eventLog'):
                    sm.GetService('tutorial').LogTutorialEvent(['tutorialID',
                     'pageNo',
                     'sequenceID',
                     'clickedByUser',
                     'errorMessageID',
                     'numMouseClicks',
                     'numKeyboardClicks'], 'CriteriaNotMet', tutorialID, pageNo, sequenceID, force, criteriaCheck.messageTextID, diffMouseClicks, diffKeyboardClicks)
                if pageNo > 1 or sequenceID and sm.GetService('tutorial').GetNextInSequence(tutorialID, sequenceID, -1):
                    self.backBtn.state = uiconst.UI_NORMAL
                if sm.GetService('tutorial').waitingForWarpConfirm == False:
                    self.nextBtn.state = uiconst.UI_NORMAL
                    self.nextBtn.OnClick = sm.GetService('tutorial').Reload
                    self.Confirm = sm.GetService('tutorial').Reload
                    self.nextBtn.SetLabel(localization.GetByLabel('UI/Commands/Next'))
                    self.sr.text.text = ''
                self.backBtn.OnClick = self.backFunc
                if checkBack:
                    self.reverseBack = 1
            else:
                sm.GetService('tutorial').ParseActions(actions)
                self.sr.text.text = localization.GetByLabel('UI/Tutorial/PageOf', num=dispPageNo, total=dispPageCount)
                if pageNo > 1 or sequenceID and sm.GetService('tutorial').GetNextInSequence(tutorialID, sequenceID, -1):
                    self.backBtn.state = uiconst.UI_NORMAL
                sm.GetService('tutorial').SetCriterias(check)
                if pageData:
                    page = pageData
                    body += '%s' % localization.GetByMessageID(page.textID)
                    self.nextBtn.state = uiconst.UI_NORMAL
                    self.nextBtn.OnClick = self.nextFunc
                    self.Confirm = self.nextFunc
                    self.backBtn.OnClick = self.backFunc
                    if pageNo < pageCount or sequenceID and sm.GetService('tutorial').GetNextInSequence(tutorialID, sequenceID):
                        self.nextBtn.SetLabel(localization.GetByLabel('UI/Commands/Next'))
                    else:
                        self.nextBtn.SetLabel(localization.GetByLabel('UI/Commands/Done'))
                        self.done = 1
                    imagePath = page.imagePath
                else:
                    body += '\n                        Page %s was not found in this tutorial.\n                        ' % pageNo
        else:
            self.captionText.text = localization.GetByLabel('UI/Tutorial/EveTutorials')
            body = '%s %s' % (localization.GetByLabel('UI/Tutorial/UnknownTutorial'), tutorialID)
        body += ''
        blue.pyos.synchro.Yield()
        self.CheckTopHeight()
        self.LoadHTML('', newThread=0)
        if self.state == uiconst.UI_HIDDEN:
            self.Maximize()
        if imagePath:
            self.LoadImage(imagePath)
            self.sr.browser.left = self.img.width
        else:
            if self.imgpar.state != uiconst.UI_HIDDEN:
                self.imgpar.state = uiconst.UI_HIDDEN
            self.sr.browser.left = const.defaultPadding
        blue.pyos.synchro.Yield()
        goodies = sm.RemoteSvc('tutorialLocationSvc').GetTutorialGoodies(tutorialID, pageID, pageNo)
        goodieHtml = self.LoadAndGiveGoodies(goodies, tutorialID, pageID, pageNo)
        if goodieHtml:
            body += '
%s' % goodieHtml
        self.LoadHTML(body, newThread=0)
        self.SetCaption(localization.GetByLabel('UI/Tutorial/EveTutorials'))
        if not hasattr(self, 'startTime') or not hasattr(self, 'current') or self.current.sequenceID != sequenceID:
            self.startTime = blue.os.GetWallclockTime()
        tutorialPageState = TutorialPageState(tutorialID, pageNo, pageID, pageCount, sequenceID, VID, pageData.pageActionID)
        settings.char.generic.Set('tutorialPageState', tuple(tutorialPageState))
        settings.char.generic.Delete('tutorialCompleted')
        self.current = tutorialPageState
        if sequenceID:
            if self.done:
                sm.GetService('tutorial').SetSequenceStatus(sequenceID, tutorialID, pageNo, 'done')
            else:
                sm.GetService('tutorial').SetSequenceStatus(sequenceID, tutorialID, pageNo)
            if not sm.GetService('tutorial').CheckTutorialDone(sequenceID, tutorialID):
                sm.GetService('tutorial').SetSequenceDoneStatus(sequenceID, tutorialID, pageNo)
        for page in tutData.pages:
            if page.pageID == pageID or page.pageNumber == pageNo:
                if not criteriaCheck:
                    translatedText = localization.GetByMessageID(page.uiPointerTextID)
                    sm.GetService('uipointerSvc').PointTo(page.uiPointerID, translatedText)
                    break

        fadeOut.Stop()
        uicore.animations.FadeIn(self.sr.browser.sr.clipper, endVal=1.0, duration=0.3, loops=1, curveType=2, callback=None, sleep=False)
        self.CheckHeight()

    def LoadHTML(self, html, newThread = 1):
        self.ShowLoad()
        self.sr.browser.LoadHTML(html, newThread=newThread)

    def LoadEnd(self):
        self.HideLoad()

    def Reload(self, forced = 1, *args):
        if not self.sr.browser:
            return
        uthread.new(self.sr.browser.LoadHTML, None, scrollTo=self.sr.browser.GetScrollProportion())


# coding: utf-8

# In[1]:

""" Topic Modelling using LDA - The following packages have been used to show basic steps to apply LDA for topic modelling:
(1) nltk
(2) stop_words
(3) gensim """

from nltk.tokenize import RegexpTokenizer
from nltk.stem.porter import PorterStemmer
from stop_words import get_stop_words
from gensim import corpora, models
import gensim

# In[2]:

""" Text Prerpocessing
Tokenization - converting documents into its atomic elements
Stopping - removing meaningless words
Stemming - merging words that are equivalent in meaning """

# In[4]:

""" Here RegexpTokenizer has been used to tokenize documents using regular expressions """
tokenizer = RegexpTokenizer(r'\w+')

# In[5]:

""" Here English stop words list has been created using get_stop_words from stop_words """
en_stop = get_stop_words('en')

# In[6]:

""" Here Porter Algorithm for stemming has been used from nltk """
p_stemmer = PorterStemmer()

# In[7]:

""" The following sample documents have been created for testing """

doc_a = "Brocolli is good to eat. My brother likes to eat good brocolli, but not my mother."

doc_b = "My mother spends a lot of time driving my brother around to baseball practice."

doc_c = "Some health experts suggest that driving may cause increased tension and blood pressure."

doc_d = "I often feel pressure to perform well at school, but my mother never seems to drive my brother to do better."

doc_e = "Health professionals say that brocolli is good for your health."

# In[8]:

""" Compile sample documents into a list """
doc_set = [doc_a, doc_b, doc_c, doc_d, doc_e]
print (doc_set)

# In[9]:

""" Initialise a list for tokenized documents in loop """

texts = []

# In[10]:

#loop through document list
for i in doc_set:

    #clean and tokenize document string
    raw = i.lower()
    tokens = tokenizer.tokenize(raw)

    #remove stop words from tokens
    stopped_tokens = [i for i in tokens if not i in en_stop]

    #stem tokens
    stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens]

    #add tokens to list
    texts.append(stemmed_tokens)

# In[11]:

# print the resultant after tokenization, stop words removal and stemming

print(texts)

# In[16]:

""" Constructing a document-term matrix to understand how frequently each term occurs within each document.
First, we need to turn our tokenized documents into an id and  term dictionary suing Dictionary() function."""

dictionary = corpora.Dictionary(texts)

""" Check each tokens unique integer id """

print(dictionary.token2id)

# In[20]:

""" Now we convert tokenized documents into a document-term matrix. The function doc2bow coverts dictionary into bag of words
where the result ie corpus is a list of vectors equal to the number of documents and each document vector is a series of tuples
and the tuples are (term id , term frequency) pairs """

corpus = [dictionary.doc2bow(text) for text in texts]

print(corpus[0])

# In[23]:

""" Generate LDA model with num_topics as how mnay topics should be generated, id2word as mappings b/w id and strings
and passes (optional) as the number of lapse the model will take through corpus """

ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics = 2, id2word = dictionary, passes=20)

# In[60]:

""" Print the resultant which includes 3 topics generated by LDA"""

print(ldamodel.print_topics(num_topics=2, num_words=4))

# In[ ]:

# In[ ]:


# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 14:24:02 2021

@author: Jireh Jam
"""

from configparser import ConfigParser
class MainConfig:

  def __init__(self, file_path):
    inpaint_config = ConfigParser()
    seen = inpaint_config.read(file_path)
    if not seen:
        raise ValueError('No config file found!')
    print(inpaint_config.sections())
    self.testing = TestingConfig(inpaint_config['TESTING'])
    self.training = TrainingConfig(inpaint_config['TRAINING'])

class TestingConfig:

  def __init__(self, test_section):
    self.batch_size = int(test_section['BATCH_SIZE'])
    self.img_height = int(test_section['IMG_HEIGHT'])
    self.img_width = int(test_section['IMG_WIDTH'])
    self.channels = int(test_section['CHANNELS'])
    self.mask_channels = int(test_section['MASK_CHANNELS'])
    self.imgs_in_batch = int(test_section['IMGS_IN_BATCH'])
    self.last_img_on =  int(test_section['LAST_IMG_ON'])
    self.num_epochs = int(test_section['NUM_EPOCHS'])
    self.g_learning_rate = float(test_section['GEN_LEARNING_RATE'])
    self.d_learning_rate = float(test_section['DISC_LEARNING_RATE'])
    self.gf = int(test_section['GEN_FILTER'])
    self.df = int(test_section['DISC_FILTER'])
    self.current_epoch = int(test_section['CURRNT_EPOCH'])
    self.sample_interval = int(test_section['SAMPLE_INTERVAL'])
    self.beta_1 = float(test_section['BETA_1'])
    self.beta_2 = float(test_section['BETA_2'])
    self.epsilon = float(test_section['EPSILON'])
    self.last_trained_epoch = int(test_section['LAST_TRAINED_EPOCH'])

class TrainingConfig:

  def __init__(self, training_section):
    self.batch_size = int(training_section['BATCH_SIZE'])
    self.img_height = int(training_section['IMG_HEIGHT'])
    self.img_width = int(training_section['IMG_WIDTH'])
    self.channels = int(training_section['NUM_CHANNELS'])
    self.mask_channels = int(training_section['MASK_CHANNELS'])
    self.num_epochs = int(training_section['NUM_EPOCHS'])
    self.g_learning_rate = float(training_section['GEN_LEARNING_RATE'])
    self.d_learning_rate = float(training_section['DISC_LEARNING_RATE'])
    self.gf = int(training_section['GEN_FILTER'])
    self.df = int(training_section['DISC_FILTER'])
    self.current_epoch = int(training_section['CURRNT_EPOCH'])
    self.sample_interval = int(training_section['SAMPLE_INTERVAL'])
    self.beta_1 = float(training_section['BETA_1'])
    self.beta_2 = float(training_section['BETA_2'])
    self.epsilon = float(training_section['EPSILON'])
    self.last_trained_epoch = int(training_section['LAST_TRAINED_EPOCH'])


def first_non_dup(s):
    count = 0
    result = ""
    for i in range(1,len(s)):
        #count the equal or duplicate
        if s[i-1] == s[i]:
            count += 1
        else:
            #if count is 0 the return
            if count == 0:
                return s[i-1]
            #reset the count for other letter
            count = 0
        # check the last char of S
        if i == len(s)-1:
            if count == 0:
                return s[i]
     # return no if all is dup
    return None

s = "aaabbbcccdde"
print(first_non_dup(s))


#!./env/bin/python3
from flask import render_template, Flask, jsonify, make_response
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from app.api import request_api
from app.config import flask_env

if flask_env == 'production':
    config = 'config.production'
else:
    config = 'config.development'

app = Flask(__name__)
app.config.from_object(config)

### swagger specific ###
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
    SWAGGER_URL,
    API_URL,
    config={
        'app_name': "Seans-Python-Flask-REST-Boilerplate"
    }
)

app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
### end swagger specific ###

app.register_blueprint(request_api.get_blueprint())

# Create a URL route in our application for "/"
@app.route('/')
def home():
    """
    This function just responds to the browser ULR
    localhost:5000/
    :return:        the rendered template 'home.html'
    """
    return render_template('index.html')

if __name__ == '__main__':
    CORS = CORS(app)
    app.run(host='0.0.0.0', port='5000')