"""
Defines an endpoint for gradebook data related to a course.
"""
import copy
import logging
import json
from collections import namedtuple
from contextlib import contextmanager

from django.conf import settings
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.views.decorators.http import require_POST
from rest_framework import status
from rest_framework.response import Response
from six import text_type
from util.date_utils import to_timestamp

from courseware.courses import get_course_by_id
from lms.djangoapps.grades.api.v1.utils import (
    USER_MODEL,
    GradeViewMixin,
    PaginatedAPIView,
    verify_course_exists
)
from lms.djangoapps.grades.constants import ScoreDatabaseTableEnum
from lms.djangoapps.grades.course_data import CourseData
from lms.djangoapps.grades.course_grade_factory import CourseGradeFactory
from lms.djangoapps.grades.events import SUBSECTION_GRADE_CALCULATED, subsection_grade_calculated
from lms.djangoapps.grades.models import (
    PersistentCourseGrade,
    PersistentSubsectionGrade,
    PersistentSubsectionGradeOverride,
    PersistentSubsectionGradeOverrideHistory,
)
from lms.djangoapps.grades.services import GradesService
from lms.djangoapps.grades.signals.signals import GRADE_EDITED
from lms.djangoapps.grades.subsection_grade import CreateSubsectionGrade
from lms.djangoapps.grades.tasks import (
    recalculate_subsection_grade_v3,
    send_grade_override_email,
    update_course_progress
)
from lms.djangoapps.instructor.enrollment import get_user_email_language
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey, UsageKey
from openedx.core.djangoapps.course_groups import cohorts
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.util.forms import to_bool
from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin, view_auth_classes
from student.auth import has_course_author_access
from student.models import CourseEnrollment
from student.roles import BulkRoleCache
from track.event_transaction_utils import (
    create_new_event_transaction_id,
    get_event_transaction_id,
    get_event_transaction_type,
    set_event_transaction_type
)

log = logging.getLogger(__name__)

@contextmanager
def bulk_gradebook_view_context(course_key, users):
    """
    Prefetches all course and subsection grades in the given course for the given
    list of users, also, fetch all the score relavant data,
    storing the result in a RequestCache and deleting grades on context exit.
    """
    PersistentSubsectionGrade.prefetch(course_key, users)
    PersistentCourseGrade.prefetch(course_key, users)
    CourseEnrollment.bulk_fetch_enrollment_states(users, course_key)
    cohorts.bulk_cache_cohorts(course_key, users)
    BulkRoleCache.prefetch(users)
    yield
    PersistentSubsectionGrade.clear_prefetched_data(course_key)
    PersistentCourseGrade.clear_prefetched_data(course_key)

def get_bool_param(request, param_name, default):
    """
    Given a request, parameter name, and default value, returns
    either a boolean value or the default.
    """
    param_value = request.query_params.get(param_name, None)
    bool_value = to_bool(param_value)
    if bool_value is None:
        return default
    else:
        return bool_value

def course_author_access_required(view):
    """
    Ensure the user making the API request has course author access to the given course.

    This decorator parses the course_id parameter, checks course access, and passes
    the parsed course_key to the view as a parameter. It will raise a
    403 error if the user does not have author access.

    Usage::
        @course_author_access_required
        def my_view(request, course_key):
            # Some functionality ...
    """
    def _wrapper_view(self, request, course_id, *args, **kwargs):
        """
        Checks for course author access for the given course by the requesting user.
        Calls the view function if has access, otherwise raises a 403.
        """
        course_key = CourseKey.from_string(course_id)
        if not has_course_author_access(request.user, course_key):
            raise DeveloperErrorViewMixin.api_error(
                status_code=status.HTTP_403_FORBIDDEN,
                developer_message='The requesting user does not have course author permissions.',
                error_code='user_permissions',
            )
        return view(self, request, course_key, *args, **kwargs)
    return _wrapper_view

def graded_subsections_for_course(course_structure):
    """
    Given a course block structure, yields the subsections of the course that are graded.
    Args:
        course_structure: A course structure object.  Not user-specific.
    """
    for chapter_key in course_structure.get_children(course_structure.root_block_usage_key):
        for subsection_key in course_structure.get_children(chapter_key):
            subsection = course_structure[subsection_key]
            if subsection.graded:
                yield subsection

GradebookUpdateResponseItem = namedtuple('GradebookUpdateResponseItem',
                                         ['user_id', 'usage_id', 'success', 'reason', 'grade_data'])

@view_auth_classes()
class GradebookBulkUpdateView(GradeViewMixin, PaginatedAPIView):
    """
    **Use Case**
        Creates `PersistentSubsectionGradeOverride` objects for multiple (user_id, usage_id)
        pairs in a given course, and invokes a Django signal to update subsection grades in
        an asynchronous celery task.

    **Example Request**
        POST /api/grades/v1/gradebook/{course_id}/bulk-update

    **POST Parameters**
        This endpoint does not accept any URL parameters.

    **Example POST Data**
          {
            9: {"block-v1:edX+DemoX+Demo_Course+type@sequential+block@basic_questions": 50,
                "block-v1:edX+DemoX+Demo_Course+type@sequential+block@advanced_questions": 100},

            11: {"block-v1:edX+DemoX+Demo_Course+type@sequential+block@basic_questions": 90}
          }

    **POST Response Values**
        An HTTP 202 may be returned if a grade override was created for each of the requested (user_id, usage_id)
        pairs in the request data.
        An HTTP 403 may be returned if the `writable_gradebook` feature is not
        enabled for this course.
        An HTTP 404 may be returned for the following reasons:
            * The requested course_key is invalid.
            * No course corresponding to the requested key exists.
            * The requesting user is not enrolled in the requested course.
        An HTTP 422 may be returned if any of the requested (user_id, usage_id) pairs
        did not have a grade override created due to some exception.  A `reason` detailing the exception
        is provided with each response item.

    **Example successful POST Response**
        [
          {
            "user_id": 9,
            "usage_id": ["some-requested-usage-id", "some-requested-usage-id"]
            "success": true,
            "reason": null,
            "grade_data": [
                {'category': 'Total', 'override': True, 'usage_key': '', 'grade': 75, 'class': 'high-column',
                    'percent': 0.75, 'detail': u'Total', 'label': 'Total'},
                {'category': u'Homework', 'override': True, 'usage_key': u'block-v1:edX+DemoX+Demo_Course+type@se..},
                {'category': u'Homework', 'override': True, 'usage_key': u'block-v1:edX+DemoX+Demo_Course+type@se..},
                {'category': u'Homework', 'override': False, 'usage_key': '', 'grade': 0, 'class': '', 'percent':..},
                {'category': u'Exam', 'override': False, 'usage_key': u'block-v1:edX+DemoX+Demo_Course+type@seq..}
            ]
          }
        ]
    """

    @verify_course_exists
    @course_author_access_required
    def post(self, request, course_key):
        """
        Creates or updates `PersistentSubsectionGradeOverrides` for the (user_id, usage_key)
        specified in the request data.  The `GRADE_EDITED` signal is invoked
        after the grade override is created, which triggers a celery task to update the
        course and subsection grades for the specified user.
        """

        course = get_course_by_id(course_key, depth=None)

        result = []
        email_list = []
        course_progress_users = []
        whole = False
        data = request.data['log']
        number_of_sections = int(request.data['number_of_sections'])
        import json
        data = json.loads(data)
        for user_id, keys in data.items():
            requested_user_id = int(user_id)
            usage_ids = list(set(keys))
            override_sections = {}
            if number_of_sections == len(usage_ids):
                whole = True
            try:
                user = self._get_single_user(request, course_key, requested_user_id)
            except USER_MODEL.DoesNotExist:
                continue

            for requested_usage_id in copy.copy(usage_ids):
                try:
                    usage_key = UsageKey.from_string(requested_usage_id)

                except InvalidKeyError as exc:
                    self._log_update_result(
                        request.user, requested_user_id, requested_usage_id, success=False, reason=text_type(exc)
                    )
                    usage_ids.remove(requested_usage_id)
                    continue

                try:
                    subsection_grade_model = PersistentSubsectionGrade.objects.get(
                        user_id=requested_user_id,
                        course_id=course_key,
                        usage_key=usage_key
                    )

                except PersistentSubsectionGrade.DoesNotExist:
                    subsection = course.get_child(usage_key)
                    if subsection:
                        subsection_grade_model = self._create_subsection_grade(user, course, subsection)
                    else:
                        self._log_update_result(
                            request.user, requested_user_id, requested_usage_id, success=False,
                            reason=u'usage_key does not exist in this course.'
                        )
                        usage_ids.remove(requested_usage_id)
                        continue

                if subsection_grade_model:
                    # if the current score equals to the override score, skip and remove the usage_id from the list
                    # This won't happen if we edit the score of subsections one by one, but it could happen when we
                    # edit the total score or the average score, because we have to change all the score of the included
                    # subsection to the same
                    override_score = keys[requested_usage_id] * subsection_grade_model.possible_all / 100
                    if override_score == subsection_grade_model.earned_all:
                        usage_ids.remove(requested_usage_id)
                        continue
                    else:
                        override_data = {
                            "earned_all_override": override_score,
                            "possible_all_override": subsection_grade_model.possible_all,
                            "earned_graded_override": override_score,
                            "possible_graded_override": subsection_grade_model.possible_all
                        }
                        override = self._create_override(request.user, subsection_grade_model, **override_data)
                        self._log_update_result(
                            request.user, requested_user_id, requested_usage_id, subsection_grade_model, override, True
                        )

            if usage_ids:
                course_grade = CourseGradeFactory().read(user, course)
                grade_summary = course_grade.summary
                graded_subsections = course_grade.graded_subsections_by_format
                section_breakdown = grade_summary['section_breakdown']
                for section in section_breakdown:
                    sections_by_format = graded_subsections.get(section.get('category'))
                    if sections_by_format:
                        pair = sections_by_format.popitem(last=False)
                        section['usage_key'] = unicode(pair[0])
                        if unicode(pair[0]) in usage_ids:
                            override_sections[pair[1].display_name] = int(section['percent'] * 100)
                        if pair[1].override is not None:
                            section['override'] = True
                            grade_summary['override'] = True
                    else:
                        continue
                grade_data = self._grade_data(grade_summary)
                result.append(GradebookUpdateResponseItem(
                    user_id=user.id,
                    usage_id=usage_ids,
                    success=True,
                    reason=None,
                    grade_data=grade_data
                ))
                email_list.append({
                    'total': int(grade_summary['percent'] * 100),
                    'name': user.profile.name or user.username,
                    'email': user.email,
                    'whole': whole,
                    'sections': override_sections,
                    'language': get_user_email_language(user)
                })
                course_progress_users.append(user.id)

        if email_list:
            # we don't finish the anaytics transcript feature yet, so use this fake link
            transcript_link = request.build_absolute_uri(reverse('analytics_my_transcript'))
            course_name = course.display_name_with_default_escaped
            platform_name = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)
            email_service_enabled = configuration_helpers.get_value('ENABLE_EMAIL_SERVICE', True)
            from_alias = configuration_helpers.get_value('email_from_alias', settings.DEFAULT_FROM_EMAIL_ALIAS)
            from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
            from_address = "{0} <{1}>".format(from_alias, from_address)
            send_grade_override_email.apply_async(
                kwargs={
                    'student_info': email_list,
                    'transcript_link': transcript_link,
                    'course_name': course_name,
                    'platform_name': platform_name,
                    'email_service_enabled': email_service_enabled,
                    'from_address': from_address
                }
            )
            if course_progress_users:
                update_course_progress.apply_async(
                    kwargs={
                        'users': course_progress_users,
                        'course_id': unicode(course_key)
                    }
                )

        status_code = status.HTTP_422_UNPROCESSABLE_ENTITY
        if len(result) > 0:
            status_code = status.HTTP_202_ACCEPTED

        return Response(
            {item.user_id: item._asdict() for item in result},
            status=status_code,
            content_type='application/json'
        )

    def _create_subsection_grade(self, user, course, subsection):
        course_data = CourseData(user, course=course)
        subsection_grade = CreateSubsectionGrade(subsection, course_data.structure, {}, {})
        return subsection_grade.update_or_create_model(user, force_update_subsections=True)

    def _create_override(self, request_user, subsection_grade_model, **override_data):
        """
        Helper method to create a `PersistentSubsectionGradeOverride` object
        and send a `GRADE_EDITED` signal.
        """
        override = PersistentSubsectionGradeOverride.update_or_create_override(
            requesting_user=request_user,
            subsection_grade_model=subsection_grade_model,
            feature=PersistentSubsectionGradeOverrideHistory.GRADEBOOK,
            **override_data
        )

        GRADE_EDITED.send(
            sender=None,
            user_id=subsection_grade_model.user_id,
            course_id=subsection_grade_model.course_id,
            modified=override.modified,
        )

        set_event_transaction_type(SUBSECTION_GRADE_CALCULATED)
        create_new_event_transaction_id()

        recalculate_subsection_grade_v3.apply(
            kwargs=dict(
                user_id=subsection_grade_model.user_id,
                anonymous_user_id=None,
                course_id=text_type(subsection_grade_model.course_id),
                usage_id=text_type(subsection_grade_model.usage_key),
                only_if_higher=False,
                expected_modified_time=to_timestamp(override.modified),
                score_deleted=False,
                event_transaction_id=unicode(get_event_transaction_id()),
                event_transaction_type=unicode(get_event_transaction_type()),
                score_db_table=ScoreDatabaseTableEnum.overrides,
                force_update_subsections=True,
            )
        )
        # Emit events to let our tracking system to know we updated subsection grade
        subsection_grade_calculated(subsection_grade_model)
        return override

    def _grade_data(self, grade_summary):
        data = []
        for section in grade_summary['section_breakdown']:
            attrs = {'percent': section['percent'], 'category': section['category'],
                     'label': section['label'], 'detail': section['detail'],
                     'class': '', 'grade': int(round(section['percent'] * 100)),
                     'usage_key': section.get('usage_key', ''),
                     'override': section.get('override', False)}
            if 'Avg' in section['label']:
                attrs['class'] = 'high-column'
            if section.get('override', False):
                attrs['override'] = True
            data.append(attrs)
        total = {'percent': grade_summary['percent'], 'category': 'Total', 'label': 'Total',
                 'detail': _('Total'),'class': 'high-column', 'grade': int(round(grade_summary['percent'] * 100)),
                 'override': grade_summary.get('override', False), 'usage_key': ''}
        if grade_summary.get('manually_changed'):
            total['manually_changed'] = True
        data = [total] + data
        return data

    @staticmethod
    def _log_update_result(
        request_user,
        user_id, usage_id,
        subsection_grade_model=None,
        subsection_grade_override=None,
        success=False,
        reason=None,
    ):

        log.info(
            u'Grades: Bulk_Update, UpdatedByUser: %s, User: %s, Usage: %s, Grade: %s, GradeOverride: %s, Success: %s, '
            u'Reason: %s',
            request_user.id,
            user_id,
            usage_id,
            subsection_grade_model,
            subsection_grade_override,
            success,
            reason
        )

@require_POST
def undo_override_for_student(request, course_id):
    user_id = int(request.POST.get('user_id'))
    user = User.objects.get(id=user_id)
    course_key = CourseKey.from_string(course_id)
    usage_ids = json.loads(request.POST.get('usage_ids'))
    for key in usage_ids:
        GradesService().undo_override_subsection_grade(user_id, course_id, key)
    GRADE_EDITED.send(
        sender=None,
        user_id=user_id,
        course_id=course_key,
        modified=timezone.now(),
    )
    grade_summary = CourseGradeFactory().read(user, course_key=course_key).summary
    update_course_progress.apply_async(
        kwargs={
            'users': [user_id],
            'course_id': course_id
        }
    )
    data = []
    for section in grade_summary['section_breakdown']:
        attrs = {'percent': section['percent'], 'category': section['category'],
                 'label': section['label'], 'detail': section['detail'],
                 'class': '', 'grade': int(round(section['percent'] * 100)),
                 'usage_key': section.get('usage_key', ''),
                 'override': section.get('override', False)}
        if 'Avg' in section['label']:
            attrs['class'] = 'high-column'
        if section.get('override', False):
            attrs['override'] = True
        data.append(attrs)
    total = {'percent': grade_summary['percent'], 'category': 'Total', 'label': 'Total',
             'detail': _('Total'), 'class': 'high-column', 'grade': int(round(grade_summary['percent'] * 100)),
             'override': grade_summary.get('override', False), 'usage_key': ''}
    data = [total] + data
    return JsonResponse({user_id: data})


import torch
from torch.autograd import grad, gradcheck

def check_grad(solve_func, inputs, eps, atol, rtol):
    assert gradcheck(solve_func, inputs, eps=eps, atol=atol)

    A_val, b = inputs[0], inputs[1]
    # Check that the gradient works correctly for floating point data
    out = solve_func(*inputs).sum()
    gA, gb = grad(out, (A_val, b))

    A_float = A_val.float()
    b_float = b.float()
    inputs2 = (A_float, b_float) + inputs[2:]
    out_float = solve_func(*inputs2).sum()
    gA_float, gb_float = grad(out_float, (A_float, b_float))

    # This mostly checks that backward() is not accumulating
    # additional floating point errors on top of those expected by
    # converting the input from double to float. Naive float casting
    # in the backward python ops can result in differences in order of magnitude
    # even for well-conditioned systems. These checks cover that case.
    #
    # Do note that, in general, it's possible to construct very
    # ill-conditioned systems where the initial loss or precision is enough
    # to get large gradient errors no matter what we do. This checks
    # are not meant to capture such scenarios.
    torch.testing.assert_close(gA, gA_float.double(), rtol=rtol, atol=atol)
    torch.testing.assert_close(gb, gb_float.double(), rtol=rtol, atol=atol)


import numpy as np
import matplotlib.pyplot as plt

class CPPN:
    def __init__(self, num_input, num_output, num_hidden_layers=3,
                 num_hidden_units=32, activation_functions=[np.sin, np.tanh]):
        self.num_input = num_input
        self.num_output = num_output
        self.num_hidden_layers = num_hidden_layers
        self.num_hidden_units = num_hidden_units
        self.activation_functions = activation_functions

        # Initialize weights and biases
        self.weights = []
        self.biases = []
        input_to_hidden = np.random.uniform(low=-1, high=1, size=(self.num_input, self.num_hidden_units))
        self.weights.append(input_to_hidden)
        self.biases.append(np.zeros(self.num_hidden_units))

        for _ in range(self.num_hidden_layers - 1):
            hidden_to_hidden = np.random.uniform(low=-1, high=1, size=(self.num_hidden_units, self.num_hidden_units))
            self.weights.append(hidden_to_hidden)
            self.biases.append(np.zeros(self.num_hidden_units))

        hidden_to_output = np.random.uniform(low=-1, high=1, size=(self.num_hidden_units, self.num_output))
        self.weights.append(hidden_to_output)
        self.biases.append(np.zeros(self.num_output))

    def activate(self, x):
        for layer in range(len(self.weights)):
            x = np.dot(x, self.weights[layer]) + self.biases[layer]
            activation_func = self.activation_functions[layer % len(self.activation_functions)]
            x = activation_func(x)
        return x

    def compute_image(self, width, height):
        x = np.linspace(-1, 1, width)
        y = np.linspace(-1, 1, height)
        xs, ys = np.meshgrid(x, y)
        rs = np.sqrt(xs**2 + ys**2)
        thetas = np.arctan2(ys, xs)

        inputs = []
        for i in range(self.num_input):
            if i % 4 == 0:
                inputs.append(rs)
            elif i % 4 == 1:
                inputs.append(thetas)
            elif i % 4 == 2:
                inputs.append(np.sin(self.c[i] * rs + self.d[i] * thetas))
            elif i % 4 == 3:
                inputs.append(np.cos(self.c[i] * rs + self.d[i] * thetas))

        inputs = np.array(inputs).transpose()

        # apply the hidden layers
        hiddens = inputs
        for i in range(self.num_hidden_layers):
            hiddens = np.maximum(np.dot(hiddens, self.weights[i]) + self.biases[i], 0)

        # apply the output layer
        rgba = np.dot(hiddens, self.weights[-1]) + self.biases[-1]
        rgba = np.clip(rgba, -1, 1)
        rgba = (rgba + 1) / 2 # scale to 0-1 range
        rgba = (rgba * 255).astype(int) # scale to 0-255 range
        rgba = np.reshape(rgba, (height, width, 4))

        return rgba

# Example usage
cppn = CPPN(num_input=2, num_output=4, num_hidden_layers=8, num_hidden_units=16, activation_functions=[np.cos, np.sin, np.square, np.sin, np.tanh])
image = cppn.compute_image(width=480, height=480)
plt.imshow(image)
plt.show()


t=int(input())
for a0 in range(t):
    flag=0
    n=int(input())
    n1=n
    a=[]
    l=0
    if n<3 or n==7 or n==4:
        print(-1)
        continue
    if n1%3==0 and n1%5==0:
       print(str(5)*int((n1)))
       continue
    while(n%3!=0 and n>=5):
        n=n-5

    l=n1-n
    a.append(str(5)*n)
    a.append(str(3)*l)
    print(*a,sep="")


intValid = False
intNumber = False
while not intValid:
    try:
        intNumber = int(input('Write a integer number: '))
    except KeyboardInterrupt:
        print('\033[0;31mNo number entered. \033[m')
        intValid = True
    except:
        print(f'\033[0;31mPlease, type a valid number. \033[m')
    else:
        intValid = True

floatValid = False
floatNumber = 0
while not floatValid:
    try:
        floatNumber = float(input('Write a float number: '))
    except KeyboardInterrupt:
        print('\033[0;31mNo number entered. \033[m')
        floatValid = True
    except:
        print(f'\033[0;31mPlease, type a valid number. \033[m')
    else:
        floatValid = True

print(f'The integer value entered was {intNumber} and the float value was {floatNumber}')


def solution(array, commands):

    result_list = []

    for command in commands:
        temp = array[command[0]-1:command[1]]
        temp.sort()
        result_list.append(temp[command[2]-1])
    print(result_list)

solution([1, 5, 2, 6, 3, 7, 4],	[[2, 5, 3], [4, 4, 1], [1, 7, 3]])


from .vector_base import VectorBase
from ..object import ObjectID
import chromadb
import logging
import os

class ChromaVectorStore(VectorBase):
    def __init__(self, root_dir, model_name: str) -> None:
        super().__init__(model_name)

        logging.info(
            "will init chroma vector store, model={}".format(model_name)
        )

        directory = os.path.join(root_dir, "vector")
        logging.info("will use vector store: {}".format(directory))

        client = chromadb.PersistentClient(
            path=directory, settings=chromadb.Settings(anonymized_telemetry=False)
        )
        # client = chromadb.Client()

        collection_name = "coll_{}".format(model_name)
        logging.info("will init chroma colletion: %s", collection_name)

        collection = client.get_or_create_collection(collection_name)
        self.collection = collection

    async def insert(self, vector: [float], id: ObjectID):
        logging.info(f"will insert vector: {len(vector)} id: {str(id)}")
        logging.debug(f"vector is {vector}")
        self.collection.add(
            embeddings=vector,
            ids=str(id),
        )

    async def query(self, vector: [float], top_k: int) -> [ObjectID]:
        ret = self.collection.query(
            query_embeddings=vector,
            n_results=top_k,
        )
        logging.info(f"query result {ret}")
        if len(ret['ids']) == 0:
            return []
        return list(map(ObjectID.from_base58, ret["ids"][0]))

    async def delete(self, id: ObjectID):
        self.collection.delete(
            ids=id,
        )


# ENCAPSULATION ->
# In an object-oriented python programming, you can restrict access to methods and variables
# This can prevent the date being modified by accident and is known as encapsulation and
# it can be achieved using the private methods and variables
# Public Variable -> Accessible from anywhere
# Public Methods  -> Accessible from anywhere
# Private variable -> Accessible only in their  own methods
# Private Methods -> Accessible only in their own class or by a method if defined. starts with two underscores.

class myClass:
    __a = 10  # This is a private class variable. Scope is with in the class.
    # This is private as it started with two underscores
    b = 20  # this is a public class variable

    def disp(self):
        print(self.__a)  # We need to use self keyword to access class variable.

print("##########################(1)################################")
objM = myClass()
objM.disp()
# print(myClass.__a)  # Here we cannot access private variable outside the class. We will get attribute error
print(myClass.b)  # We can access this as it is not a private variable
print("#############(2-Accessing private variables outside of the class indirectly using methods)#############")

class A:
    __i = 20  # It is a private variable

    def dispI(self):
        print(self.__i)

    def getI(self, ivalue):
        self.__i = ivalue
        print(self.__i)

obj = A()
obj.dispI()  # Here it is 20
obj.getI(30)  # Here indirectly we accessed a private variable
obj.dispI()  # Here it is 30 as it was accessed and modified using the above method


from django.template import Library, Node, RequestContext, Variable
from django.template.loader import select_template

register = Library()

class PromotionNode(Node):
    def __init__(self, promotion):
        self.promotion_var = Variable(promotion)

    def render(self, context):
        promotions = self.promotion_var.resolve(context)
        template = select_template(['homepage/gallery.html'])
        args = {'promotions': promotions, 'products': []}
        for promotion in promotions:
            if hasattr(promotion, 'product'):
                args['products'].append(promotion.product)
            # args.update(**promotion.template_context(request=context['request']))
        # ctx = RequestContext(context['request'], args)
        # return template.render(ctx)
        return template.render(args, context['request'])

def get_promotion_html(parser, token):
    _, promotion = token.split_contents()
    return PromotionNode(promotion)

register.tag('render_promotion', get_promotion_html)


# -*- coding: utf-8 -*-
# 爬取动漫之家 pixiv 图片，参考页面：https://news.dmzj.com/article/48293.html
# TODO: 建立数据表与数据关联，图片上传至第三方云服务器存储

import requests
from bs4 import BeautifulSoup
import os
import time
import hashlib
import re
from db import Mysql

Mysql = Mysql()

class DmzjCrawler():

    # 标识下载数量
    x = 0
    taskNum = 0
    # 爬取第几页，进程运行时自增
    page = 60
    # 请求头
    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'max-age=0',
        'cookie': 'UM_distinctid=165d8713f431c-03be91a8ec41a-54103715-1fa400-165d8713f4532b; show_tip_1=0',
        'referer': 'https://news.dmzj.com/article/12875.html',
        'upgrade-insecure-requests': '1',
        'if-modified-since': 'Thu, 04 Jan 2018 01:57:35 GMT',
        'if-none-match': "5a4d8a0f-a939e",
        'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36',
    }

    def __init__(self, config):
        self.taskMaxNum = config['taskMaxNum']
        self.sleepTime = config['sleepTime']
        self.downloadPath = config['downloadPath']

    # 创建文件夹
    def mkdir(self, path):
        folder = os.path.exists(path)
        if not folder: # 判断是否存在文件夹，如果不存在则创建为文件夹
            os.makedirs(path)

    # 下载图片
    def downloadImage(self, url, downloadPath, name):
        self.mkdir(downloadPath)
        image = self.get(url)
        with open(os.path.join(downloadPath, name), 'wb') as f:
            f.write(image.content)
            f.close()
            self.x += 1
            # print('已下载第', self.x ,'张')

    # 获得图片地址
    def getImages(self, url, title):
        try:
            r = self.get(url)
            html = r.text
            soup = BeautifulSoup(html, 'html.parser')
            p_images = soup.find_all('p', style='text-align:center')
            if len(p_images) > 0:
                # 新增专题
                now = int(time.time())
                topic_id = Mysql.create("INSERT INTO lab_topic (title, create_time, update_time) VALUES ('%s', %s, %s)" % (title, now, now))
                images_values = []
                for p_image in p_images:
                    url = p_image.img['src']
                    p_name = p_image.img['alt']
                    p_object = re.search( r'id=(\d*)\..*', p_name, re.I)
                    p_id = int(p_object.group(1)) if p_object else 0
                    # 获取文件后缀名
                    etc = os.path.splitext(url)[1]
                    date = time.strftime('%Y%m%d',time.localtime(time.time()))
                    old_name = date + str(round(time.time() * 1000)) + p_name
                    name = hashlib.md5(old_name.encode(encoding='UTF-8')).hexdigest() + etc
                    downloadPath = os.path.join(self.downloadPath, date)
                    self.downloadImage(url, downloadPath, name)
                    save_path = date + '/' + name
                    images_values.append("('%s', %s, '%s', %s, %s, %s)" % (save_path, topic_id, p_name, p_id, now, now))
                create_sql = 'INSERT INTO lab_image (url, topic_id, name, p_id, create_time, update_time) VALUES ' + (','.join(images_values))
                Mysql.execute(create_sql)
                print('\033[1;32m--------------------已创建：', title, '\033[0m')
        except Exception as e:
            # TODO: log
            print(e)
            return
    # 获得图片页面
    def getImagesViewLinks(self, url):
        try:
            r = self.get(url)
            html = r.text
            soup = BeautifulSoup(html, 'html.parser')
            # 获取相关美图文章的链接
            links = soup.find_all('a', class_='dec_img')
            if len(links) == 0:
                self.page = -1
            for link in links:
                url = link['href']
                title = link['title']
                self.getImages(url, title)
            self.page -= 1
        except Exception as e:
            # TODO: log
            return

    def get(self, url):
        r = requests.get(url, headers = self.headers)
        return r

    def start(self):
        while (self.page > 0 and self.page < 61):
           url = 'https://news.dmzj.com/meituxinshang/p{}.html'.format(self.page)
           print('\033[1;35m--------------------当前页数：', self.page, '\033[0m')
           self.getImagesViewLinks(url)
           time.sleep(self.sleepTime)
        print('下载完成！')


"""This module contains the main training loop"""

from random import random

import numpy as np
import torch
from scipy.spatial.transform import Rotation
from torch.utils.data import DataLoader
from tqdm import tqdm

from pointcloud_invariance_smoothing.models.invariance_wrappers import (
    PCAEnsembleWrapper, SinglePCAWrapper, StackingPCAWrapper)
from pointcloud_invariance_smoothing.models.pointnet import (
    PointNetClassifier, pointnet_loss)

def train(model, data_train, data_val,
          num_epochs, batch_size,
          learning_rate, weight_decay, regularization_weight,
          scheduler_stepsize, scheduler_gamma,
          rotate, scale, add_noise,
          scale_limits, std,
          rotate_validation, add_noise_validation,
          device, num_workers):
    """Main training loop, for meaning of parameters see seml/scripts/train.py.

    Returns:
        Four arrays of length num_epochs, tracking train loss, val loss,
        train accuracy, val accuracy
        and two state dicts containing model with best validation loss and model
        with best validation accuracy.
    """

    train_loader = DataLoader(data_train, drop_last=True, batch_size=batch_size, shuffle=True,
                              num_workers=num_workers)

    val_loader = DataLoader(data_val, drop_last=False, batch_size=batch_size, shuffle=True,
                            num_workers=num_workers)

    optimizer = torch.optim.Adam(
            model.parameters(),
            lr=learning_rate,
            weight_decay=weight_decay
        )

    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=scheduler_stepsize,
                                                gamma=scheduler_gamma)

    loss_fn = pointnet_loss

    loss_trace_train = []
    acc_trace_train = []

    loss_trace_val = []
    acc_trace_val = []

    best_loss_val = None
    best_acc_val = None

    best_model_loss = None
    best_model_acc = None

    for _ in tqdm(range(num_epochs)):
        model.train()

        per_batch_losses = []
        per_batch_accs = []

        for X, targets in train_loader:
            optimizer.zero_grad()

            X, targets = X.to(device), targets.to(device)

            if rotate:
                X = randomly_rotate(X, device)

            if scale:
                X = randomly_scale(X, *scale_limits, device)

            if add_noise:
                X = add_gaussian_noise(X, std, device)

            logits, trans_feat = model(X)

            loss = loss_fn(logits, targets.long(), trans_feat, regularization_weight)
            loss.backward()

            optimizer.step()

            pred = logits.detach().max(dim=1)[1]
            n_correct = (pred == targets.long()).sum().cpu()
            per_batch_accs.append(int(n_correct) / batch_size)

            per_batch_losses.append(float(loss.detach().cpu()))

        loss_trace_train.append(np.mean(per_batch_losses))
        acc_trace_train.append(np.mean(per_batch_accs))

        scheduler.step()

        model.eval()

        per_batch_losses = []
        per_batch_accs = []

        for X, targets in val_loader:
            X, targets = X.to(device), targets.to(device)

            if rotate_validation:
                X = randomly_rotate(X, device)
                raise ValueError()

            if add_noise_validation:
                X = add_gaussian_noise(X, std, device)
            else:
                if add_noise:
                    raise ValueError()

            logits, _ = model(X)

            loss = loss_fn(logits, targets.long())

            pred = logits.detach().max(dim=1)[1]
            n_correct = (pred == targets.long()).sum().cpu()
            per_batch_accs.append(int(n_correct) / batch_size)

            per_batch_losses.append(float(loss.detach().cpu()))

        loss_trace_val.append(np.mean(per_batch_losses))
        acc_trace_val.append(np.mean(per_batch_accs))

        print(loss_trace_val[-1], acc_trace_val[-1])

        if isinstance(model, (PCAEnsembleWrapper, SinglePCAWrapper, StackingPCAWrapper)):
            state_dict = model.base_model.state_dict()
        else:
            state_dict = model.state_dict()

        if best_loss_val is None or loss_trace_val[-1] < best_loss_val:
            best_loss_val = loss_trace_val[-1]
            best_model_loss = state_dict
        if best_acc_val is None or acc_trace_val[-1] < best_acc_val:
            best_acc_val = acc_trace_val[-1]
            best_model_acc = state_dict

    return (loss_trace_train, loss_trace_val,
            acc_trace_train, acc_trace_val,
            best_model_loss, best_model_acc)

def add_gaussian_noise(x: torch.Tensor, std: float, device: torch.device) -> torch.Tensor:

    return x + std * torch.randn(x.shape).to(device)

def randomly_scale(x: torch.Tensor, scale_min: float, scale_max: float,
                   device: torch.device) -> torch.Tensor:
    """Scale each point cloud in batch by a different factor sampled from uniform distribution"""

    scale = torch.rand(len(x)) / (scale_max - scale_min) + scale_min
    scale = scale[:, None, None].to(device)

    return x * scale

def randomly_rotate(x: torch.Tensor, device: torch.device) -> torch.Tensor:
    """Randomly rotate each point cloud in batch using uniformly sampled rotation matrix"""
    n_dim = x.shape[-1]
    batch_size = x.shape[0]

    rotation_matrices = generate_random_rotations(n_dim, batch_size).to(device)

    return torch.bmm(x, rotation_matrices.transpose(2, 1))

def generate_random_rotations(n_dim: int, n_samples: int) -> torch.Tensor:
    """Return n_samples different rotation matrices of shape n_dim x n_dim"""
    assert n_dim in [2, 3]

    if n_dim == 2:
        angles = np.random.uniform(0, 2 * np.pi, n_samples)

        rotation_matrices = np.empty((n_samples, n_dim, n_dim))
        rotation_matrices[:, 0, 0] = np.cos(angles)
        rotation_matrices[:, 0, 1] = -1 * np.sin(angles)
        rotation_matrices[:, 1, 0] = np.sin(angles)
        rotation_matrices[:, 1, 1] = np.cos(angles)

    if n_dim == 3:
        rotation_matrices = Rotation.random(n_samples).as_matrix()

    return torch.Tensor(rotation_matrices)


'''
You are given a dictionary/hash/object containing some languages and your test results
in the given languages. Return the list of languages where your test score is at least 60,
in descending order of the results.

Note: the scores will always be unique (so no duplicate values)
'''
def my_languages(results):
    sorted_dict = sorted((value,key) for (key,value) in results.items())
    reverse_list = sorted_dict[::-1]
    return_list = []
    for x in reverse_list:
        if x[0] >= 60:
            return_list.append(x[1])
    return(return_list)


""" Wrapper script for awscli which connects to containers running in
    ecs seamlessly """
import click
import logging
import os
import re
import inquirer
import signal
from ecs_connect.version import __version__
from ecs_connect.config import ECSConfig
from ecs_connect.ecs import ECSHandler
from ecs_connect.ssm import SSMHandler
from configparser import RawConfigParser

@click.command()
@click.option('--profile', help="Name of the profile to use in ~/.ecs-connect. \
If none is provided, then the default profile will be used.\n")
@click.option('--awsprofile', help="Name of the aws profile to use form ecs-connect. \
If none is provided, then the default aws profile will be used.\n")
@click.option('--cluster', help="Name of the ECS cluster. \
If provided, then parameter from profile will be overridden.\n")
@click.option('--service', help="Name of the service. \
If provided, then parameter from profile will be overridden.\n")
@click.option('--task', help="Name of the task. \
If provided, then parameter from profile will be overridden.\n")
@click.option('--exec_cmd', help="Initilization command to run with ecs exec. \
If provided, then parameter from profile will be overridden.\n")
@click.option('--container', help="Name of the container. \
If provided, then parameter from profile will be overridden.\n")
@click.option('--bastion', help="Instance Id of the bastion node, \
required for task running in FARGATE. \
If provided, then parameter from profile will be overridden.\n")
@click.option('--cmd', help="Initilization command to run. \
If provided, then parameter from profile will be overridden.\n")
@click.option('-l', '--logs', is_flag=True, help="fetch logs.")
@click.option('--since', default='20m', help="From what time to begin displaying logs.\n")
@click.option('-f', '--follow', is_flag=True,
              help="Whether to continuously poll for new logs.\n")
@click.option('--format', default='short', help="The format to display the logs.\n")
@click.option('--filter', help="The filter pattern to use.\n")
@click.option('-a', '--all', is_flag=True,
              help='Displays all running containers\n')
@click.option('-V', '--version', is_flag=True,
              help='Displays version number\n')
@click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')
@click.option('-d', '--debug', is_flag=True, help='Enables debug mode')
@click.option('-i', '--interactive', is_flag=True, help='Interactive mode')
def main(profile, awsprofile, cluster, service, task, container, bastion, exec_cmd, cmd,
         logs, since, follow, format, filter, all, version, verbose, debug, interactive):
    if version:
        print(__version__)
        exit(0)

    # Set up logging
    logger = logging.getLogger('ecs-connect')
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    handler.setLevel(logging.WARN)
    formatter = logging.Formatter('%(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    if verbose:
        handler.setLevel(logging.INFO)
    if debug:
        handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)

    if not interactive or logs:
        ecs_config = ECSConfig(logger)
        if not profile:
            profile = "default"
        if not cluster:
            cluster = ecs_config.get_cluster(profile)
        if not awsprofile:
            awsprofile = ecs_config.get_awsprofile(profile)
        if not task:
            task = ecs_config.get_task(profile)
        if not exec_cmd:
            exec_cmd = ecs_config.get_exec_cmd(profile)
        if not container:
            container = ecs_config.get_container(profile, exec_cmd)
        if task is None:
            if not service:
                service = ecs_config.get_service(profile)
        else:
            service = None
        if not bastion:
            bastion = ecs_config.get_bastion(profile)
        if not cmd:
            cmd = ecs_config.get_cmd(profile, exec_cmd)
        ssh_user = ecs_config.get_ssh_user(profile)
        ssh_key = ecs_config.get_ssh_key(profile)
        ssh_port = ecs_config.get_ssh_port(profile)

        ecs = ECSHandler(awsprofile, cluster, service, task, container, bastion, logger, cmd, exec_cmd)
        if exec_cmd is not None:
            if logs:
                ecs.logs(since, follow, format, filter)
            else:
                ecs.exec()
        else:
            instance_id, bastion_enabled = ecs.get_ec2_instance_id()
            ssm = SSMHandler(awsprofile, instance_id, service, bastion_enabled, bastion, ssh_user, ssh_key, ssh_port, logger)
            ssm.run(cmd, all)
    else:
        config_path = os.path.expanduser('~') + '/.aws/config'
        _value = RawConfigParser()
        _value.read(config_path)
        aws_profiles = _value.sections()
        profiles = map( str, aws_profiles)
        profiles = list(map( lambda x: re.sub("profile ", "", x), profiles))
        questions = [
            inquirer.List('aws',
                        message="Select AWS Profile",
                        choices=profiles,
                    ),
        ]
        answers = inquirer.prompt(questions)
        ecs = ECSHandler(answers["aws"], '', '', '', '', '', logger, '', 'bash')
        ecs.interactive()

if __name__ == "__main__":
    main()


# Python Program That Uses A Queue In Thread Communication

'''
Function Name    :  Uses A Queue In Thread Communication
Function Date    :  5 Oct 2020
Function Author  :  Prasad Dangare
Input            :  String
Output           :  String
'''

import queue
from threading import*
from time import*
from queue import*

# Create Producer Class

class Producer:
    def __init__(self):
        self.q = Queue()

    def produce(self):

        # Create 1 To 10 Items And Add To The Queue

        for i in range(1, 11):
          print('Producing Items : ', i)
          self.q.put(i)
          sleep(1)

# Create Consumer Class

class Consumer:
    def __init__(self, prod):
        self.prod = prod

    def consume(self):

        # Receive 1 To 10 Items From The Queue

        for i in range(1, 11):
            print('Receving Items : ', self.prod.q.get(i))

# Create Producer Object

p = Producer()

# Create Consumer Object And Pass Producer Object

c = Consumer(p)

# Create Producer And Consumer Threads

t1 = Thread(target=p.produce)
t2 = Thread(target=c.consume)

# Run The Threads

t1.start()
t2.start()


#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
This module provides definition of cuts.
"""
__author__    = "I-Huan CHIU"
__email__     = "ichiu@chem.sci.osaka-u.ac.jp"
__created__   = "2019-11-08"
__copyright__ = "Copyright 2019 I-Huan CHIU"
__license__   = "GPL http://www.gnu.org/licenses/gpl.html"

# modules
import sys,os,random,math,ROOT
from ROOT import TFile, TTree, TCut, TChain, TSelector
from ROOT import gROOT, AddressOf
import enums
from utils.logger import log

def PreEventSelection(ifile, tree, nmax):
    if not nmax: nmax = tree.GetEntries()
    cut = TCut("1")
    if "test_f_" in ifile : cut = TCut("integral_livetime > 500 && integral_livetime < 1500")#JPARC March Si-data
    if "20200307a" in ifile : cut = TCut("integral_livetime > 220 && integral_livetime < 380")#JPARC March CdTe-data
    cut += TCut("Entry$ < {}".format(nmax))
    cv = ROOT.TCanvas("","")
    tree.Draw(">>elist", cut)
    elist = gROOT.FindObject("elist")
    _cutname=cut.GetTitle()
    return elist,_cutname

def findx2yshift(h_x, h_y):
    g1x = ROOT.TF1("g1x","gaus",100,300)
    g2x = ROOT.TF1("g2x","gaus",650,800)
    g1y = ROOT.TF1("g1y","gaus",100,300)
    g2y = ROOT.TF1("g2y","gaus",650,850)
    h_x.Fit("g1x","QR")
    h_x.Fit("g2x","QR+")
    h_y.Fit("g1y","QR")
    h_y.Fit("g2y","QR+")
    mean1_x, mean2_x = g1x.GetParameter(1), g2x.GetParameter(1)
    mean1_y, mean2_y = g1y.GetParameter(1), g2y.GetParameter(1)

    a = (g2y.GetParameter(1) - g1y.GetParameter(1))/(g2x.GetParameter(1) - g1x.GetParameter(1))
    b = g1y.GetParameter(1) - (a * g1x.GetParameter(1))

    return a, b

def findadccut(line, dtype, ecut):
    adccut = []
    if ecut is None : applyEcut = enums.EnergyCut
    else : applyEcut = ecut
    if "CdTe" in dtype:
       for ch in range(0, 256):
          cut_flag = 0
          for iadc in range(20,500):
             if ch < 128: #asic 0~3
                if (line[ch].Eval(iadc) > applyEcut) and (cut_flag == 0):
                   adccut.append(iadc)
                   cut_flag = 1
             else: #asic 4~7
                if (line[ch].Eval(iadc) > (applyEcut/2.)) and (cut_flag == 0):
                   adccut.append(iadc)
                   cut_flag = 1
          if cut_flag == 0: adccut.append(enums.ADCUpperBound)# not find a good cut value for adc, drop this channel
    else:
       for ch in range(0, 256):
          cut_flag = 0
          for iadc in range(10,1000):
             if ch < 128: #asic 0~3
                if (line[ch].Eval(iadc) > (applyEcut)) and (cut_flag == 0):
                   adccut.append(iadc)
                   cut_flag = 1
             else: #asic 4~7
                if (line[ch].Eval(iadc) > (applyEcut)) and (cut_flag == 0):
                   adccut.append(iadc)
                   cut_flag = 1
          if cut_flag == 0: adccut.append(enums.ADCUpperBound)# not find a good cut value for adc, drop this channel
    return adccut


from flask import Flask, Blueprint
from flask_jwt_extended import JWTManager
from mail import mail
from db import db
from slack import slack_client
from discord import discord_client

import json

class ConfigurationError(Exception):
    """Exception raised for errors in app config
    """

    def __init__(self, key):
        super().__init__("\"{}\" not found in application config".format(key))

def get_opt_config(app, config, key):
    if (key in config):
        app.config[key] = config[key]

def get_req_config(app, config, key):
    if (key not in config): raise ConfigurationError(key)
    app.config[key] = config[key]

def create_app(config_file='config/config.json'):
    app = Flask(__name__)

    config = json.load(open(config_file))

    get_req_config(app, config, 'DEBUG')
    app.debug = app.config['DEBUG']

    get_req_config(app, config, 'SECRET_KEY')
    get_req_config(app, config, 'MONGO_URI')
    get_req_config(app, config, 'MONGO_DB_NAME')
    get_req_config(app, config, 'TESTING')
    get_req_config(app, config, 'BASE_URL')
    get_opt_config(app, config, 'SLACK_WEBHOOK')
    get_opt_config(app, config, 'DISCORD_WEBHOOK')

    get_opt_config(app, config, 'MAIL_SERVER')
    get_opt_config(app, config, 'MAIL_PORT')
    get_opt_config(app, config, 'MAIL_USERNAME')
    get_opt_config(app, config, 'MAIL_PASSWORD')

    app.config['SLACK_SUPPRESS_SEND'] = False
    app.config['DISCORD_SUPPRESS_SEND'] = False

    # Supress mail sending if not specified, i.e. in dev
    if ('MAIL_SERVER' not in config):
        app.config['MAIL_SUPPRESS_SEND'] = True

    # Supress slack sending if not specified, i.e. in dev
    if ('SLACK_WEBHOOK' not in config):
        app.config['SLACK_SUPPRESS_SEND'] = True

    # Supress discord sending if not specified, i.e. in dev
    if ('DISCORD_WEBHOOK' not in config):
        app.config['DISCORD_SUPPRESS_SEND'] = True

    # Configurations that are always the same
    app.config['JWT_TOKEN_LOCATION'] =  ['cookies', 'headers']
    app.config['JWT_REFRESH_COOKIE_PATH'] = '/api/auth/session'
    app.config['JWT_COOKIE_CSRF_PROTECT '] = False
    app.config['JWT_CSRF_IN_COOKIES'] = False
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

    # Pass configurations to extensions
    jwt = JWTManager(app)
    db.init_app(app)
    mail.init_app(app)
    slack_client.init_app(app)
    discord_client.init_app(app)

    # Add endpoints from these files
    # Note order is important here
    from auth import auth_api
    from accounts import accounts_api
    from admin import admin_api
    from resumes import resume_api
    from vaccination import vaccination_api
    from registrations import registrations_api
    from assign import assign_api
    from announcements import announcements_api
    from events import events_api
    from slack import slack_api
    from discord import discord_api
    from teammatch import teammatch_api

    app.register_blueprint(auth_api, url_prefix='/api/auth')
    app.register_blueprint(admin_api, url_prefix='/api/admin')
    app.register_blueprint(accounts_api, url_prefix='/api/accounts')
    app.register_blueprint(resume_api, url_prefix='/api/resumes')
    app.register_blueprint(vaccination_api, url_prefix='/api/vaccination')
    app.register_blueprint(registrations_api, url_prefix='/api/registrations')
    app.register_blueprint(assign_api, url_prefix='/api/judgetool')
    app.register_blueprint(announcements_api, url_prefix='/api/announcements')
    app.register_blueprint(events_api, url_prefix='/api/events')
    app.register_blueprint(slack_api, url_prefix='/api/slack')
    app.register_blueprint(discord_api, url_prefix='/api/discord')
    app.register_blueprint(teammatch_api, url_prefix='/api/teammatch')

    return app


# -*- coding: utf-8 -*-
# @Author      : Ryan
# @Time        : 2020/8/6 22:57
# @Software    : PyCharm
# @Description : 5. 最长回文子串

'''

示例 1：

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2：

输入: "cbbd"
输出: "bb"

'''

class Solution:
    def longestPalindrome(self, s: str) -> str:
        stringList = list(str(s))
        maxLength = 0
        max_list = []
        length = len(stringList)
        if length == 1:
            return s
        for i in range(length):
            for j in range(i + 1, length):
                if (j - i == 1 or j - i == 2) and stringList[j] == stringList[i]:
                    if j - i > maxLength:
                        maxLength = j - i
                        max_list = stringList[i:(j + 1)]
                elif j - i == 1 and stringList[j] != stringList[i]:
                    continue
                elif j - i > 2 and stringList[j] == stringList[i]:
                    maxLength = j - i
                    max_list = stringList[i:(j + 1)]
                else:
                    break

        if maxLength != 0:
            return ''.join(max_list)
        return s[0:1]

if __name__ == '__main__':
    so = Solution()
    string = ""
    print(so.longestPalindrome(string))


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 20 22:23:25 2020

@author: MANOJ KUMAR SHRIVAST
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

car_df=pd.read_csv('Car_Purchasing_Data.csv',encoding='ISO-8859-1')

car_df.head()

car_df.tail()

sns.pairplot(car_df)

X=car_df.drop(['Customer Name','Customer e-mail','Country','Car Purchase Amount'],axis=1)

y=car_df['Car Purchase Amount']

X.shape

from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
X_scaled=scaler.fit_transform(X)

y=y.values.reshape(-1,1)
y_scaled=scaler.fit_transform(y)

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X_scaled,y_scaled)

import tensorflow.keras
from keras.models import Sequential
from keras.layers import Dense

model=Sequential()
model.add(Dense(25,input_dim=5,activation='relu'))
model.add(Dense(25,activation='relu'))
model.add(Dense(1,activation='linear'))

model.summary()

model.compile(optimizer='adam',loss='mean_squared_error',metrics=['accuracy'])
epochs_hist=model.fit(X_train,y_train,epochs=100,batch_size=50,verbose=1,validation_split=0.2)

epochs_hist.history.keys()

plt.plot(epochs_hist.history['loss'])
plt.plot(epochs_hist.history['val_loss'])
plt.title('Model Loss Progress During Training')
plt.ylabel('Training and Validation loss')
plt.xlabel('Epochs')

#Gender ,Age,Annual Salary,Credit Card Debt,Net Worth

y_predict=model.predict(X_test)

from keras.metrics import accuracy


from mocks import MockWorkoutController
from ui import ui_server

"""
Simple utility to run the UI/API server with a mocked controller. You can run from the project root with:
python -m test.mock_ui_driver
"""

def run():
    controller = MockWorkoutController()
    api = ui_server.SparpiServer(8888, controller)
    api.start()

if __name__ == "__main__":
    run()