from __future__ import unicode_literals

from contextlib import contextmanager
import time

from django import forms
from django.conf import settings
from django.contrib.admin import site
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import SimpleTestCase

from admin_enhancer import widgets

from .models import Book

class InteractionTest(AdminSeleniumWebDriverTestCase):
    available_apps = settings.INSTALLED_APPS

    def setUp(self):
        super(InteractionTest, self).setUp()
        User.objects.create_superuser('super', '', 'secret')

    def wait_for_popup(self, name):
        def popup_is_loaded(driver):
            return driver.current_window_handle == name
        self.wait_until(popup_is_loaded)

    @contextmanager
    def handle_popup(self, trigger):
        initial_window_handle = self.selenium.current_window_handle
        window_handles = set(self.selenium.window_handles)
        try:
            trigger()
            self.wait_until(lambda driver: set(driver.window_handles) != window_handles)
            new_window_handle = (set(self.selenium.window_handles) - window_handles).pop()
            self.selenium.switch_to.window(new_window_handle)
            yield new_window_handle
        finally:
            time.sleep(1)
            self.selenium.switch_to.window(initial_window_handle)

    def test_widget_interactions(self):
        self.admin_login('super', 'secret')
        driver = self.selenium
        driver.set_page_load_timeout(10)
        driver.get("%s%s" % (self.live_server_url, reverse('admin:tests_book_add')))

        author_select = driver.find_element_by_id('id_author')
        edit_author_btn = driver.find_element_by_id('edit_id_author')
        add_author_btn = driver.find_element_by_id('add_id_author')
        delete_author_btn = driver.find_element_by_id('delete_id_author')

        self.assertIsNone(edit_author_btn.get_attribute('href'))
        self.assertIsNone(delete_author_btn.get_attribute('href'))

        def author_options():
            author_options = author_select.find_elements_by_tag_name('option')
            options_label = []
            selected_option_label = None
            for option in author_options:
                label = option.get_attribute('innerHTML')
                options_label.append(label)
                if option.get_attribute('selected'):
                    selected_option_label = label
            return selected_option_label, options_label

        def interact(button, name):
            with self.handle_popup(button.click):
                driver.implicitly_wait(1)
                driver.find_element_by_id('id_name').clear()
                driver.find_element_by_id('id_name').send_keys(name)
                driver.find_element_by_name('_save').click()
            selected_option_label, options_label = author_options()
            self.assertEqual(['---------', name], options_label)
            self.assertEqual(name, selected_option_label)

        interact(add_author_btn, 'David Abraham')

        self.assertIsNotNone(edit_author_btn.get_attribute('href'))
        self.assertIsNotNone(delete_author_btn.get_attribute('href'))

        interact(edit_author_btn, 'David Abram')

        with self.handle_popup(delete_author_btn.click):
            driver.find_element_by_css_selector('input[type="submit"]').click()

        selected_option_label, options_label = author_options()
        self.assertEqual(['---------'], options_label)
        self.assertEqual('---------', selected_option_label)

        self.assertIsNone(edit_author_btn.get_attribute('href'))
        self.assertIsNone(delete_author_btn.get_attribute('href'))

class RelatedFieldWidgetWrapperTests(SimpleTestCase):
    def test_select_multiple_widget_cant_change_delete_related(self):
        rel = Book._meta.get_field('themes').rel
        widget = forms.SelectMultiple()
        wrapper = widgets.RelatedFieldWidgetWrapper(
            widget, rel, site,
            can_add_related=True,
            can_change_related=True,
            can_delete_related=True,
        )
        self.assertTrue(wrapper.can_add_related)
        self.assertFalse(wrapper.can_change_related)
        self.assertFalse(wrapper.can_delete_related)

    def test_on_delete_cascade_rel_cant_delete_related(self):
        rel = Book._meta.get_field('collection').rel
        widget = forms.Select()
        wrapper = widgets.RelatedFieldWidgetWrapper(
            widget, rel, site,
            can_add_related=True,
            can_change_related=True,
            can_delete_related=True,
        )
        self.assertTrue(wrapper.can_add_related)
        self.assertTrue(wrapper.can_change_related)
        self.assertFalse(wrapper.can_delete_related)


from functools import wraps
from django.http import HttpResponseRedirect
import functools
from django.core.exceptions import PermissionDenied

def view_authorized(permissions=None):

    def has_permissions(request):
        perms = []
        if permissions is not None:
            perms = permissions
        exist = {x: False for x in perms}
        for rp in request.user.profile.role.privileges.filter(privilege__in=perms):
            exist[rp.privilege] = True
        return functools.reduce(lambda a, b: a and b, exist.values())

    def wrapper(fun):

        def wrapped(request, *args, **kwargs):
            if has_permissions(request):
                return fun(request, *args, **kwargs)
            else:
                raise PermissionDenied(f"{request.method} {request.path}")
        return wrapped
    return wrapper


"""initial_empty

Revision ID: fde77a68e3dd
Revises:
Create Date: 2022-12-05 17:14:59.972979

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'fde77a68e3dd'
down_revision = None
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('bus_stops',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('stop_id', sa.String(length=10), nullable=False),
    sa.Column('number', sa.String(length=10), nullable=False),
    sa.Column('name', sa.String(length=60), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('stop_id', 'number', name='unique_stop_id_number')
    )
    op.create_table('lines',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('line_number', sa.String(length=10), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('line_number')
    )
    op.create_table('bus_stop_data',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('bus_stop_id', sa.Integer(), nullable=False),
    sa.Column('street_id', sa.String(length=20), nullable=True),
    sa.Column('geo_width', sa.String(length=20), nullable=False),
    sa.Column('geo_length', sa.String(length=20), nullable=False),
    sa.Column('direction', sa.String(length=60), nullable=True),
    sa.Column('valid_from', sa.DateTime(), nullable=False),
    sa.ForeignKeyConstraint(['bus_stop_id'], ['bus_stops.id'], ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('bus_stop_id', 'valid_from', name='unique_stop_id_date')
    )
    op.create_table('bus_stop_lines',
    sa.Column('bus_stop_id', sa.Integer(), nullable=False),
    sa.Column('line_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['bus_stop_id'], ['bus_stops.id'], ondelete='CASCADE'),
    sa.ForeignKeyConstraint(['line_id'], ['lines.id'], ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('bus_stop_id', 'line_id')
    )
    op.create_table('tables',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('brigade', sa.String(length=10), nullable=False),
    sa.Column('direction', sa.String(length=50), nullable=False),
    sa.Column('route', sa.String(length=20), nullable=False),
    sa.Column('time', sa.Time(), nullable=False),
    sa.Column('bus_stop', sa.Integer(), nullable=False),
    sa.Column('line', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['bus_stop'], ['bus_stops.id'], ondelete='CASCADE'),
    sa.ForeignKeyConstraint(['line'], ['lines.id'], ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('brigade', 'bus_stop', 'line', 'time', name='one_brigade_of_line_on_stop_at_time')
    )
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('tables')
    op.drop_table('bus_stop_lines')
    op.drop_table('bus_stop_data')
    op.drop_table('lines')
    op.drop_table('bus_stops')
    # ### end Alembic commands ###


from fastapi import APIRouter, Depends, Body
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session

import crud
import schemas
from api.deps import get_current_user, get_db
from models import User, Order, OrderElement

router = APIRouter(
    prefix='/orders',
    tags=['Orders'],
    dependencies=[Depends(get_current_user)]
)

@router.get('')
def get_orders(user: User = Depends(get_current_user)):
    orders: list[Order] = user.orders

    results = []

    for o in orders:
        elements: list[OrderElement] = o.order_elements
        cart_elements = [schemas.CartElement(
            id=e.id,
            quantity=e.quantity,
            product=schemas.CartProduct(
                id=e.product.id,
                name=e.product.name,
                price=e.product.price,
                url=e.product.url,
                description=e.product.description,
                brand=e.product.brand.name,
            )
        ) for e in elements]

        order_data: dict = jsonable_encoder(o)
        order_data['orderNumber'] = o.order_number
        order_data['orderDate'] = str(o.order_date)
        order_data['items'] = cart_elements
        order_data['customerName'] = o.customer_name
        results.append(schemas.Order(**order_data))

    return results

@router.post('')
def create_order(
        db: Session = Depends(get_db),
        user: User = Depends(get_current_user),
        dto: schemas.OrderCreate = Body()
):
    order = crud.orders.create(db, user_id=user.id, dto=dto)
    return JSONResponse({'orderId': order.id, 'orderNumber': order.order_number}, status_code=201)


# Импортируем необходимые модули
import os
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Float, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker, Session
from sqlalchemy.sql import func
from dotenv import load_dotenv

# Создаем базовый класс для объявления моделей
Base = declarative_base()

# Загружаем переменные окружения из файла .env
load_dotenv()

# Получаем URL для подключения к базе данных PostgreSQL из переменной окружения
POSTGRES_URL = os.getenv('DATABASE_URL')

# Создаем движок SQLAlchemy для работы с базой данных
engine = create_engine(POSTGRES_URL, echo=True)

# Создаем сессию для работы с базой данных
DBSession = Session(engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Функция для получения экземпляра сессии базы данных
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# Определяем модель Book, которая соответствует таблице 'book' в базе данных
class Book(Base):
    __tablename__ = 'book'
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    rating = Column(Float)
    time_created = Column(DateTime(timezone=True), server_default=func.now())
    time_updated = Column(DateTime(timezone=True), onupdate=func.now())
    author_id = Column(Integer, ForeignKey('author.id'))

    author = relationship('Author')

# Определяем модель Author, которая соответствует таблице 'author' в базе данных
class Author(Base):
    __tablename__ = 'author'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)
    time_created = Column(DateTime(timezone=True), server_default=func.now())
    time_updated = Column(DateTime(timezone=True), onupdate=func.now())


import json
import os
max_words = 1500

def readjson(input_path):
    with open(input_path, 'r', encoding="utf-8") as file:
        str = file.read()
        data = json.loads(str)
    return data

def writejson(dataset, output_path):
    with open(output_path, 'w', encoding="utf-8") as file:
        for data in dataset:
            data = json.dumps(data, ensure_ascii=False)
            file.write(data)
            file.write('\n')

def labeldata(dataset):
    ev_id = "evidence"
    ev_id += "_e" + str(dataset['id'])
    child_dataset = []
    for seg in dataset['Ev_segments']:
        seg_id = ev_id
        seg_id += ("_"+ str(seg["seg"]) +
                    "_s"+ str(seg["start"]) +
                    "_e"+str(seg["end"]))

        for truth in seg['truth_info']:
            # print(sid-seg["start"])
            answer = []
            # print(dataset['id'])
            # print(seg["start"])
            # print(seg['inter_result'])
            for ev in seg['ev_result'][str(truth['t_id'])]:
                answer.append("第"+ str(ev[0]-seg["start"]) + "句到第" + str(ev[1]-seg["start"]) + "句")

            if answer != []:
                answer = '；'.join(answer)+ "。"
            else:
                answer = ""
            prompt = {"instruction": "请在文本中找出下述待证事实对应的相关证据。{},".format(truth["info"]),
                        "input": seg["case_info"],
                        "answer": answer}

            child_dataset.append(prompt)

    return child_dataset

def main():
    input_dir = "segjson2/evseg"
    output_path = "labeldata3/train_ev.json"
    input_dir_list = os.listdir(input_dir)
    dataset = []
    for filename in input_dir_list:
        file_path = os.path.join(input_dir, filename)
        data = readjson(file_path)
        event_ev = labeldata(data)
        # print(event_ev)
        dataset.extend(event_ev)

    writejson(dataset, output_path)

if __name__ == '__main__':
    main()


from aiogram.types import InputFile
from create_bot import bot
from text import texts
import keyboard

async def send_message_start(message):
    await bot.send_video(message.from_user.id, video=InputFile(path_or_bytesio="Video.mp4"), caption=f"{texts['start']}", reply_markup=keyboard.kb_mark_main,)

async def send_message_price(message):
    await bot.send_message(message.from_user.id, texts["price"], reply_markup=keyboard.inl_kb_mark_services)

# async def send_message_inst(message):
#     await bot.send_message(message.from_user.id, texts["inst"], reply_markup=keyboard.inl_kb_mark_inst)

async def send_message_contacts(message):
    photo_file = InputFile(path_or_bytesio="locations.jpg")
    await bot.send_photo(message.from_user.id, photo=photo_file, caption=texts["contacts"], reply_markup=keyboard.inl_kb_mark_contacts)

async def send_message_queshions(message):
    await bot.send_message(message.from_user.id, texts["queshions"], reply_markup=keyboard.inl_kb_mark_queshions)

async def send_message_sign_up(message):
    await bot.send_message(message.from_user.id, texts["sign_up"], reply_markup=keyboard.inl_kb_mark_sign_up)

async def about_us_message(message):
    await bot.send_message(message.from_user.id, texts["about_us"], reply_markup=keyboard.inl_kb_mark_about)

async def edit_message_service_description(call):
    await bot.edit_message_text(
        text = texts[call.data],
        message_id = call.message.message_id,
        chat_id = call.message.chat.id,
        reply_markup=keyboard.inl_kb_mark_service_description
    )

async def edit_message_all_services(call):
    await bot.edit_message_text(
        text=texts["price"],
        message_id = call.message.message_id,
        chat_id = call.message.chat.id,
        reply_markup=keyboard.inl_kb_mark_services
    )

async def work_message(message):
    await bot.send_message(message.from_user.id, texts["work"], reply_markup=keyboard.inl_kb_mark_inst)

def register_handlers(dp):
    dp.register_message_handler(send_message_start, commands=["start"])
    dp.register_message_handler(send_message_price, lambda message: "прайс" in message.text.lower(), state=None)
    # dp.register_message_handler(send_message_inst, lambda message: "instagram" in message.text.lower(), state=None)
    dp.register_message_handler(send_message_contacts, lambda message: "контакты" in message.text.lower(), state=None)
    dp.register_message_handler(send_message_queshions, lambda message: "вопрос" in message.text.lower(), state=None)
    # dp.register_message_handler(send_message_sign_up, lambda message: "записаться" in message.text.lower(), state=None)
    dp.register_callback_query_handler(edit_message_service_description, lambda callback: callback.data in ["ser_1", "ser_2", "ser_3", "ser_4", "ser_5", "ser_6", "ser_7", "ser_8"], state=None)
    dp.register_callback_query_handler(edit_message_all_services, lambda callback: callback.data == "back", state=None)
    dp.register_callback_query_handler(send_message_sign_up, lambda callback: callback.data == "sign_up", state=None)
    dp.register_message_handler(work_message, lambda message: "наши работы до-после" in message.text.lower(), state=None)
    dp.register_message_handler(about_us_message, lambda message: "о нас" in message.text.lower(), state=None)


#!/usr/bin/env python2
from pyspeedtest import SpeedTest
from pyspeedtestconfig import credentials, timezone, logfilename
import twitter
import sys
import arrow

if __name__ == '__main__':
    api = twitter.Api(**credentials)
    st = SpeedTest()
    munits = "Mb/s"
    time = arrow.utcnow().to(timezone).format('YYYY/MM/DD HH:mm:ss')
    try:
        upload_speed = st.upload()
        formatted_upload_speed = "{:.02f}".format(upload_speed / 1000000)
        units1 = munits
    except:
        formatted_upload_speed = "ERR"
        units1 = ""
    try:
        download_speed = st.download()
        formatted_download_speed = "{:.02f}".format(download_speed / 1000000)
        units2 = munits
    except:
        formatted_download_speed = "ERR"
        units2 = ""

    status = "%s Upload: %s%s, Download: %s%s" % (time, formatted_upload_speed, units1, formatted_download_speed, units2)
    api.PostUpdate(status)
    with open(logfilename, 'a') as f:
        logline = ",".join(map(str, [arrow.utcnow().timestamp, upload_speed, download_speed]))
        f.write(logline+'\n')


"""This module defines classes directly related HTTP request processing."""

import abc
import datetime
import sys
import str_generator
from database import MySQLDatabase
from models import Session

def status_description(status_code):
    """Return description of a specified HTTP status code."""
    # Use attribute of function to avoid duplicated creation
    if not hasattr(status_description, '_http_status_description'):
        status_description._http_status_description = {
            200: 'OK',
            301: 'Moved Permanently',
            302: 'Found',
            400: 'Bad Request',
            401: 'Unauthorized',
            403: 'Forbidden',
            404: 'Not Found',
            405: 'Method Not Allowed',
            406: 'Not Acceptable',
            500: 'Internal Server Error',
            501: 'Not Implemented',
        }

    return status_description._http_status_description.\
        get(status_code, 'Unknow Status')

def status_header(status_code):
    """Return the HTTP status header of the code."""
    return '%d %s' % (status_code, status_description(status_code))

class HttpCookie(object):
    """Class that represents HTTP cookies."""

    @classmethod
    def parse_http_header(cls, header_string):
        """Parse the 'Cookie' value in HTTP request header and create an
        HttpCookie object. None is returned if failed to parse."""
        if not header_string:
            return None

        # Get parts seperated by ';'
        parts = [s.strip() for s in header_string.split(';')]

        # Get key-value pairs from parts
        data = {}
        for part in parts:
            if '=' in part:
                key, value = part.split('=')
                # Ignore reserved keys
                if key.lower() not in ['path', 'domain', 'expires']:
                    data[key] = value

        # Cookie send by client only contains data fields
        return cls(data, None, None)

    def __init__(self, data, path, expires,
                 domain=None, secure=False, httponly=False):
        """Create a cookie with its attributes. data is a dictionary that
        contains the data fields. path, expires, domain, secure, httponly
        specifiy the attributes of the cookie."""
        self.data = data
        self.path = path
        self.domain = domain
        self.expires = expires
        self.secure = secure
        self.httponly = httponly

    def http_header(self):
        """Convert this cookie to an HTTP 'Set-Cookie' header. Empty string is
        returned if no data is set to this cookie."""
        if self.data is None:
            return ''

        # Get data fields
        parts = ['%s=%s' % (k, v) for k, v in self.data.items()]

        fields = {}
        # Add path
        if self.path is not None:
            fields['Path'] = self.path

        # Add expires
        if self.expires is not None:
            expires_gmt = self.expires - datetime.timedelta(hours=8)
            fields['Expires'] = \
                expires_gmt.strftime('%a, %d %b %Y %H:%M:%S GMT')

        # Add domain
        if self.domain is not None:
            fields['Domain'] = self.domain

        # Create parts(in 'key=value' or 'key')
        parts.extend(['%s=%s' % (k, v) for k, v in fields.items()])

        # Add secure flag
        if self.secure:
            parts.append('Secure')

        # Add HTTP only flag
        if self.httponly:
            parts.append('HttpOnly')

        return '; '.join(parts)

    def __str__(self):
        """Return description of this cookie."""
        return self.http_header()

class HttpRequest(object):
    """HTTP request class that stores information of the client request."""

    def __init__(self, environ, field_storage):
        """Create request object with environment variables and cgi
        FieldStorage object."""
        # Get request parameters
        self.method = environ.get('REQUEST_METHOD')
        self.uri = environ.get('REQUEST_URI')
        self.script_name = environ.get('SCRIPT_NAME', '')
        self.client_addr = environ.get('REMOTE_ADDR')
        self.useragent = environ.get('HTTP_USER_AGENT')
        self.connection = environ.get('HTTP_CONNECTION')
        self.host = environ.get('HTTP_HOST')

        # Get content attributes
        self.content_type = environ.get('CONTENT_TYPE', None)
        self.content_length = int(environ.get('CONTENT_LENGTH', '0'))

        # Get client configuration
        self.accept_format = environ.get('HTTP_ACCEPT')
        self.accept_language = environ.get('HTTP_ACCEPT_LANGUAGE')
        self.accept_encoding = environ.get('HTTP_ACCEPT_ENCODING')
        self.cache_control = environ.get('HTTP_CACHE_CONTROL')

        # Get server informathon
        self.server_name = environ.get('SERVER_NAME')
        self.server_port = environ.get('SERVER_PORT')

        # Get cookie
        self.cookie = \
            HttpCookie.parse_http_header(environ.get('HTTP_COOKIE'))

        # Get field storage passed by cgi
        self.field_storage = field_storage

class HttpResponse(object):
    """HTTP response class that stores information of server response."""

    def __init__(self, view, **headers):
        """Create HTTP response with its view and additional headers."""
        self.view = view
        self.headers = headers

        # Get content type and store it in self.headers
        if 'Content-Type' not in self.headers:
            if self.view is not None:
                self.headers['Content-Type'] = self.view.content_type
            else:
                self.headers['Content-Type'] = 'text/html'

    def add_headers(self, headers):
        """Add extra headers to this response."""
        self.headers.update(headers)

    def add_header(self, name, value):
        """Add extra header to this response."""
        self.headers[name] = value

    def set_cookie(self, cookie):
        """Add a cookie to this response."""
        if cookie is not None:
            self.headers['Set-Cookie'] = cookie.http_header()

    def remove_header(self, header_name):
        """Remove the specified header from this response."""
        if header_name in self.headers:
            del self.headers[header_name]

    def _get_header_string(self):
        """Return the HTTP header part of this response(No extra new lines)"""
        # Construct header string
        header_list = []
        for key, value in self.headers.items():
            header_list.append('%s: %s' % (key, value))

        return '\r\n'.join(header_list)

    def write_to_output(self, out=None):
        """Write this response to out. If out is None or not presented,
        stdout will be used instead."""
        # Check the output file
        if out is None:
            out = sys.stdout

        # Generate header string and body
        header_string = self._get_header_string()
        if self.view is None:
            body = ''
        else:
            body = self.view.render_body()

        # Write everything to output
        out.write(header_string)
        out.write('\r\n\r\n')
        out.write(body)
        out.flush()

class HttpRedirectResponse(HttpResponse):
    """The HTTP response that redirects the request to another location."""

    def __init__(self, redirect_location):
        """Create redirect response with the redirecting location."""
        HttpResponse.__init__(self, None)
        self.headers['Status'] = status_header(302)
        self.headers['Location'] = redirect_location

class HttpErrorResponse(HttpResponse):
    """The HTTP response that indicates an HTTP error."""

    def __init__(self, error_code, error_view):
        """Create error response with error code and view of the error page."""
        HttpResponse.__init__(self,
                              error_view,
                              Status=status_header(error_code))

class HttpSession(object):
    """Abstract class that defines API of HTTP session."""

    __metaclass__ = abc.ABCMeta

    @classmethod
    @abc.abstractmethod
    def create_session(cls, storage, data, client_ip, effective_hours):
        """Create a new session. client_ip specifies the IP address of the
        HTTP client. effective_hours specifies effective time in hours.
        data collects the data to store in the session."""
        pass

    @classmethod
    @abc.abstractmethod
    def load_session(cls, storage, session_key):
        """Load the session with specified session key."""
        pass

    @abc.abstractmethod
    def get_session_key(self):
        """Return the key of this session."""
        pass

    @abc.abstractmethod
    def get_attribute(self, attribute_name, default=None):
        """Get attribute stored in this session with specified name."""
        pass

    @abc.abstractmethod
    def set_attribute(self, attribute_name, attribute_value):
        """Set the value of attribute with specified name."""
        pass

    @abc.abstractmethod
    def expired(self):
        """Return whether this session has expired."""
        pass

    @abc.abstractmethod
    def renew(self, effective_hours):
        """Renew the expiring time of this session."""
        pass

    @abc.abstractmethod
    def get_expire_time(self):
        """Get the expire time of this session."""
        pass

    @abc.abstractmethod
    def invalidate(self):
        """Remove this session."""
        pass

class DatabaseSession(HttpSession):
    """Http session implemented with database."""

    def __init__(self, db, model):
        """Create database session object with database and session model."""
        self.db = db
        self.model = model

    @classmethod
    def create_session(cls, db, data, client_ip, effective_hours):
        """Create a new session. client_ip specifies the IP address of the
        HTTP client. effective_hours specifies effective time in hours.
        data collects the data to store in the session."""
        # Try 3 different keys
        for trial in range(3):
            session_key = str_generator.unique_id(40)

            # Try to create session instance in database
            session_model = Session.create_session(
                db,
                session_key,
                data,
                client_ip,
                effective_hours
            )

            if session_model is not None:
                break

        # If still not created, return None
        if session_model is None:
            return None
        else:
            return DatabaseSession(db, session_model)

    @classmethod
    def load_session(cls, db, session_key):
        """Load session from database with session_key."""
        session_model = Session.load_from_database(db,
                                                   session_key=session_key)

        if session_model is None:
            return None
        else:
            return DatabaseSession(db, session_model)

    def get_session_key(self):
        """Return the key of this session."""
        return self.model['session_key']

    def get_attribute(self, attribute_name, default=None):
        """Get attribute stored in this session with specified name."""
        return self.model.get_data_attribute(attribute_name, default)

    def set_attribute(self, attribute_name, attribute_value):
        """Set the value of attribute with specified name."""
        self.model.set_data_attribute(attribute_name,
                                      attribute_value)
        self.model.store_session_data(self.db)

    def get_expire_time(self):
        """Get the expire time of this session."""
        return self.model['expire_time']

    def expired(self):
        """Return whether this session has expired."""
        return self.model.session_expired()

    def renew(self, effective_hours):
        """Renew the expiring time of this session."""
        return self.model.renew_session(self.db, effective_hours)

    def invalidate(self):
        """Remove this session."""
        self.model.delete_from_database(self.db)


"""
    AVM SmartHome Actor
    ~~~~~~~~~~~~~~~~~~~
"""

import logging
logger = logging.getLogger(__name__)

class Actor(object):
    """
    Represents a single SmartHome actor.
    You usally don't create that class yourself, use FritzBox.get_actors
    instead.
    """

    def __init__(self, fritzbox, device):
        self.box = fritzbox

        self.actor_id = device.attrib['identifier']
        self.device_id = device.attrib['id']
        self.name = device.find('name').text
        self.fwversion = device.attrib['fwversion']
        self.productname = device.attrib['productname']
        self.manufacturer = device.attrib['manufacturer']
        self.functionbitmask = int(device.attrib['functionbitmask'])

        self.has_powermeter = self.functionbitmask & (1 << 7) > 0
        self.has_temperature = self.functionbitmask & (1 << 8) > 0
        self.has_switch = self.functionbitmask & (1 << 9) > 0
        self.has_heating_controller = self.functionbitmask & (1 << 6) > 0

        self.temperature = 0.0
        if self.has_temperature:
            if device.find("temperature").find("celsius").text is not None:
                self.temperature = int(device.find("temperature").find("celsius").text) / 10
            else:
                logger.info("Actor " + self.name + " seems offline. Returning None as temperature.")
                self.temperature = None

        self.target_temperature = 0.0
        self.target_temperature = 0.0
        self.battery_low = True
        if self.has_heating_controller:
            hkr = device.find("hkr")
            if hkr is not None:
                for child in hkr:
                    if child.tag == 'tist':
                        self.temperature = self.__get_temp(child.text)
                    elif child.tag == 'tsoll':
                        self.target_temperature = self.__get_temp(child.text)
                    elif child.tag == 'batterylow':
                        self.battery_low = (child.text == '1')

    def switch_on(self):
        """
        Set the power switch to ON.
        """
        return self.box.set_switch_on(self.actor_id)

    def switch_off(self):
        """
        Set the power switch to OFF.
        """
        return self.box.set_switch_off(self.actor_id)

    def get_state(self):
        """
        Get the current switch state.
        """
        return bool(
            int(self.box.homeautoswitch("getswitchstate", self.actor_id))
        )

    def get_present(self):
        """
        Check if the registered actor is currently present (reachable).
        """
        return bool(
            int(self.box.homeautoswitch("getswitchpresent", self.actor_id))
        )

    def get_power(self):
        """
        Returns the current power usage in milliWatts.
        Attention: Returns None if the value can't be queried or is unknown.
        """
        value = self.box.homeautoswitch("getswitchpower", self.actor_id)
        return int(value) if value.isdigit() else None

    def get_energy(self):
        """
        Returns the consumed energy since the start of the statistics in Wh.
        Attention: Returns None if the value can't be queried or is unknown.
        """
        value = self.box.homeautoswitch("getswitchenergy", self.actor_id)
        return int(value) if value.isdigit() else None

    def get_temperature(self):
        """
        Returns the current environment temperature.
        Attention: Returns None if the value can't be queried or is unknown.
        """
        #raise NotImplementedError("This should work according to the AVM docs, but don't...")
        value = self.box.homeautoswitch("gettemperature", self.actor_id)
        if value.isdigit():
            self.temperature = float(value)/10
        else:
            self.temperature = None
        return self.temperature

    def __get_temp(self, value):
        # Temperature is send from fritz.box a little weird
        if value.isdigit():
            value = float(value)
            if value == 253:
                return 0
            elif value == 254:
                return 30
            else:
                return value / 2
        else:
            return None

    def get_target_temperature(self):
        """
        Returns the actual target temperature.
        Attention: Returns None if the value can't be queried or is unknown.
        """
        value = self.box.homeautoswitch("gethkrtsoll", self.actor_id)
        self.target_temperature = self.__get_temp(value)
        return self.target_temperature

    def set_temperature(self, temp):
        """
        Sets the temperature in celcius
        """

        # Temperature is send to fritz.box a little weird
        param = 16 + ( ( temp - 8 ) * 2 )
        if param < 16:
            param = 253
            logger.info("Actor " + self.name + ": Temperature control set to off")
        elif param >= 56:
            param = 254
            logger.info("Actor " + self.name + ": Temperature control set to on")
        else:
            logger.info("Actor " + self.name + ": Temperature control set to " + str(temp))

        return self.box.homeautoswitch("sethkrtsoll", self.actor_id, param)

    def get_consumption(self, timerange="10"):
        """
        Return the energy report for the device.
        """
        return self.box.get_consumption(self.device_id, timerange)

    def reset_consumption(self):
        """
        Resets the energy data stored on fritzbox for reports.
        """
        return self.box.reset_consumption(self.device_id)

    def __repr__(self):
        return u"<Actor {}>".format(self.name)


from selenium import webdriver
import time
import os

# div 模块定位
# 如果页面有多个div，需要定位的元素在某一个div里，可以优先定位这个div，在此基础上再定位该元素
driver = webdriver.Firefox()
file_path = 'file:///'+os.path.abspath("E:\\课件\\测试工具等\\selenium2html\\modal.html")
driver.get(file_path)
driver.maximize_window()
time.sleep(3)

# 点击主页的 click
driver.find_element_by_id("show_modal").click()
time.sleep(3)

# 点击 click me
div1 = driver.find_element_by_class_name("modal-body")
div1.find_element_by_link_text("click me").click()
time.sleep(3)

# 定位 close
div2 = driver.find_element_by_class_name("modal-footer")
buttons = div2.find_element_by_tag_name("button")
time.sleep(3)
buttons[0].click()
time.sleep(3)

driver.quit()


import pokepy
import asyncio

your_window_name = "mGBA - 0.10.1" #replace 0.10.1 with your version

game = pokepy.Game("mGBA - 0.10.1")

#simple code that prompts you when it's your turn to play
@game.event
async def on_combat():
    print(game.json_info)
    user_input = await asyncio.wait_for(asyncio.get_event_loop().run_in_executor(None, input, 'What you do?'), timeout=None)
    if user_input == "run":
        game.escape()
    else:
        for p in range(1,5):
            if int(user_input) == p:
                game.attack(p)
game.run()


"""
WELCOME TO GROUP'S E SUPERVISED PCA
This file contains the function PCAfunction that performs PCA on a data frame

Inputs:
    - df: DATA FRAME subject of the PCA analysis
    - colstodiscard: LIST of columns of df excluded from PCA analysis
    - accuracy: NUMERIC value to indicate the selected accuracy of PCA
Output:
    - df2: DATA FRANE that combines the output of the PCA analysis with the
    columns that were discarded from the analysis

"""

"""
Necessary imports
"""
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale

"""
PCA function. It works by:
    1) extracting the name of the columns from the data frame
    2) using those names to filter the data frame by the columns to be
    analyzed and generating another one with the columns to be discarded
    (e.g. the TARGET variable)
    3) Run PCA on the selected data frame
    4) Identify the number of columns required to achieve the desired accuracy
    and run PCA again only with those columns as output
    5) Concatenate the result of PCA analysis and data frame with filtered
    columns and return it
"""
def PCAfunction(df, colstodiscard, accuracy):
    #local variable to count optimal number for PCA
    counter=0                       #count output columns from PCA
    dfnames=df.columns.values       #obtain column names from data frame
    dfnames = [ x for x in dfnames if x not in colstodiscard ]

    #Create output DF dtry with filtered columns and DF for the PCA analysis
    dftry=df
    for i in range(len(colstodiscard)):
        df = df.drop(colstodiscard[i], axis=1)
    for i in range(len(dfnames)):
        dftry = dftry.drop(dfnames[i], axis=1)

    #Converting and scaling the DF where the PCA will run
    dfasmatrix= df.as_matrix()      #to matrix
    data=scale(dfasmatrix)          #scaled

    #running PCA, obtaining the maximum number of variables
    pca = PCA(n_components=(len(dfnames)))
    pca.fit(data)
    var1=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=4)*100)
    print(var1)
    #Use the ACCURACY parameter to draw the line of when to stop PCA
    for i in range(len(var1)):
        if(var1[i-1]<accuracy):
            counter+=1

    #Rerun PCA only selecting the n_components determined above
    pca = PCA(n_components=counter)
    pca.fit(data)
    var1=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=4)*100)
    print(var1)

    #Perform the PCA transformation
    output=pca.fit_transform(data)

    #Reshape back to DF
    df2=pd.DataFrame(data=output[0:,0:])

    #Merge the two DFs again
    for i in range(len(colstodiscard)):
        df2[colstodiscard[i]] = dftry[colstodiscard[i]]

    #return DF resulting from PCA analysis
    return df2


from sklearn.metrics import pairwise_distances
import numpy as np

class MDS:
  def __init__(self, n_components=2, max_iter=300, eps=0.001):
    self.__n_components = n_components
    self.__max_iter = max_iter
    self.__eps = eps
    self.embedding_ = None
    self.stress_ = None

  def fit(self, X):
    X_distances = pairwise_distances(X)

    new_coord = np.random.uniform(size=(X.shape[0], self.__n_components))
    alpha = 1 / X.shape[0] * np.sum(X_distances)

    for k in range(self.__max_iter):
      for i in range(X.shape[0]):
        stress_derivative = np.zeros_like(new_coord)
        for j in range(X.shape[0]):
          stress_derivative[i] += (X_distances[i,j] - np.linalg.norm(new_coord[i] - new_coord[j])) * -2 * (new_coord[i] - new_coord[j])

        new_coord[i] = new_coord[i] - alpha * self.__eps * stress_derivative[i]

    new_distances = pairwise_distances(new_coord)
    self.stress_ = np.sum((X_distances-new_distances).T @ (X_distances-new_distances))
    self.embedding_ = new_coord

    return new_coord, new_distances


import os
import server
import unittest
from unittest.mock import patch
from server import checksum
import tempfile
import logging
from lxml.etree import fromstring, tostring
from formencode.doctest_xml_compare import xml_compare

logging.basicConfig(level=logging.WARN)

class MenuSystemTestCase(unittest.TestCase):
    def setUp(self):
        self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
        server.app.config['TESTING'] = True
        self.app = server.app.test_client()

    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(server.app.config['DATABASE'])

PAYPHONE_RESPONSE = [{'properties': {
    'SSC_Name': 'Wilton',
    'Latitude': 123,
    'Longitude': 321
}}]

class TestLocation(MenuSystemTestCase):
    maxDiff = None

    def assertXMLEqual(self, first, second):
        first = fromstring(first)
        second = fromstring(second)
        try:
            self.assertTrue(xml_compare(first, second))
        except AssertionError:
            print(tostring(first))
            print(tostring(second))
            xml_compare(first, second, print)
            raise

    def test_location(self):
        self.assertXMLEqual(
            (
                b'<?xml version="1.0" encoding="UTF-8"?>'
                b'<Response>'
                b'<Gather action="/location/id_recieved" numDigits="9">'
                b'<Say language="en-AU">'
                b'Please enter the nine digit payphone identification number'
                b'</Say>'
                b'</Gather>'
                b'</Response>'
            ),
            self.app.post('/location').data
        )

    @patch('payphones.PayPhones.by_cabinet_id',
           return_value=PAYPHONE_RESPONSE)
    def test_id_recieved(self, by_cabinet_id):
        self.assertXMLEqual(
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<Response>'
            b'<Say language="en-AU">'
            b'Payphone found in Wilton'
            b'</Say>'
            b'<Gather'
            b' action="/location/payphone_found?latlon=123%2C+321"'
            b' numDigits="1">'
            b'<Say language="en-AU">'
            b'Please enter, 1 for walking instructions, or 2 for public '
            b'transportation instructions</Say>'
            b'</Gather>'
            b'</Response>',
            self.app.post(
                '/location/id_recieved',
                data={'Digits': '089458082'}
            ).data
        )

    @patch('payphones.PayPhones.by_cabinet_id',
           return_value=[])
    def test_id_recieved_phone_not_found(self, by_cabinet_id):
        self.assertXMLEqual(
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<Response>'
            b'<Say language="en-AU">'
            b'Payphone could not be found'
            b'</Say>'
            b'<Hangup/>'
            b'</Response>',
            self.app.post(
                '/location/id_recieved',
                data={'Digits': '089485082'}
            ).data
        )

    @patch('server.gmaps.directions')
    def test_payphone_found(self, directions):
        directions.return_value = [{'legs': [{'steps': [
            {
                'html_instructions': 'Move forward Station.',
                'travel_mode': 'WALKING'
            }
        ]}]}]
        self.assertXMLEqual(
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<Response>'
            b'<Say language="en-AU">Move forward Station.</Say>'
            b'<Pause length="1" />'
            b'<Say language="en-AU">End of instructions</Say>'
            b'<Gather '
                b'action="/possibly_repeat?latlon=123%2C+321&Digits=1" '
                b'numDigits="1">'
                    b'<Say language="en-AU">'
                        b'Enter 1 to repeat instructions, or hang up.'
                    b'</Say>'
            b'</Gather>'
            b'</Response>',
            self.app.post(
                '/location/payphone_found',
                query_string={'latlon': '123, 321'},
                data={'Digits': '1'}
            ).data
        )

    def test_invalid_transportation_mode(self):
        self.assertXMLEqual(
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<Response>'
            b'<Say language="en-AU">Invalid input</Say>'
            b'<Hangup />'
            b'</Response>',
            self.app.post(
                '/location/payphone_found',
                query_string={'latlon': '123, 123'},
                data={'Digits': '0'}
            ).data
        )

    def test_parse_instruction(self):
        from server import parse_instruction

        self.assertEqual(
            parse_instruction(
                'Turn right to stay on Kent St'
                '
Destination '
                'will be on the left
'
            ),
            'Turn right to stay on Kent St . Destination will be on the left .'
        )

        self.assertEqual(
            parse_instruction('Move forward Station'),
            'Move forward Station .'
        )

    def test_easter_egg(self):
        self.assertXMLEqual(
            b'<?xml version="1.0" encoding="UTF-8"?>'
            b'<Response>'
            b'<Play>/static/Gorillaz%20-%20Film%20Music%20(Official%20Visual).mp3</Play>'
            b'<Hangup/>'
            b'</Response>',
            self.app.post(
                '/location/id_recieved',
                data={'Digits': '123456789'}
            ).data
        )

class TestValidation(unittest.TestCase):
    def test_validation(self):
        res = checksum(
            'https://mycompany.com/myapp.php?foo=1&bar=2',
            {
                'CallSid': 'CA1234567890ABCDE',
                'Caller': '+14158675309',
                'Digits': '1234',
                'From': '+14158675309',
                'To': '+18005551212',
            },
            '12345'
        )

        self.assertEqual(
            res,
            'RSOYDt4T1cUTdK1PDd93/VVr8B8='
        )

if __name__ == '__main__':
    unittest.main()


import discord
from discord.ext import commands
import datetime

class STREAM_INFO(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='twitch', help='Get the Twitch channel link.')
    async def twitch_link(self, ctx):
        twitch_url = "https://www.twitch.tv/lgodhatesmel"
        await ctx.send(f"Here's the Twitch link:\n{twitch_url}")

        current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        author = ctx.message.author
        command = ctx.command.name
        print(f"{current_time} - {author.name} used the *{command}* command.")

    @commands.command(name='youtube', help='Get the YouTube channel link.')
    async def youtube_link(self, ctx):
        youtube_url = "https://www.youtube.com/@lGodHatesMel"
        await ctx.send(f"Here's the Youtube link:\n{youtube_url}")

        current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        author = ctx.message.author
        command = ctx.command.name
        print(f"{current_time} - {author.name} used the *{command}* command.")

def setup(bot):
    bot.add_cog(STREAM_INFO(bot))


from sklearn.metrics import classification_report
import torch
import json
import numpy as np
from phobert_finetuned import PhoBERT_finetuned
from transformers import AutoModel,AutoTokenizer
import random

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Load train and validation dataset
with open('content.json', 'r', encoding="utf-8") as c:
    contents = json.load(c)

tags = []
X = []

for content in contents['intents']:
    tag = content['tag']
    for pattern in content['patterns']:
        X.append(pattern)
        tags.append(tag)

tags_set = sorted(set(tags))

num_class = len(tags_set)
hidden_size = 512
phobert = AutoModel.from_pretrained('vinai/phobert-base')
tokenizer = AutoTokenizer.from_pretrained('vinai/phobert-base')
model = PhoBERT_finetuned(phobert, hidden_size=hidden_size,
                          num_class=num_class)
# model = model.to(device)

with open('test_content.json', 'r', encoding="utf-8") as c:
    contents = json.load(c)

path = 'saved_weights.pth'
model.load_state_dict(torch.load(path, map_location=torch.device('cpu')))

#func to predict input
def predict_PhoBERT(sentence):
    token = tokenizer(sentence, max_length=13, padding='max_length',
                      truncation=True)
    X_mask = torch.tensor([token['attention_mask']])
    X = torch.tensor([token['input_ids']])
    with torch.no_grad():
        preds = model(X, X_mask)
    preds = torch.argmax(preds, dim=1)
    tag = tags_set[preds.item()]
    for content in contents['intents']:
        if tag == content['tag']:
            answer = random.choice(content['responses'])
    return answer


import discord
import os
from discord import client
from discord import channel
from discord import message
#import json
#import requests
#from keep_alive import keep_alive
#COMMAND_PREFIX = "&"
client = discord.Client()

@client.event
async def on_ready():
    print("Bot is awake")
@client.event
async def on_message(message):
    msg = message.content
    if message.author.bot:
        return
    if msg.startswith("spam"):
        n = int(msg.split()[1])
        if n > 100:
            await message.channel.send(f"Uh Uh max spam limit is capped at 100")
        else:
            for i in range(n):
                await message.channel.send(f"{msg.split()[2:]}")
            await message.channel.send(f"Succesfully spammed {n} times")
client.run(os.environ.get("TOKEN"))


import urllib.request
import datetime
import json
from connection import *
from functions import *

import logging

logging.basicConfig(filename='yttracker.log', level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(__name__)

# establish db connection
connection = get_connection()

# get channels info and push to db
def channels(channel_id, api_key):
    try:
        # get api request url
        request_url = 'https://www.googleapis.com/youtube/v3/channels?id=' + channel_id + '&key=' + api_key + '&part=snippet'

        # get response from api
        with urllib.request.urlopen(request_url) as url:
            data = json.loads(url.read().decode())

            # get channel info
            channel_id = data['items'][0]['id']  # get channel id
            channel_title = data['items'][0]['snippet']['title']  # get the name displayed in channel
            thumbnails_medium_url = data['items'][0]['snippet']['thumbnails']['medium'][
                'url']  # get medium thumbnail url
            # description = data['items'][0]['snippet']['description']				            # get the description of channel
            description = ''
            joined_date = normalize_metadate(data['items'][0]['snippet']['publishedAt'])  # get joined date
            added_to_db_time = '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())  # get added to db time
            # playlist_id = get_playlist_id(channel_id)                                           # get playlist id from channel id
            try:
                location = data['items'][0]['snippet']['country']  # get location/country
            except:
                location = 'N/A'
            language = get_language(description)  # get language of channnel description

            with connection.cursor() as cursor:
                cursor.execute("""INSERT INTO channels (channel_id, channel_title, thumbnails_medium_url, description, joined_date, added_to_db_time, location, language)
                            VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
                               (channel_id,
                                channel_title,
                                thumbnails_medium_url,
                                description,
                                joined_date,
                                added_to_db_time,
                                location,
                                language
                                ))
                connection.commit()

    except Exception as err:
        logger.error(err)


from django.urls import path, include
from . import views

app_name = 'core'
urlpatterns = [
    path('', views.homepage, name="home_page"),
    path('search/', views.AssessmentSearchView.as_view(), name="search"),
    path('answer/<int:id_>', views.viewAnswers, name='view_answers'),
    path('upload/', views.upload_paper, name="upload"),
    path('upvote/<int:id_>', views.upvote, name="upvote"),
    path('downvote/<int:id_>', views.downvote, name="downvote"),
    path('assessment/<int:pk>', views.AssessmentDetailView.as_view(), name="assessment_detail_view"),
    path('hitcount/', include(('hitcount.urls', 'hitcount'), namespace='hitcount')),
    path('tagged/<slug:slug>', views.taggedAssessemnt, name='tagged'),
    path('manualQuestion/<int:id_>', views.saveQuestions, name='MsaveQ'),
    path('addtolist/<int:id_>',views.addToList, name='addtollist'),
    path('mylist/', views.viewMyList, name='myFav'),
    ]


import numpy as np
import pandas as pd
import sqlite3
from werkzeug.security import safe_str_cmp
from flask_restful import Resource, reqparse
from models.user import UserModel
from flask_restplus import abort

class CollegeData(Resource):
    parser = reqparse.RequestParser()

    parser.add_argument('caste',
        type=str,
        required=True,
        help="This field cannot be blank."
    )

    parser.add_argument('university',
        type=str,
        required=True,
        help="This field cannot be blank."
    )

    parser.add_argument('department',
        type=str,
        required=True,
        help="This field cannot be blank."
    )

    parser.add_argument('merit',
        type=int,
        required=True,
        help="This field cannot be blank."
    )

    parser.add_argument('gender',
        type=str,
        required=True,
        help="This field cannot be blank."
    )

    parser.add_argument('tfws',
        type=str,
        required=True,
        help="This field cannot be blank."
    )

    parser.add_argument('defs',
        type=str,
        required=True,
        help="This field cannot be blank."
    )

    # def get(self):
    #     df = pd.read_csv('pict_comp.csv')
    #     return{"data" :df['GOPENH'].to_json(orient='values')}

    def post(self):
        data = CollegeData.parser.parse_args()
        df = pd.read_csv('2019predicted.csv')
        cb =pd.read_csv("2013-2018 Imputed10.csv")
        cd =pd.read_csv("college Details.csv")
        category = ''

        if(data['tfws']=="true"):
            category="TFWS"
        elif(data['defs']=='true'):
            category="DEFS"
        else:
            if data and safe_str_cmp(data.gender, 'male'):
                category = 'G'
            if data and safe_str_cmp(data.gender, 'female'):
                category = 'L'
            category = category + data['caste']
            if data and safe_str_cmp(data.university, 'home'):
                category = category + 'H'
            if data and safe_str_cmp(data.university, 'other'):
                category = category + 'O'

        # if data and safe_str_cmp(data.cast, 'TFWS'):
        #     category = 'TFWS'
        # return {'data': category}

        merit= data['merit']
        years=['year_2013','year_2014','year_2015','year_2016','year_2017','year_2018']
        intyears=[2013,2014,2015,2016,2017,2018]

        # ndf=df[(df[category]>merit) & (df['Branch Name']==data['department'])].head(10)
        ndf=df.sort_values([category],ascending=['True'])[(df[category]>merit) & (df['Branch Name'].str.contains(data['department']))].head(10)
        if(ndf[category].empty):
            abort(400 ,custom='No record found')
            # return{"message":"no record found"}, 404
        ndf=ndf[['Code','Name','Branch No.',category,'college_website','lat','lon','naac']].sort_values(by=category)

        y1=[]
        for y in intyears:
            for x in ndf['Branch No.']:
                y1.append(int(cb[category][(cb['Branch No.']==x )& (cb['Year']==y)]))

        for x,y in zip(range(0,len(y1),int(len(y1)/6)),years):
            ndf[y]=y1[x:x+int(len(y1)/6)]

        ndf.rename(columns={category:'year_2019','Branch No.':'branch_no','Branch Name':'branch_name'},inplace=True)

        return{'data': ndf.to_json(orient='records')}


#!/usr/bin/env python
from Adafruit_GPIO import I2C
import logging
import time

# Register Addresses
VL53L0X_REG_SYSRANGE_START = 0x00

VL53L0X_REG_SYSTEM_THRESH_HIGH = 0x0C
VL53L0X_REG_SYSTEM_THRESH_LOW = 0x0E

VL53L0X_REG_SYSTEM_SEQUENCE_CONFIG = 0x01
VL53L0X_REG_SYSTEM_RANGE_CONFIG = 0x09
VL53L0X_REG_SYSTEM_INTERMEASUREMENT_PERIOD = 0x04

VL53L0X_REG_SYSTEM_INTERRUPT_CONFIG_GPIO = 0x0A

VL53L0X_REG_GPIO_HV_MUX_ACTIVE_HIGH = 0x84

VL53L0X_REG_SYSTEM_INTERRUPT_CLEAR = 0x0B

VL53L0X_REG_RESULT_INTERRUPT_STATUS = 0x13
VL53L0X_REG_RESULT_RANGE_STATUS = 0x14

VL53L0X_REG_RESULT_CORE_AMBIENT_WINDOW_EVENTS_RTN = 0xBC
VL53L0X_REG_RESULT_CORE_RANGING_TOTAL_EVENTS_RTN = 0xC0
VL53L0X_REG_RESULT_CORE_AMBIENT_WINDOW_EVENTS_REF = 0xD0
VL53L0X_REG_RESULT_CORE_RANGING_TOTAL_EVENTS_REF = 0xD4
VL53L0X_REG_RESULT_PEAK_SIGNAL_RATE_REF = 0xB6

VL53L0X_REG_ALGO_PART_TO_PART_RANGE_OFFSET_MM = 0x28

VL53L0X_REG_I2C_SLAVE_DEVICE_ADDRESS = 0x8A

VL53L0X_REG_MSRC_CONFIG_CONTROL = 0x60

VL53L0X_REG_PRE_RANGE_CONFIG_MIN_SNR = 0x27
VL53L0X_REG_PRE_RANGE_CONFIG_VALID_PHASE_LOW = 0x56
VL53L0X_REG_PRE_RANGE_CONFIG_VALID_PHASE_HIGH = 0x57
VL53L0X_REG_PRE_RANGE_MIN_COUNT_RATE_RTN_LIMIT = 0x64

VL53L0X_REG_FINAL_RANGE_CONFIG_MIN_SNR = 0x67
VL53L0X_REG_FINAL_RANGE_CONFIG_VALID_PHASE_LOW = 0x47
VL53L0X_REG_FINAL_RANGE_CONFIG_VALID_PHASE_HIGH = 0x48
VL53L0X_REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT = 0x44

VL53L0X_REG_PRE_RANGE_CONFIG_SIGMA_THRESH_HI = 0x61
VL53L0X_REG_PRE_RANGE_CONFIG_SIGMA_THRESH_LO = 0x62

VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD = 0x50
VL53L0X_REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI = 0x51
VL53L0X_REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_LO = 0x52

VL53L0X_REG_SYSTEM_HISTOGRAM_BIN = 0x81
VL53L0X_REG_HISTOGRAM_CONFIG_INITIAL_PHASE_SELECT = 0x33
VL53L0X_REG_HISTOGRAM_CONFIG_READOUT_CTRL = 0x55

VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD = 0x70
VL53L0X_REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI = 0x71
VL53L0X_REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_LO = 0x72
VL53L0X_REG_CROSSTALK_COMPENSATION_PEAK_RATE_MCPS = 0x20

VL53L0X_REG_MSRC_CONFIG_TIMEOUT_MACROP = 0x46

VL53L0X_REG_SOFT_RESET_GO2_SOFT_RESET_N = 0xBF
VL53L0X_REG_IDENTIFICATION_MODEL_ID = 0xC0
VL53L0X_REG_IDENTIFICATION_REVISION_ID = 0xC2

VL53L0X_REG_OSC_CALIBRATE_VAL = 0xF8

VL53L0X_REG_GLOBAL_CONFIG_VCSEL_WIDTH = 0x32
VL53L0X_REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0 = 0xB0
VL53L0X_REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_1 = 0xB1
VL53L0X_REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_2 = 0xB2
VL53L0X_REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_3 = 0xB3
VL53L0X_REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_4 = 0xB4
VL53L0X_REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_5 = 0xB5

VL53L0X_REG_GLOBAL_CONFIG_REF_EN_START_SELECT = 0xB6
VL53L0X_REG_DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD = 0x4E
VL53L0X_REG_DYNAMIC_SPAD_REF_EN_START_OFFSET = 0x4F
VL53L0X_REG_POWER_MANAGEMENT_GO1_POWER_FORCE = 0x80

VL53L0X_REG_VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV = 0x89

VL53L0X_REG_ALGO_PHASECAL_LIM = 0x30
VL53L0X_REG_ALGO_PHASECAL_CONFIG_TIMEOUT = 0x30

# Sequence Steps list
VL53L0X_SEQUENCESTEP_TCC = 0
VL53L0X_SEQUENCESTEP_DSS = 1
VL53L0X_SEQUENCESTEP_MSRC = 2
VL53L0X_SEQUENCESTEP_PRE_RANGE = 3
VL53L0X_SEQUENCESTEP_FINAL_RANGE = 4

# Check Enable list
VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE = 0
VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE = 1
VL53L0X_CHECKENABLE_SIGNAL_REF_CLIP = 2
VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD = 3
VL53L0X_CHECKENABLE_SIGNAL_RATE_MSRC = 4
VL53L0X_CHECKENABLE_SIGNAL_RATE_PRE_RANGE = 5

# Vcsel Period
VL53L0X_VCSEL_PERIOD_PRE_RANGE = 0
VL53L0X_VCSEL_PERIOD_FINAL_RANGE = 1

VL53L0X_DEVICEMODE_SINGLE_RANGING = 0
VL53L0X_DEVICEMODE_CONTINUOUS_RANGING = 1
VL53L0X_DEVICEMODE_SINGLE_HISTOGRAM = 2
VL53L0X_DEVICEMODE_CONTINUOUS_TIMED_RANGING = 3
VL53L0X_DEVICEMODE_SINGLE_ALS = 10
VL53L0X_DEVICEMODE_GPIO_DRIVE = 20
VL53L0X_DEVICEMODE_GPIO_OSC = 21

log = logging.getLogger(__name__)

class VL53L0X:
    def __init__(self, address, i2c=None):
        if i2c is None:
            i2c = I2C
        pass

        self.device = i2c.get_i2c_device(address)

        rev_id = self.get_revision_id()
        dev_id = self.get_model_id()

        # Internal Parameters
        self.device_mode = VL53L0X_DEVICEMODE_SINGLE_RANGING
        self.limit_checks_value = [0, 0, 0, 0, 0, 0]

        log.info("VL53L0X RevisionID[{0}] DeviceID[{1}]".format(hex(rev_id), hex(dev_id)))

    def calc_macro_period_ps(self, vcsel_period_pclks):
        pll_period_ps = 1655
        macro_period_vclks = 2304

        return int(macro_period_vclks * vcsel_period_pclks * pll_period_ps)

    def calc_timeout_mclks(self, timeout_period_us, vcsel_period_pclks):
        macro_period_ps = self.calc_macro_period_ps(vcsel_period_pclks)
        macro_period_ns = (macro_period_ps + 500) / 1000

        return int(((timeout_period_us * 1000) + (macro_period_ns / 2)) / macro_period_ns)

    def calc_timeout_us(self, timeout_period_mclks, vcsel_period_pclks):
        macro_period_ps = self.calc_macro_period_ps(vcsel_period_pclks)
        macro_period_ns = (macro_period_ps + 500) / 1000

        return ((timeout_period_mclks * macro_period_ns) + 500) / 1000

    def decode_timeout(self, encoded_timeout):
        return (int(encoded_timeout & 0x00FF) << int((encoded_timeout & 0xFF00) >> 8)) + 1

    def decode_vcsel_period(self, vcsel_period_reg):
        """Converts the encoded VCSEL period register value into the real period in PLL clocks"""
        return (vcsel_period_reg + 1) << 1

    def encode_timeout(self, timeout_macro_clks):
        ms_byte = 0

        if timeout_macro_clks > 0:
            ls_byte = timeout_macro_clks - 1

            while (ls_byte & 0xFFFFFF00) > 0:
                ls_byte = ls_byte >> 1
                ms_byte += 1

            return (ms_byte << 8) + (ls_byte & 0x000000FF)
        else:
            return 0

    def fixpoint1616_to_fixpoint97(self, value):
        return int((value >> 9) & 0xFFFF)

    def get_sequence_step_enables(self):
        val = self.device.readU8(VL53L0X_REG_SYSTEM_SEQUENCE_CONFIG)

        enables = {}

        enables['TccOn'] = bool(self.sequence_step_enabled(VL53L0X_SEQUENCESTEP_TCC, val))
        enables['DssOn'] = bool(self.sequence_step_enabled(VL53L0X_SEQUENCESTEP_DSS, val))
        enables['MsrcOn'] = bool(self.sequence_step_enabled(VL53L0X_SEQUENCESTEP_MSRC, val))
        enables['PreRangeOn'] = bool(self.sequence_step_enabled(VL53L0X_SEQUENCESTEP_PRE_RANGE, val))
        enables['FinalRangeOn'] = bool(self.sequence_step_enabled(VL53L0X_SEQUENCESTEP_FINAL_RANGE, val))

        return enables

    def get_sequence_step_timeout(self, step_id):
        if step_id == VL53L0X_SEQUENCESTEP_TCC or step_id == VL53L0X_SEQUENCESTEP_DSS or step_id == VL53L0X_SEQUENCESTEP_MSRC:
            current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_PRE_RANGE)
            encoded_time_out_byte = self.device.readU8(VL53L0X_REG_MSRC_CONFIG_TIMEOUT_MACROP)

            msrc_time_out_m_clks = self.decode_timeout(encoded_time_out_byte)
            return self.calc_timeout_us(msrc_time_out_m_clks, current_vcsel_pulse_period_p_clk)
        elif step_id == VL53L0X_SEQUENCESTEP_PRE_RANGE:
            current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_PRE_RANGE)
            encoded_time_out_byte = self.device.readU16(VL53L0X_REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, False)

            msrc_time_out_m_clks = self.decode_timeout(encoded_time_out_byte)
            return self.calc_timeout_us(msrc_time_out_m_clks, current_vcsel_pulse_period_p_clk)
        elif step_id == VL53L0X_SEQUENCESTEP_FINAL_RANGE:
            scheduler_sequence_steps = self.get_sequence_step_enables()
            pre_range_time_out_m_clks = 0

            if scheduler_sequence_steps['PreRangeOn']:
                current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_PRE_RANGE)
                pre_range_encoded_time_out = self.device.readU16(VL53L0X_REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, False)
                pre_range_time_out_m_clks = self.decode_timeout(pre_range_encoded_time_out)

            current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_FINAL_RANGE)
            final_range_encoded_time_out = self.device.readU16(VL53L0X_REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, False)
            final_range_time_out_m_clks = self.decode_timeout(final_range_encoded_time_out)

            final_range_time_out_m_clks -= pre_range_time_out_m_clks
            return self.calc_timeout_us(final_range_time_out_m_clks, current_vcsel_pulse_period_p_clk)
        else:
            raise ValueError("get_sequence_step_timeout received invalid step_id")

    def get_vcsel_pulse_period(self, period_type):
        if period_type == VL53L0X_VCSEL_PERIOD_PRE_RANGE:
            vcsel_period_reg = self.device.readU8(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD)
        elif period_type == VL53L0X_VCSEL_PERIOD_FINAL_RANGE:
            vcsel_period_reg = self.device.readU8(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD)
        else:
            raise ValueError("get_vcsel_pulse_period received invalid period_type")

        return self.decode_vcsel_period(vcsel_period_reg)

    def sequence_step_enabled(self, step_id, val):
        if step_id == VL53L0X_SEQUENCESTEP_TCC:
            return (val & 0x10) >> 4
        elif step_id == VL53L0X_SEQUENCESTEP_DSS:
            return (val & 0x08) >> 3
        elif step_id == VL53L0X_SEQUENCESTEP_MSRC:
            return (val & 0x04) >> 2
        elif step_id == VL53L0X_SEQUENCESTEP_PRE_RANGE:
            return (val & 0x40) >> 6
        elif step_id == VL53L0X_SEQUENCESTEP_FINAL_RANGE:
            return (val & 0x80) >> 7
        else:
            raise ValueError("sequence_step_enabled received invalid step_id")

    def set_limit_check_value(self, limit_check_id, limit_check_value):
        if limit_check_id == VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE:
            self.limit_checks_value[VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE] = limit_check_value
        elif limit_check_id == VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE:
            self.device.write16(VL53L0X_REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT,
                                self.fixpoint1616_to_fixpoint97(limit_check_value))
        elif limit_check_id == VL53L0X_CHECKENABLE_SIGNAL_REF_CLIP:
            self.limit_checks_value[VL53L0X_CHECKENABLE_SIGNAL_REF_CLIP] = limit_check_value
        elif limit_check_id == VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD:
            self.limit_checks_value[VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD] = limit_check_value
        elif limit_check_id == VL53L0X_CHECKENABLE_SIGNAL_RATE_MSRC or limit_check_id == VL53L0X_CHECKENABLE_SIGNAL_RATE_PRE_RANGE:
            self.device.write16(VL53L0X_REG_PRE_RANGE_MIN_COUNT_RATE_RTN_LIMIT,
                                self.fixpoint1616_to_fixpoint97(limit_check_value))
        else:
            raise ValueError("sequence_step_enabled received invalid step_id")

    def set_measurement_timing_budget_micro_seconds(self, measurement_timing_budget_micro_seconds):
        start_overhead_micro_seconds = 1910
        end_overhead_micro_seconds = 960
        msrc_overhead_micro_seconds = 660
        tcc_overhead_micro_seconds = 590
        dss_overhead_micro_seconds = 690
        pre_range_overhead_micro_seconds = 660
        final_range_overhead_micro_seconds = 550
        c_min_timing_budget_micro_seconds = 20000

        if measurement_timing_budget_micro_seconds < c_min_timing_budget_micro_seconds:
            measurement_timing_budget_micro_seconds = c_min_timing_budget_micro_seconds

        final_range_timing_budget_micro_seconds = measurement_timing_budget_micro_seconds - (
            start_overhead_micro_seconds + end_overhead_micro_seconds)

        sequence_steps = self.get_sequence_step_enables()

        if sequence_steps['TccOn'] or sequence_steps['MsrcOn'] or sequence_steps['DssOn']:
            msrc_dcc_tcc_timeout_micro_seconds = self.get_sequence_step_timeout(VL53L0X_SEQUENCESTEP_MSRC)

            if sequence_steps['TccOn']:
                sub_timeout = msrc_dcc_tcc_timeout_micro_seconds + tcc_overhead_micro_seconds

                if sub_timeout < final_range_timing_budget_micro_seconds:
                    final_range_timing_budget_micro_seconds -= sub_timeout
                else:
                    raise ValueError("Requested timeout too big.")

            if sequence_steps['DssOn']:
                sub_timeout = 2 * (msrc_dcc_tcc_timeout_micro_seconds + dss_overhead_micro_seconds)

                if sub_timeout < final_range_timing_budget_micro_seconds:
                    final_range_timing_budget_micro_seconds -= sub_timeout
                else:
                    raise ValueError("Requested timeout too big.")

            elif sequence_steps['MsrcOn']:
                sub_timeout = msrc_dcc_tcc_timeout_micro_seconds + msrc_overhead_micro_seconds

                if sub_timeout < final_range_timing_budget_micro_seconds:
                    final_range_timing_budget_micro_seconds -= sub_timeout
                else:
                    raise ValueError("Requested timeout too big.")

        if sequence_steps['PreRangeOn']:
            pre_range_timeout_micro_seconds = self.get_sequence_step_timeout(VL53L0X_SEQUENCESTEP_PRE_RANGE)

            sub_timeout = pre_range_timeout_micro_seconds + pre_range_overhead_micro_seconds

            if sub_timeout < final_range_timing_budget_micro_seconds:
                final_range_timing_budget_micro_seconds -= sub_timeout
            else:
                raise ValueError("Requested timeout too big.")

        if sequence_steps['FinalRangeOn']:
            final_range_timing_budget_micro_seconds -= final_range_overhead_micro_seconds

        self.set_sequence_step_timeout(VL53L0X_SEQUENCESTEP_FINAL_RANGE, final_range_timing_budget_micro_seconds)

    def set_sequence_step_timeout(self, step_id, TimeOutMicroSecs):
        if step_id == VL53L0X_SEQUENCESTEP_TCC or step_id == VL53L0X_SEQUENCESTEP_DSS or step_id == VL53L0X_SEQUENCESTEP_MSRC:
            current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_PRE_RANGE)
            msrc_range_time_out_m_clks = self.calc_timeout_mclks(TimeOutMicroSecs, current_vcsel_pulse_period_p_clk)

            if msrc_range_time_out_m_clks > 256:
                msrc_encoded_time_out = 255
            else:
                msrc_encoded_time_out = msrc_range_time_out_m_clks - 1

            self.device.write8(VL53L0X_REG_MSRC_CONFIG_TIMEOUT_MACROP, msrc_encoded_time_out)
        elif step_id == VL53L0X_SEQUENCESTEP_PRE_RANGE:
            current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_PRE_RANGE)
            pre_range_time_out_m_clks = self.calc_timeout_mclks(TimeOutMicroSecs, current_vcsel_pulse_period_p_clk)
            pre_range_encoded_time_out = self.encode_timeout(pre_range_time_out_m_clks)

            self.device.write16(VL53L0X_REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, pre_range_encoded_time_out)
        elif step_id == VL53L0X_SEQUENCESTEP_FINAL_RANGE:
            sequence_steps = self.get_sequence_step_enables()
            pre_range_time_out_m_clks = 0
            if sequence_steps['PreRangeOn']:
                current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_PRE_RANGE)
                pre_range_encoded_time_out = self.device.readU16(VL53L0X_REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, False)
                pre_range_time_out_m_clks = self.decode_timeout(pre_range_encoded_time_out)

            current_vcsel_pulse_period_p_clk = self.get_vcsel_pulse_period(VL53L0X_VCSEL_PERIOD_FINAL_RANGE)
            final_range_time_out_m_clks = self.calc_timeout_mclks(TimeOutMicroSecs, current_vcsel_pulse_period_p_clk)
            final_range_time_out_m_clks += pre_range_time_out_m_clks
            final_range_encoded_time_out = self.encode_timeout(final_range_time_out_m_clks)

            self.device.write16(VL53L0X_REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, final_range_encoded_time_out)
        else:
            raise ValueError("get_sequence_step_timeout received invalid step_id")

    # custom
    def get_model_id(self):
        return self.device.readU8(VL53L0X_REG_IDENTIFICATION_MODEL_ID)

    def get_result_range_status(self):
        return self.device.readU8(VL53L0X_REG_RESULT_RANGE_STATUS)

    def get_result_range_ambient(self):
        return self.device.readU16(VL53L0X_REG_RESULT_RANGE_STATUS + 6, False)

    def get_result_range_signal_count(self):
        return self.device.readU16(VL53L0X_REG_RESULT_RANGE_STATUS + 8, False)

    def get_result_range_disance(self):
        return self.device.readU16(VL53L0X_REG_RESULT_RANGE_STATUS + 10, False)

    def get_revision_id(self):
        return self.device.readU8(VL53L0X_REG_IDENTIFICATION_REVISION_ID)

    def measure_distance(self):
        self.set_sysrange_start(0x01)

        cnt = 0
        while (cnt < 100):  # 1 second waiting time max
            time.sleep(0.010)
            val = self.get_result_range_status()
            if (val & 0x01):
                break
            cnt += 1

        if not (val & 0x01):
            logging.warn("VL53L0X scanner not ready")

        return [self.get_result_range_disance(), self.get_result_range_signal_count()]

    def set_sysrange_start(self, val):
        val = val & 0xFF
        self.device.write8(VL53L0X_REG_SYSRANGE_START, val)


import logging
logger = logging.getLogger(__name__)
from book import book

def manual_entry() -> book:
    '''
    The user manually creates a new entry to be stored in the database.
    '''
    title = input("Please enter the title of the book (leave blank if not "
                  "known): ")
    title = title if len(title) > 0 else "UNKNOWN"
    authors = []
    i = 1
    while True:
        author_name = input(f"Please enter the name of the {i}{_i_suffix(i)} "
                            "author (leave blank to end): ")
        if author_name != '':
            authors.append(author_name)
        else:
            break
        i += 1
    authors = authors if len(authors) != 0 else ["UNKNOWN"]
    publisher = input("Please enter the name of the publisher (leave blank if "
                      "not known): ")
    publisher = publisher if len(publisher) > 0 else "UNKNOWN"
    publish_date = input("Please enter the date of publishing (leave blank if "
                         "not known): ")
    publish_date = publish_date if len(publish_date) > 0 else "UNKNOWN"
    identifiers = {
        'isbn_10': None,
        'isbn_13': None,
        'issn': None,
        'oclc': None,
        'lccn': None
    }
    for identifier in identifiers:
        while True:
            identifier_value = input(f"Please enter the {identifier.upper()} "
                                     "of the book (leave blank if not known)"
                                     ": ")
            if identifier_value == '':
                break
            try:
                identifiers[identifier] = int(identifier_value)
            except ValueError as e:
                logger.error("Invalid value provided for "
                             f"{identifier.upper()}.")
                logger.error(e)
                logger.error("Please enter a valid value!")
                continue
            break
    pages = 0
    while True:
        try:
            pages_str = input("Please enter the number of pages of this book "
                              "(leave blank if not known): ")
            pages = pages if len(pages_str) == 0 else int(pages_str)
        except ValueError as e:
            logger.error("Invalid input!")
            logger.error(e)
            logger.error("Please re-enter the number of pages!")
            continue
        break
    book_manual = book(title, authors, publisher, publish_date, identifiers,
                       pages)
    return book_manual

def _i_suffix(i: int) -> str:
    '''
    Checks the number and returns the appropriate suffix for it.
    '''
    i_str = str(i)
    suff_123 = {1: 'st', 2: 'nd', 3: 'rd'}
    suff_th = 'th'
    i_last_num = int(i_str[-1])
    return suff_123[i_last_num] if i_last_num in suff_123 else suff_th

if __name__ == "__main__":
    c = manual_entry()
    print(c)


import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from keras.datasets import fashion_mnist

# 1. 데이터
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

print(x_train.shape, y_train.shape) # (60000, 28, 28) (60000,)
print(x_test.shape, y_test.shape)   # (10000, 28, 28) (10000,)

# 정규화
x_train, x_test = x_train/255.0, x_test/255.0

# reshape 3차원을 4차원으로 늘림
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)

#실습

# 2. 모델 구성
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size= (4, 4),
                 activation='relu',
                   input_shape = (28, 28, 1)))
# model.add(MaxPooling2D(2, 2))
model.add(Conv2D(64, (4, 4), activation = 'relu' ))
model.add(MaxPooling2D(2, 2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.summary()

'''
# 3. 컴파일, 훈련

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=20, batch_size=256)

# 4. 평가, 예측
loss, acc = model.evaluate(x_test, y_test)
print('loss : ', loss)
print('acc : ', acc)

# 결과
# MaxPooling2D(2,2), Dropout(0.2)
# loss :  0.27315348386764526
# acc :  0.9052000045776367
'''


import pygame

class Menu():
    down = pygame.transform.scale(pygame.image.load("Assets/base.png"), (300, 100))
    flag = pygame.transform.scale(pygame.image.load("Assets/pngegg.png"), (600, 200))
    flag_movement = (500, 100)
    game_over = pygame.transform.scale(pygame.image.load("Assets/gameover.png"), (600, 200))
    flag_index = 0
    back = pygame.transform.scale(pygame.image.load("Assets/background-day.png"), (800, 900))
    start = pygame.transform.scale(pygame.image.load("Assets/start.png"), (100, 100))
    start_button = pygame.Rect(675, 625, 100, 100)
    option = pygame.transform.scale(pygame.image.load("Assets/menu.png"), (100, 100))
    option_button = pygame.Rect(825, 625, 100, 100)
    back_button = pygame.transform.scale(pygame.image.load("Assets/back.png"), (100, 100))
    bird_list = [
        [pygame.transform.scale(pygame.image.load("Assets/bluebird-{}flap.png".format(a)), (100, 60)) for a in
         ["up", "mid", "down"]],
        [pygame.transform.scale(pygame.image.load("Assets/redbird-{}flap.png".format(a)), (100, 60)) for a in
         ["up", "mid", "down"]],
        [pygame.transform.scale(pygame.image.load("Assets/yellowbird-{}flap.png".format(a)), (100, 60)) for a in
         ["up", "mid", "down"]]
    ]
    selected_bird = 0
    bird_index = 0
    bird_index1 = 0
    start_game_index = 0
    death = False
    started = False
    go_option = False

    def display_beginning(self, WIN):
        for i in range(2):
            WIN.blit(self.back, (i*800, 0))
        WIN.blit(self.flag, self.flag_movement)
        WIN.blit(self.bird_list[self.selected_bird][self.bird_index], (750, 420))
        WIN.blit(self.start, (675, 625))
        WIN.blit(self.option, (825, 625))
        self.handle_flag()
        self.handle_bird()
        self.start_button_fun()
        self.option_button_fun()

    def display_options(self, WIN):
        for i in range(2):
            WIN.blit(self.back, (i*800, 0))
        WIN.blit(self.flag, self.flag_movement)
        WIN.blit(self.back_button, (750, 625))
        x, y = (580, 400)
        for a in range(3):
            if a == self.selected_bird:
                WIN.blit(pygame.transform.scale(self.bird_list[a][self.bird_index], (150, 90)), (x - 25, y - 15))
            else:
                WIN.blit(self.bird_list[a][self.bird_index], (x, y))
            x += 170
        self.handle_flag()
        self.handle_bird()
        self.select_bird()
        self.back_button_fun()

    def display_death(self, WIN):
        WIN.blit(self.game_over, (500, 150))
        WIN.blit(self.start, (675, 625))
        WIN.blit(self.option, (825, 625))
        self.start_button_fun()
        self.option_button_fun()

    def select_bird(self):
        x, y = (580, 400)
        for a in range(3):
            if pygame.Rect(x, y, 100, 60).collidepoint(pygame.mouse.get_pos()):
                if pygame.mouse.get_pressed()[0]:
                    self.selected_bird = a
            x += 170

    def handle_flag(self):
        flag_list = range(-10, 11)
        if self.flag_index != 20:
            i, j = self.flag_movement
            j += flag_list[self.flag_index]
            self.flag_movement = (i, j)
            self.flag_index += 1
        else:
            i, j = self.flag_movement
            j += flag_list[self.flag_index]
            self.flag_movement = (i, j)
            self.flag_index = 0

    def handle_bird(self):
        if self.bird_index1 < 4:
            self.bird_index = 0
            self.bird_index1 += 1
        elif self.bird_index1 < 8:
            self.bird_index = 1
            self.bird_index1 += 1
        elif self.bird_index1 < 12:
            self.bird_index = 2
            self.bird_index1 += 1
        else:
            self.bird_index = 1
            self.bird_index1 = 0

    def start_button_fun(self):
        if self.start_button.collidepoint(pygame.mouse.get_pos()):
            if pygame.mouse.get_pressed()[0]:
                self.started = True

    def option_button_fun(self):
        if self.option_button.collidepoint(pygame.mouse.get_pos()):
            if pygame.mouse.get_pressed()[0]:
                self.go_option = True

    def back_button_fun(self):
        if pygame.Rect(750, 625, 100 ,100).collidepoint(pygame.mouse.get_pos()):
            if pygame.mouse.get_pressed()[0]:
                self.go_option = False
                self.death = False

    def start_game(self, WIN):
        if self.start_game_index != 20:
            for i in range(2):
                WIN.blit(self.back, (i * 800, 0))
            WIN.blit(self.bird_list[self.selected_bird][self.bird_index], (750 - self.start_game_index*30, 420))
            for j in range(7):
                WIN.blit(self.down, (j*300, 900 - self.start_game_index*5))
            self.start_game_index += 1
        elif self.start_game_index == 20:
            for i in range(2):
                WIN.blit(self.back, (i * 800, 0))
            WIN.blit(self.bird_list[self.selected_bird][self.bird_index], (750 - self.start_game_index*30, 420))
            for j in range(7):
                WIN.blit(self.down, (j*300, 900 - self.start_game_index*5))
            self.start_game_index += 1
        self.handle_bird()


import os
import coverage
import unittest
from flask.cli import FlaskGroup
from api import create_app, db

dir_path = os.path.dirname(os.path.realpath(__file__))
data_path = os.path.join(dir_path, "data")

COV = coverage.coverage(
    branch=True,
    include='api/*',
    omit=[
        'tests/*',
        'config.py',
        'api/*/__init__.py'
    ]
)
COV.start()

app = create_app()
cli = FlaskGroup(create_app=create_app)

@cli.command('test')
def test():
    """Runs the unit tests without test coverage."""
    tests = unittest.TestLoader().discover('tests', pattern='test*.py')
    result = unittest.TextTestRunner(verbosity=2).run(tests)
    if result.wasSuccessful():
        return 0
    return 1

@cli.command('cov')
def cov():
    """Runs the unit tests with coverage."""
    tests = unittest.TestLoader().discover('tests')
    result = unittest.TextTestRunner(verbosity=2).run(tests)
    if result.wasSuccessful():
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
        return 0
    return 1

@cli.command('recreate_db')
def recreate():
    db.drop_all()
    db.create_all()
    db.session.commit()

@cli.command('load')
def load_data():
    db.drop_all()
    db.create_all()
    db.session.commit()
    load_admin1_codes()
    load_admin2_codes()
    load_geonames()

def load_admin1_codes(file=None, cnx=None):
    """
    Load admin 1 codes
    :param file: input file for unit testing
    :param cnx: database connection for unit testing
    :return: None
    """
    if not file:
        file = download_and_extract('admin1CodesASCII.txt')
    with open(file, 'r', encoding='utf8') as f:
        conn = db.create_engine(cnx if cnx else app.config['SQLALCHEMY_DATABASE_URI'], {}).raw_connection()
        cursor = conn.cursor()
        cmd = '''
        COPY admin1code(code, name, name_ascii, geonameid) FROM STDIN WITH delimiter E'\t' null as ''
        '''
        cursor.copy_expert(cmd, f)
        cursor.execute(
            "UPDATE admin1code SET country_code = SPLIT_PART(code, '.', 1);"
            "UPDATE admin1code SET admin1 = SPLIT_PART(code, '.', 2);"
            "")
        conn.commit()
    if not cnx:
        print('populated the admin codes table.')

def load_admin2_codes(file=None, cnx=None):
    """
    Load admin 2 codes
    :param file: input file for unit testing
    :param cnx: database connection for unit testing
    :return: None
    """
    if not file:
        file = download_and_extract('admin2Codes.txt')
    with open(file, 'r', encoding='utf8') as f:
        conn = db.create_engine(cnx if cnx else app.config['SQLALCHEMY_DATABASE_URI'], {}).raw_connection()
        cursor = conn.cursor()
        cmd = '''
        COPY admin2code(code, name, name_ascii, geonameid) FROM STDIN WITH delimiter E'\t' null as ''
        '''
        cursor.copy_expert(cmd, f)
        cursor.execute(
            "UPDATE admin2code SET country_code = SPLIT_PART(code, '.', 1);"
            "UPDATE admin2code SET admin1 = SPLIT_PART(code, '.', 2);"
            "UPDATE admin2code SET admin2 = SPLIT_PART(code, '.', 3);"
            "")
        conn.commit()
    if not cnx:
        print('populated the admin 2 codes table.')

def load_geonames(file=None, cnx=None):
    """
    Load geonames data
    :param file: input file for unit testing
    :param cnx: database connection for unit testing
    :return: None
    """
    if not file:
        file = download_and_extract(os.getenv('GEONAMES_DATA') + ".zip")
        print("importing geonames data...")
    with open(file, 'rb') as f:
        conn = db.create_engine(cnx if cnx else app.config['SQLALCHEMY_DATABASE_URI'], {}).raw_connection()
        cursor = conn.cursor()
        cmd = '''
        COPY geoname(geonameid, name, asciiname, alternatenames, latitude, longitude, feature_class, feature_code,
        country_code, cc2, admin1, admin2, admin3, admin4, population, elevation, gtopo30, timezone, moddate)
        FROM STDIN WITH delimiter E'\t' null as ''
        '''
        cursor.copy_expert(cmd, f)
        cursor.execute(
            "UPDATE geoname SET the_geom = ST_PointFromText('POINT(' || longitude || ' ' || latitude || ')', 4326);")
        conn.commit()
    if not cnx:
        print('populated the geonames table.')

def download_and_extract(file_name):
    """
    Downloads from geoname dump and returns the local .txt file location
    :param file_name: input filename to download (.txt or .zip)
    :return: full pathname of downloaded/extracted file.
    """
    from tqdm import tqdm
    import requests
    import zipfile
    print('downloading {}...'.format(file_name))
    url = "http://download.geonames.org/export/dump/{}".format(file_name)
    if not os.path.exists(data_path):
        os.makedirs(data_path)
    dest_path = os.path.join(data_path, file_name)
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        total_size = int(r.headers.get('content-length', 0))
        block_size = 1024  # 1 kb
        t = tqdm(total=total_size, unit='iB', unit_scale=True)
        with open(dest_path, "wb") as handle:
            for data in tqdm(r.iter_content(block_size)):
                t.update(len(data))
                handle.write(data)
        t.close()
        if total_size != 0 and t.n != total_size:
            raise Exception("Error downloading {}".format(file_name))
        if ".zip" in file_name:
            with zipfile.ZipFile(dest_path, 'r') as zip_ref:
                zip_ref.extractall(data_path)
            dest_path = os.path.join(data_path, file_name.split(".zip")[0] + ".txt")
        return dest_path
    else:
        raise Exception('Error reaching Geonames server. {} {}.'.format(r.status_code, r.reason))

if __name__ == '__main__':
    cli()


from string import ascii_lowercase as letters
import secrets

class Cipher:

    def __init__(self, key = None):
        if key and (key.islower() and key.isalpha()):
            self.key = key
        else:
            self.key = "".join((secrets.choice(letters) for _ in range(100)))
        self.key_len = len(self.key)

    def encode_decode(self, text, direction):
        out = []
        for i, c in enumerate(text):
            chr_position = letters.index(c)
            shift_margin = letters.index(self.key[i % self.key_len])
            out.append(letters[(chr_position + direction * shift_margin) % 26])
        return out

    # def encode_decode(self, text, direction):
    #     return [letters[(letters.index(c) + direction * letters.index(self.key[i % self.key_len])) % 26] for i, c in enumerate(text)]

    def encode(self, plaintext):
        return "".join(self.encode_decode(plaintext, 1))

    def decode(self, encodedtext):
        return "".join(self.encode_decode(encodedtext, -1))


from django.conf.urls import url
from django.urls import path
from . import views

app_name = 'app01'

urlpatterns = [
    path('sudoku', views.app_sudoku, name='sudoku'),
    path('sudoku_solve', views.app_sudoku_solve, name='sudoku_solve'),
    path('user', views.app_user, name='user'),
    path('icons', views.app_icons, name='icons'),
    path('map', views.app_map, name='map'),
    path('maps', views.app_maps, name='maps'),
    path('notifications', views.app_notifications, name='notifications'),
    path('rtl', views.app_rtl, name='rtl'),
    path('tables', views.app_tables, name='tables'),
    path('typography', views.app_typography, name='typography'),
    path('upgrade', views.app_upgrade, name='upgrade'),
]


import logging
import json
from datetime import date

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404

# Create your views here.
from django.urls import reverse_lazy
from django.views import generic

from cash.forms import CashOnHandForm, CashOnHandModelForm
from cash.models import CashOnHand

logger = logging.getLogger(__name__)

class IndexView(PermissionRequiredMixin, generic.ListView):
    permission_required = 'cash.view_cashonhand'
    raise_exception = False
    permission_denied_message = "You are not allowed"
    # permission_required = ''
    template_name = 'cash/index.html'
    context_object_name = 'cash_list'
    paginate_by = 10

    def get_queryset(self):
        return CashOnHand.objects.all()

class DetailView(LoginRequiredMixin, generic.DetailView):
    permission_required = 'cash.view_cashonhand'
    model = CashOnHand
    context_object_name = 'cash_on_hand'
    template_name = 'cash/detail.html'

class CreateView(PermissionRequiredMixin, generic.edit.CreateView):
    permission_required = 'cash.add_cashonhand'
    # model = CashOnHand
    # fields = ['operation_date', 'serial_number', 'opposite_account', 'summary', 'lucre', 'remark']
    template_name = 'cash/add.html'
    form_class = CashOnHandModelForm
    model = CashOnHand
    success_url = reverse_lazy('cash:index')

    def get_initial(self):
        self.initial = {}
        if 'operation_date' in self.request.session:
            self.initial['operation_date'] = date.fromisoformat(self.request.session['operation_date'])
        if 'opposite_account' in self.request.session:
            self.initial['opposite_account'] = self.request.session['opposite_account']
        return self.initial

    def form_valid(self, form):
        form.instance.user = self.request.user
        self.request.session['operation_date'] = form.instance.operation_date.isoformat()
        self.request.session['opposite_account'] = form.instance.opposite_account.id
        return super().form_valid(form)

class UpdateView(generic.edit.UpdateView):
    permission_required = 'cash.change_cashonhand'
    model = CashOnHand
    fields = ['operation_date', 'serial_number', 'opposite_account', 'summary', 'lucre', 'remark']
    template_name_suffix = '_update_form'
    # template_name = 'cash/edit.html'
    success_url = reverse_lazy('cash:index')

    def form_valid(self, form):
        form.instance.user = self.request.user
        self.request.session['operation_date'] = form.instance.operation_date.isoformat()
        self.request.session['opposite_account'] = form.instance.opposite_account.id
        return super().form_valid(form)

class DeleteView(generic.edit.DeleteView):
    permission_required = 'cash.delete_cashonhand'
    model = CashOnHand
    success_url = reverse_lazy('cash:index')

@login_required
@permission_required('cash.add_cashonhand', raise_exception=True)
def login_view(request):
    return render(request, 'cash/child1.html')

def logout_view(request):
    logout(request)
    # Redirect to a success page.