import pandas as pd
import regex as re
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory

# Convert Filter File to Data Frame
df_kamus_alay = pd.read_csv('API Documentation/filter/new_kamusalay.csv', encoding='latin-1', sep=',', names=['Alay', 'Normal'])
df_kamus_alay_dict = dict(zip(df_kamus_alay.iloc[:, 0], df_kamus_alay.iloc[:, 1]))

df_stopwordbahasa = pd.read_csv('API Documentation/filter/stopwordbahasa.csv')

# Load stopwords into a set for faster lookup
stopwords = set(df_stopwordbahasa['stopword'])

# Create stemmer object
factory = StemmerFactory()
stemmer = factory.create_stemmer()

# Text Preprocessing
def preprocess_text(text):
    # Convert text to lowercase
    text = text.lower()

    # Remove emoticons and special characters
    text = re.sub(r'\\x[\da-fA-F]{2}', '', text)

    # Keep only characters from a to z (both uppercase and lowercase) and digits
    text = re.sub(r'[^a-zA-Z0-9]', ' ', text)

    # Remove excessive white spaces
    text = re.sub(r'\s+', ' ', text)

    # Remove digits or numbers
    text = re.sub(r"\b\d+\b", " ", text)

    # Remove digits from strings
    text = re.sub("\S*\d\S*", "", text).strip()

    return text

# Removing Stopwords
def remove_stopwords(text):
    return ' '.join(word for word in text.split() if word not in stopwords)

# Normalization
def normalize(text):
    words = text.split()
    normalized_words = [df_kamus_alay_dict.get(word, word) for word in words]
    return ' '.join(normalized_words)

# Stemming Words
def stem_text(text):
    return stemmer.stem(text)

# Text Cleaner Function
def cleansing_text(text):
    text = preprocess_text(text)
    text = normalize(text)
    text = remove_stopwords(text)
    text = stem_text(text)
    return text


#!/bin/python3

# A serious 2.5D game in Python3 using Pygame.
#
# Educational value may vary between:
# 1. The dangers, and basic properties of chemical combinations
# 2. salt memorising
#
# mode ideas
# learning mode: let's you play freely with the chemical components
# defender mode: is a castle defence game; the gameplay
# story mode: crazy scientist on the run against monsters with salts
#
# Game mechanics Ideas
# monster's attack each other when they are a different color (because elitism?)
# monster's chemical composition changes because of (a salt) reactions (and makes them susceptible to physical attacks)
# Monster's walk towards player, possibly replace with AI

import sys
from queue import Full
from time import sleep

import pygame
from pygame.locals import *

from events import *
from game_components import *
from configurations import *

# Input (keys, mouse)
class InputHandler:
    """handles key presses and the pointer"""
    movement_keys = ['left', 'right', 'up', 'jump']
    action_keys = {'attack': AttackEvent}
    KEYS = []

    def __init__(self, game_state):
        pygame.key.set_repeat(1, 100)
        self.active_keys = []
        self.player = None
        self.game_state = game_state

    def set_player(self, player):
        if type(player) == Player:
            self.player = player

    # player input handling
    # generates a stop throw event
    def move(self, movement):
        if self.player is not None:
            self.player.move(movement)
            if DEBUG: print(f"[IO] {self.player} moved: {movement}")
        else:
            if WARNING:
                print("[IO] movement handled while no player selected: {movement}!")

    # generates a stop throw event
    def stop_move(self, movement):
        if self.player is not None:
            self.player.stop_move(movement)
            if DEBUG: print(f"[IO] {self.player} stopped moving:: {movement}")
        else:
            if WARNING:
                print("[IO] movement handled while no player selected: {movement}!")

    # key group handling
    # Every key group has a relevant function
    def handle_key(self, id, key_event_type=None):
        if self.player is not None:
            if id in self.movement_keys:  # player movement
                self.move(id)
            elif id in self.action_keys:  # player actions
                event_handler.add(self.action_keys[id])
        else:
            if DEBUG:
                print("[IO] Event handled while no player selected, event discarded!")

    def press(self, id):
        self.handle_key(id)

    def release(self, id):
        pass

    def handle_mouse(self, id):
        pass

    keys = {}

    def handle_pygame_event(self, event):
        # todo: rebuild if-tree to seperate 'key-releasing/-pressing' and 'which key is pressed'
        if event == pygame.QUIT:
            Game.de_init()
        # keypress handling
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                Game.de_init()
            #if event.key.name in KEYS.values()
            if event.key == K_a:  # left
                self.move('left')
            elif event.key == K_d:  # right
                self.move('right')
            elif event.key == K_w:  # up
                self.move('up')
            elif event.key == K_s:  # down
                self.move('down')
            elif event.key == K_SPACE:  # down
                self.move('jump')
            elif event.key == K_t: # activate test
                if self.test:
                    self.test()
            elif event.key == K_r:
                self.game_state.init_level(1)
            elif event.key == K_f:
                self.game_state.level.freeze = not self.game_state.level.freeze
        # when a key is released, in some casescreate an event
        elif event.type == KEYUP:  # something to handle seperate key pressing and releasing
            if event.key == K_a:  # left
                self.stop_move('left')
            if event.key == K_d:  # right
                self.stop_move('right')
            if event.key == K_w:  # up
                self.stop_move('up')
            if event.key == K_s:  # down
                self.stop_move('down')
            if event.key == K_SPACE:  # down
                self.stop_move('jump')
        # mouse handling
        elif event.type == MOUSEBUTTONDOWN:
            event_handler.add(AttackEvent(attacker=self.player, pos=event.pos))

# a class which handles the initialization, resource loading, and interaction between the game components
class Game:
    """Can hold a level object, which it updates on every tick, and displays
    Levels can be hotswapped. Doesn't touch graphics handler!"""
    FPS = 30
    SOUND_RESOURCE = r''  # todo: replace with sound per image

    # Init Game state
    def __init__(self):
        assert (pygame.init(), (6, 0))  # assert all Pygame modules are loaded
        self.running = False
        self.init_sound()  # load a song for music
        self.clock = pygame.time.Clock()  # for frame control; time
        self.graphics = graphics_controller  # graphics controller
        # event_handler.start()
        self.input = InputHandler(self)  # keyboard, and mouse input
        self.active_game_components = []  # can be used to hold all on-screen game components for optimization
        # self.load_game_components()
        self.level = None
        self.meters ={'fps': None, 'player_health': None, 'kills_left':None}

    def load_resources(self):
        self.init_sound()
        # todo: make this an Event
        if self.show_fps:  # adds a fps meter to the Game state active_game_components list
            self.active_game_components.append(Meter(self.clock.get_fps, (30, 40)))

    # save, and unload game
    @staticmethod
    def de_init():
        pygame.quit()
        print("[Ga] de-init completed!")
        sys.exit()

    # load a song, ready for playing
    def init_sound(self):
        self.music = None
        try:
            self.music = pygame.mixer.Sound(Game.SOUND_RESOURCE)
        except pygame.error:
            if WARNING:
                print("[!]Sound didn't load!")

    def init_level(self, level_number):
        print(level_number)
        self.add_game_event(LoadLevelEvent(level=level_number, game_state=self))  # build, and load image
        sleep(1)

    # Event system
    def add_game_event(self, event):
        try:
            event_handler.add(event)
        except Full:
            if WARNING:
                print("[Ga] Event queue is full, event disposed: {}".format(event.TYPE))

    # handle event amount proportional to the amount of events in queue, alternatively thread it
    def handle_game_events(self):
        if event_handler.qsize() < 10:
            while not event_handler.empty():
                event = event_handler.get()
                event.handle()
        elif 20 < event_handler.qsize() >= 10:
            if WARNING:
                print("[!]queue is 10 items or more large")
            for _ in range(10):
                event = event_handler.get()
                event.handle()
        else:
            if WARNING:
                print("[!]queue seems to get big, add queue handling code")
            while not event_handler.empty():
                event = event_handler.get()
                event.handle()

    # start menu, currently sends you directly into the game
    def launch(self):
        level_number = 0
        self.graphics.init_screen()
        level_number = 1  # debugging value: -1
        self.start_game(level_number)

    # load and start game
    def start_game(self, level_n):
        level_number=level_n
        # starts music
        if self.music:
            self.music.play()

        # load the first level
        self.init_level(level_number)

        self.running = True
        loop_counter = 0
        frames_per_time = 0
        dt = [0]*15
        while self.running:
            if self.level:
                if self.level.check_level_finished():
                    level_number += 1
                    self.init_level(level_number)
            # Input mechanics
            for event in pygame.event.get():
                self.input.handle_pygame_event(event)
            event_handler.handle_events()  # calls '.handle()' on (almost) every game event in queue

            # graphics processing
            if self.level is not None:
                self.level.display()

            # time betweem frames
            dt[loop_counter] = self.clock.tick(Game.FPS)  # returns the elapsed time in milliseconds

            # update game components that aren't part of the image
            for component in self.active_game_components:
                component.update(dt[loop_counter])
            for component in self.meters.values():
                if component is not None:
                    component.display()

            # update display on screen
            pygame.display.update()

            # game mechanics
            # update game components with delta time
            # todo: make the physics simulation take into account the time till the frame is displayed
            self.level.detect_collisions()  # detect world, and character collisions
            self.level.update(dt[loop_counter])  # milliseconds
            #  detect collisions

            loop_counter += 1  # how many loops have been made
            # FPS
            if loop_counter == len(dt):  # print and start over every 15 frames
                frames_per_time = ((len(dt)/sum(dt))*1000)
                time_per_frames = 1/frames_per_time
                print((len(dt)/sum(dt)))
                if DEBUG:
                    print("[G] TPF: {}\t FPS: {}".format(time_per_frames, frames_per_time))
                loop_counter = 0
                # todo: don't put this here!
            if self.level:
                self.meters['fps'] = Text(f'FPS: {int(frames_per_time)}',
                                                        pos=(CAMERA_WIDTH - 200, 10), size=(200, 200), max_time=-1)
                self.meters['kills_left'] = Text(f'kills left: : {max(int(self.level.killed_monster-8),0)}',
                                                 pos=(10, 20), size=(200, 200), max_time=-1)
                if self.level.player:
                    self.meters['player_health'] = Text(f'HEALTH: {int(self.level.player.life_points)}',
                                              pos=(10, 100), size=(200, 200), max_time=-1)

    def test(self):
        """function for testing pygame things"""
        for component in self.level.components:
            if type(component) == Text:
                self.add_game_event(DelGameComponentEvent(level=self.level, component=component))
                break

def display_level(level_n):
    input_handler = InputHandler()

    graphics_controller.init_screen()

    class Temp:
        pass
    t = Temp()
    t.input = input_handler
    event_handler.add(LoadLevelEvent(level=level_n, game_state=t))
    event_handler.get().handle()
    level = t.level
    print('background size: {}'.format(level.rect.bottomleft))

    running = True
    dt = 0
    while running:
        # Input mechanics
        for event in pygame.event.get():
            input_handler.handle_pygame_event(event)

        while not event_handler.empty():
            event = event_handler.get()
            event.handle()

        # graphics processing
        if level is not None:
            level.display()
        # time betweem frames
        # display after waiting for fps time passed
        pygame.display.flip()

def display_level1(level_n):
    input_handler = InputHandler()
    pygame.init()

    class Temp:
        pass
    t = Temp()
    t.input = input_handler
    event_handler.add(LoadLevelEvent(level=level_n, game_state=t))
    event_handler.get().handle()
    level = t.level
    print('background size: {}'.format(level.rect.bottomleft))

    running = True
    dt = 0
    while running:
        # Input mechanics
        for event in pygame.event.get():
            input_handler.handle_pygame_event(event)

        while not event_handler.empty():
            event = event_handler.get()
            event.handle()

        # graphics processing
        if level is not None:
            level.display()
        # time betweem frames
        # display after waiting for fps time passed
        pygame.display.flip()


import glob
import os
import re

import clang.cindex as cli
import cppbind.utils.clang as cutil
from cppbind import logging
from cppbind.common.error import Error

class CXXParser:
    """
    Class is responsible for source cxx files parsing and cursor returning
    """
    CLANG_DEF_OPTIONS = cli.TranslationUnit.PARSE_SKIP_FUNCTION_BODIES | \
                        cli.TranslationUnit.PARSE_INCOMPLETE
    EXTRA_INCLUDES_FILE_NAME = "extra_includes.cpp"

    def __init__(self, processor, single_tu, filter_=None):
        self.current_file = None
        self.filter = filter_
        self.processor = processor
        self.single_tu = single_tu
        # list to keep track of which files are already processed to not process them again
        self.processed_files = []
        # current files stack which are being processed
        self.files_stack = []

    def parse_tu(self):
        """
        Parses cxx files and returns list of TranslationUnit s
        """
        return list(self.parse_x())

    def parse_tu_x(self, clang_args, include_dirs, src_glob, extra_headers, **kwargs):
        """
        Parses cxx files and returns generator of TranslationUnit s
        """
        index = cli.Index.create()
        # build parser arguments
        args = ['-x', 'c++', '--std=c++20'] + clang_args + ['-I' + includeDir.strip()
                                                            for includeDir in
                                                            include_dirs]

        logging.debug(f"Clang path: {cutil.get_libclang_full_path()}")
        logging.debug(f"Clang args: {args}")

        logging.info("parsing files: {}".format(' '.join(src_glob)))

        # using list to keep files order constant
        all_files = []
        for file in src_glob:
            files_glob = sorted(glob.glob(file.strip(), recursive=True))
            for file_path in files_glob:
                abs_fp = os.path.abspath(file_path)
                if not (self.filter and self.filter.filter_by_file(abs_fp)):
                    all_files.append(abs_fp)

        extra_includes = None
        unsaved_files = None
        if extra_headers:
            extra_includes = "\n".join(f"#include <{header}>" for header in extra_headers)
            unsaved_files = [(CXXParser.EXTRA_INCLUDES_FILE_NAME, extra_includes)]

        if self.single_tu and all_files:
            # include all src files in a virtual file to parse everything once
            includes = "\n".join(f'#include "{file}"' for file in all_files)
            if extra_includes:
                includes = extra_includes + f"\n{includes}"
            unsaved_files = [(CXXParser.EXTRA_INCLUDES_FILE_NAME, includes)]
            all_files = [CXXParser.EXTRA_INCLUDES_FILE_NAME]
        else:
            if extra_includes:
                all_files = [CXXParser.EXTRA_INCLUDES_FILE_NAME] + all_files

        for file in all_files:
            try:
                tu = index.parse(path=file,
                                 args=args,
                                 unsaved_files=unsaved_files,
                                 options=CXXParser.CLANG_DEF_OPTIONS)
            except cli.TranslationUnitLoadError as err:
                Error.critical(f"Cannot continue: cppbind error has occurred: {err}.")
            has_error = False
            for diagnostic in tu.diagnostics:
                diagnostic_error_msg = diagnostic.spelling
                if diagnostic.severity in (cli.Diagnostic.Error, cli.Diagnostic.Fatal):
                    Error.error(diagnostic_error_msg,
                                   diagnostic.location.file,
                                   diagnostic.location.line)
                    has_error = True
                else:
                    Error.warning(diagnostic_error_msg,
                                  diagnostic.location.file,
                                  diagnostic.location.line)
            if not has_error and tu.spelling not in self.processed_files:
                    # allow different files(includes) in translation unit level
                    self._process_cursor_children(tu.cursor, allow_includes=True)
                    if self.files_stack:
                        for _ in range(len(self.files_stack)):
                            self._end_process_file(self.files_stack[-1])

    def cursor_walk(self, cursor):
        """
        cursor_walk ast recursively by filtering using filter
        """
        if self.filter and self.filter.filter_cursor(cursor):
            logging.debug(f"Filtering cursor: {cursor.spelling}")
            return

        # processor current cursor
        yield cursor

        # now if needed dive into children
        if not (self.filter and self.filter.filter_cursor_children(cursor)):
            for child in cursor.get_children():
                for descendant in self.cursor_walk(child):
                    yield descendant

    def _start_process_file(self, file_name):
        logging.info(f'parsing {file_name}')
        self.files_stack.append(file_name)
        tu_parent_dirs = CXXParser.__dirs_to_process(file_name)
        # TODO:
        # currently we are not parsing the entire directory tree at once,
        # instead for each file we are going from root to leaf,
        # if there are already processed dirs then we are retrieving them from the dict,
        # later we may construct the whole source directory tree and then build the ir tree
        for dir_name in tu_parent_dirs:
            if hasattr(self.processor, 'start_dir'):
                self.processor.start_dir(dir_name)

        if hasattr(self.processor, 'start_file'):
            self.processor.start_file(file_name)

    def _end_process_file(self, file_name):
        tu_parent_dirs = CXXParser.__dirs_to_process(file_name)

        if hasattr(self.processor, 'end_file'):
            self.processor.end_file(file_name)

        if tu_parent_dirs:
            for dir_name in reversed(tu_parent_dirs):
                if hasattr(self.processor, 'end_dir'):
                    self.processor.end_dir(dir_name)

        if not self.single_tu:
            self.processed_files.append(file_name)
        self.files_stack.pop()

    def parse(self, **kwargs):
        """
        Method parses all translation units
        """
        self.parse_tu_x(**kwargs)

    @staticmethod
    def __dirs_to_process(file_name):
        if not os.path.isfile(file_name):
            return []

        dirs_to_search = set()

        root = os.path.abspath(file_name)
        while root:
            root = os.path.dirname(root)
            dir_name = os.path.relpath(root, os.getcwd())

            match = re.match(r'^[./]+$', dir_name) and dir_name != '.'
            if match:
                break
            dirs_to_search.add(dir_name)
        # sort to get root to child list
        return sorted(dirs_to_search)

    def _process_cursor(self, cursor, allow_includes=False):
        if self.filter and self.filter.filter_cursor(cursor):
            return

        # process current cursor
        if hasattr(self.processor, 'start_cursor'):
            self.processor.start_cursor(cursor)

        if callable(self.processor):
            self.processor(cursor)

        self._process_cursor_children(cursor, allow_includes)

        if hasattr(self.processor, 'end_cursor'):
            self.processor.end_cursor(cursor)

    def _process_cursor_children(self, cursor, allow_includes=False):
        current_allow_includes = cursor.kind not in (
            cli.CursorKind.NAMESPACE,
            cli.CursorKind.STRUCT_DECL,
            cli.CursorKind.CLASS_DECL,
            cli.CursorKind.CLASS_TEMPLATE,
            cli.CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION,
            cli.CursorKind.ENUM_DECL,
            cli.CursorKind.FUNCTION_DECL,
            cli.CursorKind.FUNCTION_TEMPLATE)
        for child in cursor.get_children():
            process_child = child.kind in (
                cli.CursorKind.NAMESPACE,
                cli.CursorKind.STRUCT_DECL,
                cli.CursorKind.CLASS_DECL,
                cli.CursorKind.CLASS_TEMPLATE,
                cli.CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION,
                cli.CursorKind.CONSTRUCTOR,
                cli.CursorKind.CXX_METHOD,
                cli.CursorKind.FIELD_DECL,
                cli.CursorKind.ENUM_DECL,
                cli.CursorKind.FUNCTION_DECL,
                cli.CursorKind.FUNCTION_TEMPLATE)
            if process_child:
                if child.extent.start.file:
                    file = os.path.abspath(child.extent.start.file.name)
                    # file is changed, either we ignore it if it's not allowed(e.g. include in namespace)
                    # or start/continue processing the new/not_finished file
                    current_file = self.files_stack[-1] if self.files_stack else None
                    if file != current_file:
                        # consider parent allow includes and current allow includes
                        if allow_includes and current_allow_includes:
                            # file is already started to be processed but due to includes is not finalized yet, e.g.
                            # void func1()
                            # #include "other.h"
                            # void func2()
                            if file in self.files_stack:
                                child_file = self.files_stack[-1]
                                # end included files to come to current file to be able to continue its processing
                                while file != child_file:
                                    self._end_process_file(child_file)
                                    child_file = self.files_stack[-1]
                                self._process_cursor(child, allow_includes and current_allow_includes)
                            else:
                                # file is not processed, start its processing
                                # if merge src is true we can not have duplicate files
                                if self.single_tu or file not in self.processed_files:
                                    self._start_process_file(file)
                                    self._process_cursor(child, allow_includes and current_allow_includes)
                    else:
                        # file is not changed, continue processing
                        self._process_cursor(child, allow_includes and current_allow_includes)
            else:
                self._process_cursor_children(child, allow_includes and current_allow_includes)


from flask import Blueprint

from invoice.api import BillCartApi, InvoiceAPI, CustomerInvoiceAPI, InvoiceCollectedAPI, InvoiceFailedAPI
from invoice.api import CouponCodeAPI

invoice_app = Blueprint('invoice_app', __name__)

bill_card_view = BillCartApi.as_view('bill_cart_api')
invoice_view = InvoiceAPI.as_view('invoice_api')
customer_invoice_view = CustomerInvoiceAPI.as_view('customer_invoice_api')
invoice_collected_view = InvoiceCollectedAPI.as_view('invoice_collected_api')
invoice_failed_view = InvoiceFailedAPI.as_view('invoice_failed_api')
coupon_code_view = CouponCodeAPI.as_view('coupon_api')

invoice_app.add_url_rule('/customer/<customer_id>/cart/billcart', view_func=bill_card_view, methods=['POST', ])
invoice_app.add_url_rule('/invoice/<invoice_id>', view_func=invoice_view, methods=['GET', ])
invoice_app.add_url_rule('/invoice/', view_func=invoice_view, methods=['GET', ])
invoice_app.add_url_rule('/customer/<customer_id>/invoices', view_func=customer_invoice_view, methods=['GET', ])
invoice_app.add_url_rule('/invoice/<invoice_id>/collected', view_func=invoice_collected_view, methods=['POST', ])
invoice_app.add_url_rule('/invoice/<invoice_id>/failed', view_func=invoice_failed_view, methods=['PUT', ])

invoice_app.add_url_rule('/coupon_code/', view_func=coupon_code_view, methods=['POST', ])
invoice_app.add_url_rule('/coupon_code/<code>/is_valid', view_func=coupon_code_view, methods=['GET', ])
invoice_app.add_url_rule('/coupon_code/<code>', view_func=coupon_code_view, methods=['DELETE', ])


import os
import argparse

# args option
parser = argparse.ArgumentParser()
parser.add_argument('--project_name',type=str,default='My_Project',help='The name of project')
args = parser.parse_args()

# Create Folder

folder_list = ['models','checkpoints','data','datasets','docs','options','result','scripts','test_out','util']
file_list = ['train.py','test.py']

if not os.path.isdir('./'+args.project_name):
	os.mkdir(args.project_name)
os.chdir(args.project_name)
print('Starting create folders....')
for folder_name in folder_list:
	path = './' + folder_name
	if not os.path.isdir(path):
		os.mkdir(path)
print('Successfully creating folders !')
print('Starting create files....')
for file_name in file_list:
	path = './' + file_name
	if not os.path.isfile(path):
		fd = open(path,mode='w',encoding='utf-8')
		fd.close()

print('Successfully creating files !')


import tensorflow as tf
import tflearn
import numpy as np
import pandas as pd

import matplotlib
import matplotlib.pyplot as plt
import time

matplotlib.style.use('ggplot')

# Human Activity Recognition Using Smartphones Dataset
#
# [1] Davide Anguita, Alessandro Ghio, Luca Oneto, Xavier Parra and Jorge L. Reyes-Ortiz.
# A Public Domain Dataset for Human Activity Recognition Using Smartphones.
# 21th European Symposium on Artificial Neural Networks, Computational Intelligence and Machine Learning,
# ESANN 2013. Bruges, Belgium 24-26 April 2013.
#
# http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
#
class HarData(object):
    max_timestep = 60
    output_size = 6

    @staticmethod
    def split_time(m, split_size):
        r = m.shape[0]
        extend_row_size = np.math.ceil(r / split_size) * split_size - r
        m_p = np.expand_dims(np.pad(m, [(0, extend_row_size), (0, 0)], mode='constant'), axis=0)
        result = m_p.reshape((np.math.ceil(r / split_size), split_size, m.shape[1]))
        return result

    @staticmethod
    def convert(split_size=max_timestep):
        m = pd.read_csv('har_dataset/train/X_train.txt', header=None).as_matrix()
        x_train = HarData.split_time(m, split_size)
        m = pd.read_csv('har_dataset/train/y_train.txt', header=None).as_matrix()
        y_train = HarData.split_time(tflearn.data_utils.to_categorical(m - 1, HarData.output_size), split_size)
        m = pd.read_csv('har_dataset/test/X_test.txt', header=None).as_matrix()
        x_test = HarData.split_time(m, split_size)
        m = pd.read_csv('har_dataset/test/y_test.txt', header=None).as_matrix()
        y_test = HarData.split_time(tflearn.data_utils.to_categorical(m - 1, HarData.output_size), split_size)
        pd.to_pickle([(x_train, y_train), (x_test, y_test)], 'har_data.pkl')

    @staticmethod
    def load():
        return pd.read_pickle('har_data.pkl')

class Trainer(object):
    def __init__(self, max_timestep, feature_size, output_size):
        self._max_timestep = max_timestep
        self._feature_size = feature_size
        self._output_size = output_size
        self._hidden_size = 128
        self._batch_size = 16
        self._max_epoch = 100
        self._model_path = "har_model.ckpt"
        self._create_model()

    def _create_model(self):
        # [timestep, mini-batch, feature dims]
        self._x = tf.placeholder(tf.float32, [None, None, self._feature_size])
        self._y = tf.placeholder(tf.float32, [None, None, self._output_size])
        self._index = tf.placeholder(tf.int32, [None, ])

        initializer = tf.random_uniform_initializer(-1, 1)
        cell = tf.nn.rnn_cell.LSTMCell(self._hidden_size, self._feature_size, initializer=initializer)
        cell_out = tf.nn.rnn_cell.OutputProjectionWrapper(cell, self._output_size)
        outputs, _ = tf.nn.dynamic_rnn(cell_out, self._x, sequence_length=self._index, dtype=tf.float32,
                                       time_major=True)
        output_shape = tf.shape(outputs)
        prediction = tf.nn.softmax(tf.reshape(outputs, [-1, self._output_size]))
        self._prediction = tf.reshape(prediction, output_shape)
        self._loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(tf.reshape(outputs,[-1, self._output_size]),
                                                                      tf.reshape(self._y, [-1, self._output_size])))
        #self._loss = tf.reduce_mean(tf.sqrt(tf.pow(self._prediction - self._y, 2)))  # mse
        self._optimizer = tf.train.AdamOptimizer(learning_rate=0.01).minimize(self._loss)
        correct_prediction = tf.equal(tf.argmax(self._prediction, 2), tf.argmax(self._y, 2))
        self._accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    def train(self, train_set, validation_set):
        init = tf.initialize_all_variables()
        saver = tf.train.Saver()
        train_total_size = train_set[0].shape[0]
        train_xs = train_set[0]
        train_ys = train_set[1]
        validation_total_size = validation_set[0].shape[0]
        validation_xs = np.swapaxes(validation_set[0], 0, 1)
        validation_ys = np.swapaxes(validation_set[1], 0, 1)
        train_total_batch = int(train_total_size / self._batch_size)

        # Launch the graph
        max_accuracy = 0.
        start_time = time.time()
        with tf.Session() as sess:
            sess.run(init)
            for epoch in range(self._max_epoch):
                avg_cost = 0.
                s = 0
                e = self._batch_size
                for i in range(train_total_batch):
                    sample_size = e - s
                    batch_xs = np.swapaxes(train_xs[s:e], 0, 1)
                    batch_ys = np.swapaxes(train_ys[s:e], 0, 1)
                    # TODO: adding argument for time indices
                    batch_indices = [self._max_timestep] * sample_size
                    # batch_indices = np.random.choice(max_timestep, sample_size)
                    sess.run(self._optimizer,
                             feed_dict={self._x: batch_xs, self._y: batch_ys, self._index: batch_indices})
                    cost = self._loss.eval(feed_dict={self._x: batch_xs, self._y: batch_ys, self._index: batch_indices})
                    avg_cost += cost / train_total_batch
                    s = e
                    e += self._batch_size
                    if e > train_total_size:
                        e = train_total_size

                batch_indices = [self._max_timestep] * validation_total_size
                accuracy = self._accuracy.eval(
                    feed_dict={self._x: validation_xs, self._y: validation_ys, self._index: batch_indices})
                save_message = ""
                if accuracy > max_accuracy:
                    model_path = saver.save(sess, self._model_path)
                    max_accuracy = accuracy
                    save_message = "Model saved: {}".format(model_path)
                print("Epoch: {:03d}".format(epoch + 1), "Loss: {:.5f}".format(avg_cost),
                      "Accuracy: {:.3f}".format(accuracy), save_message)

            elapsed_time = time.time() - start_time
            print("elapsed_time:", elapsed_time)

    def test(self, test_set, index=0):
        saver = tf.train.Saver()
        with tf.Session() as sess:
            saver.restore(sess, self._model_path)
            x = np.swapaxes(np.expand_dims(test_set[0][index], axis=0), 0, 1)
            y = np.swapaxes(np.expand_dims(test_set[1][index], axis=0), 0, 1)
            index = [x.shape[0]]
            y_hat = self._prediction.eval(feed_dict={self._x: x, self._y: y, self._index: index})
        return y, y_hat

def plot_output(y, y_hat):
    y = np.swapaxes(y, 0, 1)[0]
    y_hat = np.swapaxes(y_hat, 0, 1)[0]
    t = range(y.shape[0])
    plt.plot(t, y)
    plt.gca().set_prop_cycle(None)
    plt.plot(t, y_hat, ':', linewidth=2)
    plt.legend()
    plt.ylim([-0.1, 1.1])
    plt.show()

def main():
    train_set, test_set = HarData.load()
    print('Input shape:', train_set[0].shape)
    print('Output shape', train_set[1].shape)

    trainer = Trainer(HarData.max_timestep, train_set[0].shape[2], HarData.output_size)
    trainer.train(train_set, test_set)
    y, y_hat = trainer.test(test_set, 2)
    plot_output(y, y_hat)

if __name__ == '__main__':
    HarData.convert()
    main()


import sys
from functools import cache

# 1. 第二行输入 n 个整数,其中 ai 表示第 i 个文件感染的病毒编号。
# 2. 第四行输入 (m+1) 个整数, c0表示一次万能杀毒需要的时间，ci 表示使用大小为 i 的病毒库的特效杀毒需要的时间。

def read_data(source):
    N = int(next(source))
    for _ in range(N):
        n = int(next(source))
        a_lst = [int(i) for i in next(source).split()]
        print('a_lst', a_lst)
        q = int(next(source))
        q_lst = [int(i) for i in next(source).split()]
        print('q_list:', q_lst)
        yield a_lst, q_lst

def solve(n_lst, q_lst):
    print(n_lst, q_lst)
    q_len = len(q_lst) - 1

    @cache
    def dfs(idx) -> int:
        if idx >= len(n_lst):
            print('-----------')
            return 0

        ans = float('inf')
        st = {n_lst[idx]}
        i = idx + 1
        while len(st) <= q_len:
            if i == len(n_lst) or n_lst[i] not in st:
                print(f"use 病毒库：{st}, 清除了{n_lst[idx: i]}, cost: {q_lst[len(st)]}")
                ans = min(ans, dfs(i) + q_lst[len(st)])
                if i == len(n_lst):
                    break
                st.add(n_lst[i])
            i += 1
        ans = min(ans, dfs(idx + 1) + q_lst[0])
        return ans

    print(dfs(0))

for x in read_data(sys.stdin):
    solve(x[0], x[1])
# solve([1, 2, 3, 4, 1, 1, 1], [4, 5, 6, 7])


import matplotlib.pyplot as plt
import mpmath as mp
from scipy.special import eval_legendre
from scipy.special import roots_legendre
from scipy.special import erf
import numpy as np
import pandas as pd

#-----------------------------------------Parameters---------------------------------------#

e2= 1.44
Ap= 1
At= 12
zp= 1
zt= 6
h2mu=20.736*(Ap+At)/(Ap*At)
a=8 #leer
V0=73.8
R0=2.70
l=0

#-------------------------------Legendre roots and function--------------------------------#

def root(x):  #zeros legendre
    zero=roots_legendre(x)[0]
    xi=(zero+1)/2
    return xi

def L(N,x): #eval legendre function
    b=eval_legendre (N,x)
    return b

def f(N): #Regulazed Legendre functions evaluated in a
    M=[]
    zerosN=root(N)
    k=0
    for xi in zerosN:
        p=(-1)**(N+k+1)*(1/xi)*(a*xi*(1.-xi))**(1./2)*1/(a-a*xi)
        k=k+1
        M.append(p)
    MM=np.array(M)
    return MM

#----------------------------------------Potential--------------------------------------------#

def V(x,l):
    aa=Vn(x)
    bb=Vc(x)
    cc=Vl(x,l)
    return aa+bb +cc

def Vl(x,l):
    cent=h2mu*l*(l+1)/(x*x)
    return cent

def Vn(x):
    xx=(x/R0)**2
    VN=-V0*np.exp(-xx)
    return VN

"""
    if x>R0:
        a=4*e/x
    else:
        a=4*(e/(2*R0))*(3-np.power(x/R0,2))
    return a
"""
def Vc(x):
    a=zp*zt*e2/x
    return a
#--------------------------------------Matrix-------------------------------------------------#

def Cmatrix(zeros1,zeros2,a,N,E): #Matrix Elements
	A = np.matrix(np.zeros((N, N), dtype = np.float))
	N=float(N)
	i=0
	for xi in zeros2:
		j=0
		for xj in zeros1:
			if xi!=xj:
				element=((-1)**(i+j)/(a**2*(xi*xj*(1.-xi)*(1.-xj))**(0.5)))*(N**2+N+1+(xi+xj-2*xi*xj)/(xi-xj)**2-1./(1.-xi)-1./(1.-xj))
				A[i,j]=element*h2mu
			elif xi==xj:
				A[i,j]=((4*N**2+4*N+3)*xi*(1-xi)-6*xi+1)/(3*a**2*xi**2*(1-xi)**2)*h2mu+V(a*xi,l)-E
			j=j+1
		i=i+1
	return A

#--------------------------------------R-Matrix-------------------------------------------------#
def RE(x,N):
	zeros1=root(N)
	zeros2=root(N)
	Regulazed_Legendre_functions=f(N)
	C=Cmatrix(zeros1,zeros2,a,N,x)                              #C matrix
	Cinv = np.linalg.inv(C)                                     #C inverse matrix
	RE1=np.dot(Cinv,Regulazed_Legendre_functions)               #Dot matrix vector
	p=RE1.tolist()[0]
	RE2=np.array(p)
	REa=(h2mu/a)*Regulazed_Legendre_functions.dot(RE2)          #R-matrix
	return REa
#------------------------------------Scattering matrix------------------------------------------#
def F(l,eta,x):                                   #F Coulumb function
    Fc=mp.coulombf(l,eta,x)
    return Fc

def G(l,eta,x):                                   #G Coulumb function
    Gc=mp.coulombg(l,eta,x)
    return Gc

def derivateH(m,l,eta,x):                         #Derivate of a function
    dx=1e-10
    h=(H(m,l,eta,x+dx/2)-H(m,l,eta,x-dx/2))/dx
    return h

def H(m,l,eta,x):                                 #Coulumb Hankel (+,-) function
    if m==1:
        h=G(l,eta,x)+1j*F(l,eta,x)
    else:
        h=G(l,eta,x)-1j*F(l,eta,x)
    return h

def U(l,eta,x,E,N):                                 #Scattering matrix
    ul=(H(0,l,eta,x)-x*RE(E,N)*derivateH(0,l,eta,x))/(H(1,l,eta,x)-x*RE(E,N)*derivateH(1,l,eta,x))
    return ul

#---------------------------------------Phase shifts (in degrees)------------------------------------------#

def angle(i,l,N):
	k=(i/h2mu)**(1./2)
	eta=zp*zt*e2/(2*k*h2mu)
	scatterM=U(l,eta,k*a,i,N)
	y=float(scatterM.imag)
	x=float(scatterM.real)
	alpha=np.arctan2(y,x)/2
	if alpha<0:
		alpha=alpha+np.pi
	deg=np.degrees(alpha)
	return deg

#---------------------------------------------------Plot-------------------------------------------------#
E=np.arange(0.01,2,0.02)
Angle=[]
for j in 7,10:
	M=[]
	for i in E:
		shift=angle(i,l,j)
		print(j,i,shift)
		M.append(shift)
	Angle.append(M)

plt.plot(E,Angle[0],label="N=7")
plt.plot(E,Angle[1],label="N=10")
plt.legend()
plt.show()

"""
def DF(l,eta,x):                         #Fs Derivate
	dx=0.000000001
	h=(F(l,eta,x+dx/2)-F(l,eta,x-dx/2))/dx
	return h

def DG(l,eta,x):                         #Gs Derivate
	dx=0.000000001
	h=(G(l,eta,x+dx/2)-G(l,eta,x-dx/2))/dx
	return h

"""

"""

def Pl(l,eta,x,E):
	f=F(l,eta,x)
	g=G(l,eta,x)
	P=(x)/(f**2+g**2)
	return P

def Sl(l,eta,x,E):
	f=F(l,eta,x)
	g=G(l,eta,x)
	ff=DF(l,eta,x)
	gg=DG(l,eta,x)
	S=(x)/(f**2+g**2)*(f*ff+g*gg)
	return S

def angle(i,N):
	k=(i/h2mu)**(1./2)
	B=0
	eta=zp*zt*e2/(2*k*h2mu)
	uu=-1*np.arctan(0.005)
	u1=float(F(l,eta,k*a)/G(l,eta,k*a))
	u11=np.arctan(u1)
	u2=float((Pl(l,eta,k*a,i)*RE(i,N))/(1-(Sl(l,eta,k*a,i)-B)*RE(i,N)))
	phi=-np.arctan(u1)+np.arctan(u2)
	return phi

E=np.arange(0.01,2,0.02)
ANGLE=[]
for i in E:
	shift=angle(i,7)
	if shift<0:
		shift=shift+np.pi
	shift1=np.degrees(shift)
	print(i,shift1)
	ANGLE.append(shift1)

ANGLE2=[]
for i in E:
	shift=angle(i,10)
	if shift<0:
		shift=shift+np.pi
	shift1=np.degrees(shift)
	print(i,shift1)
	ANGLE2.append(shift1)

plt.title("Alpha shift")
plt.xlabel("E(MeV)")
plt.plot(E,ANGLE,label="N=7")
plt.plot(E,ANGLE2,label="N=10")
plt.legend()
plt.show()

"""


import cv2

cap = cv2.VideoCapture(0)
while (cap.isOpened()):
  ret,img = cap.read()
  cv2.imshow('my win',img)
  img_canny = cv2.Canny(img, 30, 70)
  cv2.imshow('canny',img_canny)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cap.release()
cv2.destroyAllWindows()


#
# @lc app=leetcode.cn id=55 lang=python3
#
# [55] 跳跃游戏
#
# https://leetcode-cn.com/problems/jump-game/description/
#
# algorithms
# Medium (37.00%)
# Likes:    411
# Dislikes: 0
# Total Accepted:    49.7K
# Total Submissions: 133.2K
# Testcase Example:  '[2,3,1,1,4]'
#
# 给定一个非负整数数组，你最初位于数组的第一个位置。
#
# 数组中的每个元素代表你在该位置可以跳跃的最大长度。
#
# 判断你是否能够到达最后一个位置。
#
# 示例 1:
#
# 输入: [2,3,1,1,4]
# 输出: true
# 解释: 我们可以先跳 1 步，从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
#
#
# 示例 2:
#
# 输入: [3,2,1,0,4]
# 输出: false
# 解释: 无论怎样，你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 ， 所以你永远不可能到达最后一个位置。
#
#
#

# @lc code=start

from typing import List

class Solution:
    def canJump(self, nums: List[int]) -> bool:

        # # 2019-12-28 19:50:33
        # # Time Limit Exceeded
        # # 72/75 cases passed (N/A)
        # if len(nums) == 1: return True
        # len_nums = len(nums)

        # def dfs(location):
        #     if location >= len_nums: return False
        #     if location == len_nums - 1: return True
        #     for i in range(nums[location], 0, -1):
        #         if dfs(location + i): return True
        #     return False

        # return dfs(0)

        # # # 2019-12-28 20:39:04
        # # Time Limit Exceeded
        # # 74/75 cases passed (N/A)
        # if len(nums) == 1: return True
        # len_nums = len(nums)
        # is_location_valid = [None for _ in range(len_nums)]

        # def dfs(location):
        #     if location >= len_nums: return False
        #     if location == len_nums - 1: return True
        #     if is_location_valid[location] is False: return False
        #     if is_location_valid[location] is True: return True

        #     for i in range(nums[location], 0, -1):
        #         if dfs(location + i):
        #             is_location_valid[location] = True
        #             return True

        #     is_location_valid[location] = False
        #     return False

        # return dfs(0)

        # # # 2019-12-28 20:39:04
        # # Time Limit Exceeded
        # # 74/75 cases passed (N/A)
        # if len(nums) == 1: return True
        # len_nums = len(nums)
        # is_location_valid = [None for _ in range(len_nums)]

        # def dfs(location):
        #     if location >= len_nums: return False
        #     if location == len_nums - 1: return True
        #     if is_location_valid[location] is False: return False
        #     if is_location_valid[location] is True: return True

        #     for i in range(nums[location], 0, -1):
        #         if dfs(location + i):
        #             is_location_valid[location] = True
        #             return True

        #     is_location_valid[location] = False
        #     return False

        # return dfs(0)

        # # 2019-12-28 21:03:32
        # # 找到关键位置
        # len_nums = len(nums)
        # end_reachable = len_nums - 1
        # for i in range(len_nums - 1, -1, -1):
        #     if i + nums[i] >= end_reachable:
        #         end_reachable = i

        # return end_reachable == 0

        # 2019-12-28 21:03:40
        # 要点: 如果i可以到达, 那么所有{j|j<i}也可以到达
        max_reachable = 0
        for i, n in enumerate(nums):
            if i > max_reachable: return False
            max_reachable = max(i + n, max_reachable)
            # if max_reachable >= len(nums) - 1: return True  # shortcut, 注意len(nums)本身也是O(N)

        return True

# def main():
#     s = Solution()
#     assert s.canJump([2, 0])
#     assert s.canJump([2, 0, 0])
#     assert s.canJump([3, 2, 1, 0, 4]) is False
#     assert s.canJump([2, 3, 1, 1, 4]) is True
#     assert s.canJump([2, 0, 6, 9, 8, 4, 5, 0, 8, 9, 1, 2, 9, 6, 8, 8, 0, 6, 3, 1, 2, 2, 1, 2, 6, 5, 3, 1, 2, 2, 6, 4, 2, 4, 3, 0, 0, 0, 3, 8, 2, 4, 0, 1, 2, 0, 1, 4, 6, 5, 8, 0, 7, 9, 3, 4, 6, 6, 5, 8, 9, 3, 4, 3, 7, 0, 4, 9, 0, 9, 8, 4, 3, 0, 7, 7, 1, 9, 1, 9, 4, 9, 0, 1, 9, 5, 7, 7, 1, 5, 8, 2, 8, 2, 6, 8, 2, 2, 7, 5, 1, 7, 9, 6]) is False

# if __name__ == '__main__':
#     main()

# @lc code=end


import os
from setuptools import find_packages, setup
from esi import __version__

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='adarnauth-esi',
    version=__version__,
    install_requires=[
        'requests>=2.9.1,<3.0',
        'requests_oauthlib>=0.8.0,<1.0',
        'django>=1.10',
        'bravado>=8.4.0,<10.0',
        'celery>=4.0.2',
    ],
    packages=find_packages(),
    include_package_data=True,
    license='GNU General Public License v3 (GPLv3)',
    description='Django app for accessing the EVE Swagger Interface.',
    long_description=README,
    url='https://github.com/adarnof/adarnauth-esi',
    author='Adarnof',
    author_email='adarnof@gmail.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.10',
        'Framework :: Django :: 1.11',
        'Framework :: Django :: 2.0',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


from typing import Any, Dict, Union

from pydantic import BaseModel

class HttpExceptionModel(BaseModel):
    detail: str

def add_to_openapi_doc(code_pair: Dict[int, str]) -> Dict[int, Dict[str, Any]]:
    return {
        code: {
            "description": detail,
            "model": HttpExceptionModel,
        }
        for code, detail in code_pair.items()
    }


from django.test import TestCase
from django.urls import resolve
from lists.views import home_page
from django.http import HttpRequest
from django.template.loader import render_to_string
from lists.models import Item, List

# Create your tests here.
class HomePageTest(TestCase):
    # def test_root_url_resolves_to_home_page_view(self):
    #     found = resolve('/')
    #     self.assertEqual(found.func, home_page)

    def test_uses_home_template(self):
        #request = HttpRequest() #创建了一个HttpRequest对象。用户请求网页，django中看到的就是这个对象
        #response = home_page(request)#把这个httprequest对象传给home_page视图，得到响应。
        #用test client代替httpresponse对象，也不再直接调用视图函数，用self,client.get
        response = self.client.get('/')
        html = response.content.decode('utf8')#提取响应的.content，得到的结果是原始字节，即0和1。
        #expected_html = render_to_string('home.html') #用render_to_String手动渲染
        #self.assertEqual(html,expected_html)
        # decode用来把原始字节转换成发给用户的html字符串
        # self.assertTrue(html.startswith('')) #希望响应以标签开头，并在结尾处关闭该标签
        # self.assertIn('<title>To-Do lists</title>', html)#希望响应中有一个<title>标签，内容包含单词To-Do Lists
        # self.assertTrue(html.endswith(''))#希望响应以标签结尾
        self.assertTemplateUsed(response,'home.html') #assertTemplateUsed用于检查响应是哪个模板渲染的

    def test_only_saves_items_when_necessary(self):
        self.client.get('/')
        self.assertEqual(Item.objects.count(),0)

    # def test_displays_all_list_item(self):
    #     Item.objects.create(text = 'itemey 1')
    #     Item.objects.create(text = 'itemey 2')
    #     response = self.client.get('/')
    #     self.assertIn('itemey 1',response.content.decode())
    #     self.assertIn('itemey 2',response.content.decode())

class NewListTest(TestCase):
    def test_can_save_a_POST_request(self):
        #发送post请求，data指定想发送的表单数据
        self.client.post('/',data= {'item_text':'A new list item'})
        #检查视图是否把新添加的待办事项存入数据库
        # self.assertEqual(Item.objects.count(),1)
        #objects.all()[0]
        new_item = Item.objects.first()
        #检查待办事项的文本是否正确
        # self.assertEqual(new_item.text,'A new list item')
        #检查post请求渲染得到的html中是否有指定的文本
        #self.assertIn('A new list item',response.content.decode())
        #self.assertTemplateUsed(response, 'home.html')  # 检查是否依然使用这个模板

        # self.assertEqual(response.status_code,302)
        # self.assertEqual(response['location'],'/')

    def test_redirects_after_POST(self):
        # 不再拿响应中的content属性值和渲染模板的值比较
        # 现在比较重新定向
        response = self.client.post('/lists/new',data= {'item_text':'A new list item'})
        new_list = List.objects.first()
        # self.assertEqual(response.status_code, 302)
        # self.assertEqual(response['location'], '/')
        # self.assertEqual(response['location'], '/lists/the-only-list-in-the-world/')
        self.assertRedirects(response,f'/lists/{new_list.id}/')

class ListAndItemModelTest(TestCase):
    def test_saving_and_retrieving_items(self):
        list_ = List()
        list_.save()
        #	3. 在数据库中创建新纪录：创建一个对象；为一些属性赋值；调用.save()函数
        first_item = Item()
        first_item.text = 'The first (ever) list item'
        first_item.list = list_
        first_item.save()

        second_item = Item()
        second_item.text = 'Item the second'
        second_item.list = list_
        second_item.save()

        saved_list = List.objects.first()
        self.assertEqual(saved_list,list_)

        #django提供了一个查询数据库的API,即类.objects，.all()是查询方法，返回类似列表的对象，叫QuerySet
        saved_items = Item.objects.all()
        self.assertEqual(saved_items.count(),2)
        first_saved_item = saved_items[0]
        second_saved_item = saved_items[1]

        self.assertEqual(first_saved_item.text,'The first (ever) list item')
        self.assertEqual(first_saved_item.list, list_)
        self.assertEqual(second_saved_item.text,'Item the second')
        self.assertEqual(second_saved_item.list,list_)

class ListViewTest(TestCase):
    def test_uses_list_template(self):
        list_ = List.objects.create()
        response = self.client.get(f'/lists/{list_.id}/')
        self.assertTemplateUsed(response,'list.html')

    def test_displays_only_items_for_that_list(self):
        correct_list = List.objects.create()
        Item.objects.create(text = 'itemey 1', list = correct_list)
        Item.objects.create(text = 'itemey 2',list = correct_list)

        other_list = List.objects.create()
        Item.objects.create(text='other list item 1', list=other_list)
        Item.objects.create(text='other list item 2', list=other_list)

        response = self.client.get(f'/lists/{correct_list.id}/')
        # self.assertContains(response,'itemey 1') #判断响应里面包含这个字符串，assertContains会处理字节，不用额外的decode
        # self.assertContains(response,'itemey 2')
        self.assertNotContains(response, 'other list item 1')
        self.assertNotContains(response, 'other list item 2')

    def test_passes_correct_list_to_template(self):
        other_list = List.objects.create()
        correct_list = List.objects.create()
        response = self.client.get(f'/lists/{correct_list.id}/')
        #response.context表示要传入render函数的上下文
        self.assertEqual(response.context['list'],correct_list)

class NewItemTest(TestCase):
    def test_can_save_a_POST_request_to_an_existing_list(self):
        other_list = List.objects.create()
        correct_list = List.objects.create()
        self.client.post(f'/lists/{correct_list.id}/add_item',
                         data = {'item_text':'A new item for an existing list'})

        self.assertEqual(Item.objects.count(),1)
        new_item = Item.objects.first()

        self.assertEqual(new_item.text,'A new item for an existing list')
        self.assertEqual(new_item.list,correct_list)

    def test_redirects_to_list_view(self):
        other_list = List.objects.create()
        correct_list = List.objects.create()
        response = self.client.post(f'/lists/{correct_list.id}/add_item',
                                    data = {'item_text':'A new item for an existing list'})

        self.assertRedirects(response,f'/lists/{correct_list.id}/')


from django.urls import path, include

from . import views

app_name = 'material'
urlpatterns = [
    path('', views.index, name='index'),
    path('selected_nature/<int:nature_id>', views.index, name='index_nature'),
    path('selected_pattern/<int:pattern_id>', views.index, name='index_pattern'),
    path('nature/<int:pk>/', views.index, name='nature-details'),
    path('pattern/<int:pk>/', views.pattern_details, name='pattern-details'),
    path('finish/<int:pk>/', views.finish_details, name='finish-details'),

    path('colorchart/', include([
        path('', views.colorchart_index, name='colorchart-index'),
        path('<int:pk>/', views.colorchart, name='colorchart'),
        ])),

]


import uuid
from datetime import datetime
from dateutil.parser import parse as parse_iso
from flask import render_template, request
from haversine import haversine
from vehicle_tracker import app, db, model, socketio

@app.route('/')
def index():
    return render_template('index.html', mapbox_key=app.config['MAPBOX_KEY'])

@app.route('/vehicles', methods=['POST'])
def register_vehicle():
    """
    Registers new vehicle by uuid if it doesn't already exist in our database.
    :return:
    """

    try:
        vehicle_id = str(uuid.UUID(request.get_json()['id']))
    except KeyError:
        return 'Vehicle uuid was NOT provided', 400
    except ValueError:
        return 'Vehicle uuid is NOT valid', 400

    vehicle = model.Vehicle.query.filter_by(vehicle_uuid=vehicle_id).first()
    if not vehicle:
        vehicle = model.Vehicle(vehicle_uuid=vehicle_id)
        db.session.add(vehicle)

    model.Registration(vehicle=vehicle,
                       action='register',
                       time=datetime.utcnow())
    db.session.commit()

    return '', 204

@app.route('/vehicles/<uuid:vehicle_id>', methods=['DELETE'])
def deregister_vehicle(vehicle_id):
    """
    Deregister vehicle with given vehicle id.
    :param vehicle_id:
    :return:
    """

    vehicle_id = str(vehicle_id)
    vehicle = model.Vehicle.query.filter_by(vehicle_uuid=vehicle_id).first()
    if not vehicle:
        return 'Vehicle does NOT exist', 404

    # Deregister vehicle and persist
    model.Registration(vehicle=vehicle,
                       action='deregister',
                       time=datetime.utcnow())
    db.session.commit()

    # Send to the socket check if vehicle is within allowed city boundaries
    socketio.emit('deregister_vehicle',
                  {'vehicle_id': str(vehicle_id)},
                  namespace='/vehicles')

    return '', 204

@app.route('/vehicles/<uuid:vehicle_id>/locations', methods=['POST'])
def update_location(vehicle_id):
    """
    Updates a vehicle with current location bases on it's uuid.
    :param vehicle_id:
    :return:
    """

    vehicle_id = str(vehicle_id)
    vehicle = model.Vehicle.query.filter_by(vehicle_uuid=vehicle_id).first()
    if not vehicle:
        return 'Vehicle does NOT exist', 404

    if vehicle.registrations[-1].action != 'register':
        return 'Vehicle is NOT registered', 401

    data = request.get_json()

    # Only allow to update vehicle's current location if lat and lng is
    # within city boundaries
    if haversine((data['lat'], data['lng']), (52.53, 13.403)) <= 3.5:
        model.Location(vehicle=vehicle,
                       lat=data['lat'],
                       lng=data['lng'],
                       time=parse_iso(data['at']))
        db.session.commit()

        # Send to the socket to visually update the location of the vehicle on the map
        socketio.emit('update_location',
                      {'vehicle_id': str(vehicle_id),
                       'lat': data['lat'],
                       'lng': data['lng']},
                      namespace='/vehicles')

    # Send to the socket check if vehicle is within allowed city boundaries
    else:
        socketio.emit('deregister_vehicle',
                      {'vehicle_id': str(vehicle_id)},
                      namespace='/vehicles')

    return '', 204


import sys
import json
import re
import os
import lxml.etree as et
from defusedxml.lxml import parse as parse_xml

from .classes import Composition, Module, Topic, Property, Parameter

class ModuleParser:

    # calling-path independent method to get a platforms data type mapping
    @staticmethod
    def get_data_types(plat):
        try:

            data_types = {}

            # save the current path
            base_path = os.path.abspath(os.getcwd())

            # parse the mapping file
            data_tree = parse_xml((os.path.join(os.getcwd(), "models",
                                                "dataMapping.xml")))

            data_root = data_tree.getroot()

            # return to the previous path
            os.chdir(base_path)

            # map the data types
            if any(platform.attrib.get("name") == plat for platform
                   in data_root):
                for platform in data_root.iter("platform"):
                    if platform.attrib.get("name") == plat:
                        for dataType in platform.iter("type"):
                            data_types[dataType.attrib.get("name")] = \
                                dataType.attrib.get("value")
            else:
                print("Chosen platform doesn't exist")
                sys.exit(1)

        except Exception as ex:
            print("Error parsing dataType mapping file")
            raise ex

        return data_types

    # check for value type, else all values'll be strings
    @staticmethod
    def process_value(value, process_value_type):
        if value is None or not value:
            return None
        # if numeric with no decimals (bool would either be 0 or 1)
        if process_value_type in ["int", "uint", "bool"]:
            return int(value)
        # if numeric with decimals
        if process_value_type in ["float", "double"]:
            return float(value)
        # else return the value without modifying, it's treated as a string
        return value

    # topic parsing and processing
    def process_topic(self, topic, mandatory):
        top = Topic(topic.attrib.get("name"), topic.attrib.get("type"),
                    mandatory)
        if "description" in topic.attrib:
            top.desc = topic.attrib.get("description")
        if "package" in topic.attrib:
            top.package = topic.attrib.get("package")
        top.fileName = topic.attrib.get("fileName")
        for prop in topic:
            if prop.tag == "property":
                top.add_prop(self.process_property(prop))
            if prop.tag == "response":
                for res in prop:
                    top.add_res(self.process_property(res))
            if prop.tag == "feedback":
                for res in prop:
                    top.add_feed(self.process_property(res))
        return top

    # property and sub property recursive parsing and processing
    def process_property(self, process_property):
        if "type" in process_property.attrib:
            type_list = process_property.attrib.get("type")

            # check for array declaration in type
            if re.search(r"\[.*\]", type_list):
                prop = Property(process_property.attrib.get("name"),
                                re.sub(r"\[.*\]", "", type_list))
                prop.array = True

                # check for array length if specified
                matches = re.finditer(r"\[\D*(\d+)\]", type_list)
                for i, match in enumerate(matches):
                    prop.length = int(match.group(1))
            else:
                prop = Property(process_property.attrib.get("name"), type_list)
        else:
            prop = Property(process_property.attrib.get("name"))
        if "unit" in process_property.attrib:
            prop.unit = process_property.attrib.get("unit")

            # check for enumeration values
            if prop.unit == "enum" and "enum" in process_property.attrib:
                prop.enumeration = json.loads(process_property.attrib
                                              .get("enum"))
        if "description" in process_property.attrib:
            prop.desc = process_property.attrib.get("description")

        if "fileName" in process_property.attrib:
            prop.fileName = process_property.attrib.get("fileName")

        if "package" in process_property.attrib:
            prop.package = process_property.attrib.get("package")

        # check for sub properties
        if any(x.tag == "property" for x in process_property):

            # process sub properties
            for subProp in process_property:
                if subProp.tag == "property":
                    prop.add_prop(self.process_property(subProp))

        # else process the value
        else:

            # if array assume multiple values
            if prop.array:

                # if length is specified fill every entry before appending
                # value
                if prop.length is not None:
                    value = [None] * prop.length
                    i = 0
                    for tag in process_property:
                        if tag.tag == "value" and i < prop.length:
                            value[i] = tag.text
                            i += 1

                # else simply append value to the array
                else:
                    value = []
                    for tag in process_property:
                        if tag.tag == "value":
                            value.append(tag.text)

            # else process a single value
            else:
                value = process_property[0].text
            prop.value = value
        return prop

    # parameter parsing and processing
    def process_param(self, parameter, mandatory):
        # check for array declaration in type
        if re.search(r"\[.*\]", parameter.attrib.get("type")):

            param = Parameter(
                parameter.attrib.get("name"), re.sub(r"\[.*\]",
                                                     "",
                                                     parameter.attrib.get(
                                                         "type")),
                mandatory, parameter.attrib.get("unit")
            )
            param.desc = parameter.attrib.get("description")

            param.array = True

            # check for array length if specified
            matches = re.finditer(r"\[\D*(\d+)\]",
                                  parameter.attrib.get("type"))
            for i, match in enumerate(matches):
                param.length = int(match.group(1))

            if param.length is not None:
                value = [None] * param.length
                i = 0
                for tag in parameter:
                    if tag.tag == "value" and i < param.length:
                        value[i] = self.process_value(tag.text, param.type)
                        i += 1
            else:
                value = []
                for tag in parameter:
                    if tag.tag == "value":
                        value.append(self.process_value(tag.text, param.type))
            param.value = value
            return param
        param = Parameter(
            parameter.attrib.get("name"), parameter.attrib.get("type"),
            mandatory, parameter.attrib.get("unit")
        )
        param.desc = parameter.attrib.get("description")
        param.value = self.process_value(parameter[0].text, param.type)
        return param

    def parse_base(self, path):
        generic_topics = []

        try:
            gen_tree = parse_xml(path)
            gen_tree.xinclude()
            gen_root = gen_tree.getroot()
            for topic in gen_root:
                generic_topics.append(self.process_topic(topic, True))
        except Exception as ex:
            print("Problem parsing generic topics")
            raise ex
        return generic_topics

    def parse_composition(self, path):
        comp_tree = parse_xml(path)
        comp_root = comp_tree.getroot()
        composition = Composition(comp_root.attrib.get("name"))
        for model in comp_root:
            topic_list = []
            for topic in model.findall("topic"):
                topic_list.append(topic.attrib.get("name"))
            param_list = []
            for param in model.findall("param"):
                param_list.append(param.attrib.get("name"))
            model_path = os.path.join(os.getcwd(), model.attrib.get("path"))
            module = self.parse_file(model_path)
            for topic in list(module.topics):
                if not topic.mandatory and topic.name not in topic_list:
                    module.topics.remove(topic)
            for param in list(module.params):
                if not param.mandatory and param.name not in param_list:
                    module.params.remove(param)
            composition.modules.append(module)
        return composition

    # main parse method
    def parse_file(self, file_path):

        # check for parsability
        try:
            if os.path.exists(file_path):
                path = file_path
            else:
                path = os.getcwd() + file_path
            tree = et.parse(path)
        except Exception as ex:
            print("Problem parsing " + file_path)
            raise ex

        tree.xinclude()
        root = tree.getroot()

        # instantiate module
        module = Module(
            root.attrib.get("name"), root.attrib.get("type"),
            root.attrib.get("description")
        )

        # loop through mandatory topics and parameters
        for tag in root[0]:
            if tag.tag == "topic":
                module.add_topic(self.process_topic(tag, True))
            if tag.tag == "param":
                module.add_param(self.process_param(tag, True))

        # check for optional topics/parameters
        if len(root) > 1:
            # loop through optional topics and parameters
            for tag in root[1]:
                if tag.tag == "topic":
                    module.add_topic(self.process_topic(tag, False))
                if tag.tag == "param":
                    module.add_param(self.process_param(tag, False))

        return module

    def __init__(self):
        pass


#Biblotecas
import curses
import psutil
import threading
import time
import platform

#variables
global numerosHilos
global conta
global mutex
global barrera
#Variables para la sincronizar hilos
numerosHilos = 4
conta = 0
mutex = threading.Semaphore(1)
barrera= threading.Semaphore(0)

#Conversion de bytes
def convesion(num, sufijo='B'):
    for unit in ['','K','M','G','T','P','E','Z']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, sufijo)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', sufijo)

#procesos en ejecucion
def procesos(tamanio):
	lstproc = psutil.pids()
	lstproc.reverse()

	for x in xrange(0,tamanio):
		pantalla.addstr(10+x, 2,"%d "%lstproc[x])
		pantalla.addstr(10+x, 8,psutil.Process(lstproc[x]).name()+"         ")
		pantalla.addstr(10+x, 22,psutil.Process(lstproc[x]).status()+"  ")
		pantalla.addstr(10+x, 35,"%d   "%psutil.Process(lstproc[x]).num_threads())
		pantalla.addstr(10+x, 43,psutil.Process(lstproc[x]).username()+"      ")
		pantalla.addstr(10+x, 53,"%.2f"%psutil.Process(lstproc[x]).cpu_percent(interval=0))
		pantalla.addstr(10+x, 63,convesion(psutil.Process(lstproc[x]).memory_info().rss)+"    ")

#inicalizacion de la barrera
def inbarre():
	global conta
	mutex.acquire()
	conta=conta+1
	mutex.release()

	if conta == numerosHilos:
		barrera.release()
	barrera.acquire()
	barrera.release()

# porcentaje
def porcentaje (fuente,y):
	tamanio = 50
	percent = int(round(fuente/2))
	for i in range(0,percent):
		pantalla.addstr(y,i+18," ",curses.A_STANDOUT)
	for i in range(percent,tamanio):
		pantalla.addstr(y,i+18," ")
	if fuente<10:
		pantalla.addstr(y,18+tamanio,"| 0%d %%"%fuente)
	else:
		pantalla.addstr(y,18+tamanio,"| %d %%"%fuente)
	pantalla.refresh()

	inbarre()

# la memoria usada y disponible
def memoriaUsada():
	pantalla.addstr(7,45,convesion(psutil.virtual_memory().available))
	pantalla.addstr(7,71,convesion(psutil.virtual_memory().used))

	inbarre()

# inicia los hilos de las funciones
def hilos():
	threading.Thread(target=memoriaUsada, args=[]).start()
	threading.Thread(target=procesos, args=[13]).start()
	threading.Thread(target=porcentaje, args=[psutil.cpu_percent(interval=1),2]).start()
	threading.Thread(target=porcentaje, args=[psutil.virtual_memory().percent,4]).start()

#Funcion que dibuja toda la interfaz
def interfaz(args):
	global pantalla
	global conta
	global numerosHilos

	while True:

		pantalla = curses.initscr()

		pantalla.addstr(0, 45, "Monitor de Procesos",curses.A_BOLD)
		pantalla.addstr(2, 1, "Uso de CPU:")
		pantalla.addstr(4, 1, "Uso de MEMORIA:")
		pantalla.addstr(6, 28, platform.system())
		pantalla.addstr(6, 34, platform.processor())
		pantalla.addstr(6, 43,"%d Nucleos"%psutil.cpu_count())
		pantalla.addstr(7, 3,"Memoria Total: "+convesion(psutil.virtual_memory().total))
		pantalla.addstr(7, 30,"Memoria Libre:")
		pantalla.addstr(7, 55,"Memoria en Uso:")

		for j in xrange(1,79):
			pantalla.addstr(9, j, " ")
		pantalla.addstr(9, 2,"PID",curses.A_REVERSE)
		pantalla.addstr(9,8,"Nombre",curses.A_REVERSE)
		pantalla.addstr(9,23,"Estado",curses.A_REVERSE)
		pantalla.addstr(9,34,"Hilos",curses.A_REVERSE)
		pantalla.addstr(9,42,"Usuario",curses.A_REVERSE)
		pantalla.addstr(9,53,"% CPU",curses.A_REVERSE)
		pantalla.addstr(9,63,"Memoria",curses.A_REVERSE)

		hilos()
		mutex.acquire()
		conta-=numerosHilos
		mutex.release()

		pantalla.refresh()

		curses.endwin()

curses.wrapper(interfaz)


#!/usr/bin/python
# encoding: utf-8

import torch
import torch.nn as nn
from torch.autograd import Variable
import collections
import Levenshtein
import tensorflow as tf
import numpy as np
from PIL import Image
from torchvision.transforms import ToTensor, Normalize

mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]

class BeamSearchDecoder():
    def __init__(self, lib, corpus, chars, word_chars, beam_width=20, lm_type='Words', lm_smoothing=0.01, tfsess=None):
        word_beam_search_module = tf.load_op_library(lib)
        self.mat = tf.placeholder(tf.float32)
        corpus = open(corpus).read()
        chars = open(chars).read()
        word_chars = open(word_chars).read()

        self.beamsearch_decoder = word_beam_search_module.word_beam_search(self.mat, beam_width, lm_type, lm_smoothing, corpus, chars, word_chars)
        self.tfsess = tfsess or tf.Session()
        self.idx2char = dict(zip(range(0, len(chars)), chars))

    def beamsearch(self, mat):

        mat = np.concatenate((mat[:,:, 1:], mat[:,:,:1]), axis=-1)
        results=self.tfsess.run(self.beamsearch_decoder, {self.mat:mat})
        return results

    def decode(self, preds_idx):
        return [''.join([self.idx2char[idx] for idx in row if idx < len(self.idx2char)]) for row in preds_idx]

def resizePadding(img, width, height):
    desired_w, desired_h = width, height #(width, height)
    img_w, img_h = img.size  # old_size[0] is in (width, height) format
    ratio = 1.0*img_w/img_h
    new_w = int(desired_h*ratio)
    new_w = new_w if desired_w == None else min(desired_w, new_w)
    img = img.resize((new_w, desired_h), Image.ANTIALIAS)

    # padding image
    if desired_w != None and desired_w > new_w:
        new_img = Image.new("RGB", (desired_w, desired_h), color=255)
        new_img.paste(img, (0, 0))
        img = new_img

    img = ToTensor()(img)
    img = Normalize(mean, std)(img)

    return img

def maxWidth(sizes, height):
    ws = [int(height*(1.0*size[0]/size[1])) for size in sizes]
    maxw = max(ws)

    return maxw

class strLabelConverter(object):
    """Convert between str and label.

    NOTE:
        Insert `blank` to the alphabet for CTC.

    Args:
        alphabet (str): set of the possible characters.
        ignore_case (bool, default=True): whether or not to ignore all of the case.
    """

    def __init__(self, alphabet, ignore_case=True):
        self._ignore_case = ignore_case
        if self._ignore_case:
            alphabet = alphabet.lower()
        self.alphabet = alphabet + '-'  # for `-1` index

        self.dict = {}
        for i, char in enumerate(alphabet):
            # NOTE: 0 is reserved for 'blank' required by wrap_ctc
            self.dict[char] = i + 1

    def encode(self, text):
        """Support batch or single str.

        Args:
            text (str or list of str): texts to convert.

        Returns:
            torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
            torch.IntTensor [n]: length of each text.
        """
        if isinstance(text, str):
            text = [
                self.dict[char.lower() if self._ignore_case else char]
                for char in text
            ]
            length = [len(text)]
        elif isinstance(text, collections.Iterable):
            length = [len(s) for s in text]
            text = ''.join(text)
            text, _ = self.encode(text)

        return (torch.IntTensor(text), torch.IntTensor(length))

    def decode(self, t, length, raw=False):
        """Decode encoded texts back into strs.

        Args:
            torch.IntTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.
            torch.IntTensor [n]: length of each text.

        Raises:
            AssertionError: when the texts and its length does not match.

        Returns:
            text (str or list of str): texts to convert.
        """
        if length.numel() == 1:
            length = length[0]
            assert t.numel() == length, "text with length: {} does not match declared length: {}".format(t.numel(), length)
            if raw:
                return ''.join([self.alphabet[i - 1] for i in t])
            else:
                char_list = []
                for i in range(length):
                    if t[i] != 0 and (not (i > 0 and t[i - 1] == t[i])):
                        char_list.append(self.alphabet[t[i] - 1])
                return ''.join(char_list)
        else:
            # batch mode
            assert t.numel() == length.sum(), "texts with length: {} does not match declared length: {}".format(t.numel(), length.sum())
            texts = []
            index = 0
            for i in range(length.numel()):
                l = length[i]
                texts.append(
                    self.decode(
                        t[index:index + l], torch.IntTensor([l]), raw=raw))
                index += l
            return texts

class averager(object):
    """Compute average for `torch.Variable` and `torch.Tensor`. """

    def __init__(self):
        self.reset()

    def add(self, v):
        if type(v) is list:
            self.n_count += len(v)
            self.sum += sum(v)
        else:
            self.n_count += 1
            self.sum += v

    def reset(self):
        self.n_count = 0
        self.sum = 0

    def val(self):
        res = 0
        if self.n_count != 0:
            res = self.sum / float(self.n_count)
        return res

def oneHot(v, v_length, nc):
    batchSize = v_length.size(0)
    maxLength = v_length.max()
    v_onehot = torch.FloatTensor(batchSize, maxLength, nc).fill_(0)
    acc = 0
    for i in range(batchSize):
        length = v_length[i]
        label = v[acc:acc + length].view(-1, 1).long()
        v_onehot[i, :length].scatter_(1, label, 1.0)
        acc += length
    return v_onehot

def loadData(v, data):
    v.resize_(data.size()).copy_(data)

def prettyPrint(v):
    print('Size {0}, Type: {1}'.format(str(v.size()), v.data.type()))
    print('| Max: %f | Min: %f | Mean: %f' % (v.max().data[0], v.min().data[0],
                                              v.mean().data[0]))

def assureRatio(img):
    """Ensure imgH <= imgW."""
    b, c, h, w = img.size()
    if h > w:
        main = nn.UpsamplingBilinear2d(size=(h, h), scale_factor=None)
        img = main(img)
    return img

def cer_loss_one_image(sim_pred, label):
    loss = Levenshtein.distance(sim_pred, label) * 1.0 / max(len(sim_pred), len(label))
    return loss

def cer_loss(sim_preds, labels):
    losses = []
    for i in range(len(sim_preds)):
        pred = sim_preds[i]
        text = labels[i]

        loss = cer_loss_one_image(pred, text)
        losses.append(loss)
    return losses


from django.urls import path
from .views import create_review,get_list_of_reviews,review_details
app_name='reviews'

urlpatterns = [
    path('<int:id>/create-review/',create_review,name="create_review"),
    path('<int:id>/get-all-reviews/',get_list_of_reviews,name="get_all_reviews"),
    path('get-review-details/<int:review_id>/',review_details,name="get_review_details"),
    # path('edit-review/<int:review_id>/',edit_review,name="edit_review"),
    # path('delete-review/<int:review_id>/',delete_review,name="delete_review"),
]


import torch
from torch import nn
from torch.nn import functional as F

class Decoder(nn.Module):
    def __init__(self, low_level_channels, num_classes):
        super(Decoder, self).__init__()
        self.conv1x1 = nn.Sequential(
            nn.Conv2d(low_level_channels, 48, 1, bias=False),
            nn.BatchNorm2d(48),
            nn.ReLU(inplace=True)
        )

        self.output = nn.Sequential(
            nn.Conv2d(48+256, 256, 3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, 3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True),
            nn.Dropout(0.1),
            nn.Conv2d(256, num_classes, 1, stride=1),
        )

        # initialize weight
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight.data, nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1.)
                nn.init.constant_(m.bias, 0.)

    def forward(self, x, low_level_features):
        low_level_features = self.conv1x1(low_level_features)
        _, _, H, W = low_level_features.size()

        x = F.interpolate(x, size=(H, W), mode='bilinear', align_corners=True)
        x = self.output(torch.cat([low_level_features, x], 1))
        return x


import os
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import TimeoutException

def wait_and_click(driver, xpath):
    WebDriverWait(driver, 30).until(
        EC.presence_of_all_elements_located((By.XPATH, xpath))
    )
    elems = driver.find_elements(By.XPATH, xpath)
    if len(elems) > 0:
        elems[0].click()

options = Options()
options.add_argument(
    "user-data-dir=/Users/umairashraf/Library/Application Support/Google/Chrome/Default"
)
driver = webdriver.Chrome(
    executable_path="/Users/umairashraf/Develop/selenium_tests/chromedriver",
    chrome_options=options,
)

stop = False

while not stop:
    try:
        driver.get(
            "https://ceda.datatrium.com/fmi/webd/CEDA?homeurl=https://cedamtl.org/francisation-au-quebec/"
        )
        xpath1 = "//div[@role='dialog']"
        WebDriverWait(driver, 60 * 10).until(
            EC.presence_of_element_located((By.XPATH, xpath1))
        )
        elems = driver.find_elements(By.XPATH, xpath1)
        if len(elems) > 0:
            wait_and_click(driver, "//span[@class='v-button-caption']")
            wait_and_click(driver, "//div[text()='Francisation']")
            time.sleep(2)
        else:
            stop = True
    except TimeoutException as timeout_exc:
        pass
    except:
        driver.close()
        os.system('say "Uh oh"')
        raise

for i in range(50):
    os.system('say "It\'s Ready!"')
    time.sleep(2)


"""taxi URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

from main import views

urlpatterns = [
    path('', views.OrderCreateView.as_view(), name='create-order'),
    path('users/login/', views.login_view, name='login'),
    path('users/logout/', views.logout_view, name='logout'),
    path('orders/', views.OrderListView.as_view(), name='order-list'),
    path('orders/<int:pk>/', views.OrderDetailView.as_view(), name='order-detail'),
    path('cars/', views.CarListView.as_view(), name='car-list'),
    path('cars/<int:pk>/', views.CarDetailView.as_view(), name='car-detail'),
    path('cars/<int:pk>/set-available/', views.car_set_available_view, name='car-set-available'),
    path('admin/', admin.site.urls),
]


from rest_framework import serializers
from db.user import User, UserRoleLink, Role

class UserDashboardSerializer(serializers.ModelSerializer):
    total_karma = serializers.SerializerMethodField()

    def get_total_karma(self, obj):
        karma = obj.total_karma_user.karma if hasattr(obj, "total_karma_user") else 0
        return karma

    class Meta:
        model = User
        exclude = ("password",)
        extra_fields = ["total_karma"]
        read_only_fields = ["id", "created_at", "total_karma"]

class UserSerializer(serializers.ModelSerializer):
    muid = serializers.CharField(source="mu_id")
    firstName = serializers.CharField(source="first_name")
    lastName = serializers.CharField(source="last_name")
    existInGuild = serializers.CharField(source="exist_in_guild")
    joined = serializers.CharField(source="created_at")
    roles = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            "muid",
            "firstName",
            "lastName",
            "fullname",
            "fullname",
            "email",
            "mobile",
            "gender",
            "dob",
            "active",
            "existInGuild",
            "joined",
            "roles",
        ]

    def get_roles(self, obj):
        return [
            user_role_link.role.title
            for user_role_link in obj.user_role_link_user.all()
        ]

class UserVerificationSerializer(serializers.ModelSerializer):
    full_name = serializers.ReadOnlyField(source="user.fullname")
    user_id = serializers.ReadOnlyField(source="user.id")
    discord_id = serializers.ReadOnlyField(source="user.discord_id")
    mu_id = serializers.ReadOnlyField(source="user.mu_id")
    role_title = serializers.ReadOnlyField(source="role.title")

    class Meta:
        model = UserRoleLink
        fields = [
            "id",
            "user_id",
            "discord_id",
            "mu_id",
            "full_name",
            "verified",
            "role_id",
            "role_title",
        ]


"""
Monte Carlo dart-throwing simulation
"""

import math as m
import numpy as np
import matplotlib.pyplot as plt

def draw_board(r=1, pts=100):
    plt.plot([-r, r, r, -r, -r], [-r, -r, r, r, -r], 'k-')
    theta = np.linspace(0, 2*m.pi, pts)
    x = r*np.cos(theta)
    y = r*np.sin(theta)
    plt.plot(x, y, 'r-')
    plt.axis('equal')

def throw_darts(r=1):
    xpos = np.random.uniform(-r, r)
    ypos = np.random.uniform(-r, r)
    return (xpos, ypos)

def plot_darts(x, y, color='b'):
    plt.figure(1)
    plt.plot(x, y, '.', mfc=color, mec=color)
    plt.draw()
    plt.pause(0.01)

def plot_est(nums, ests):
    plt.figure(2)
    plt.plot(nums, ests, 'ko')
    plt.plot(nums, m.pi*np.ones(len(nums)), 'g.')
    plt.draw()
    plt.pause(0.01)

if __name__ == '__main__':
    darts_to_throw = 10000
    darts_thrown = 0
    board_rad = 1
    do_plot = 0
    inside = 0
    pi_est = []
    x_i_vec = []
    y_i_vec = []
    x_o_vec = []
    y_o_vec = []

    plt.figure(1)
    plt.clf()
    draw_board(r=board_rad)

    plt.figure(2)
    plt.clf()

    while darts_thrown < darts_to_throw:
        darts_thrown += 1
        x_d, y_d = throw_darts(board_rad)
        r_d = m.sqrt(x_d**2 + y_d**2)
        color='m'
        if r_d < board_rad:
            inside += 1
            x_i_vec += [x_d]
            y_i_vec += [y_d]
            color='g'
        else:
            x_o_vec += [x_d]
            y_o_vec += [y_d]

        pi_est += [4*inside/darts_thrown]
        print('{:5d}'.format(darts_thrown) +
               ' {:5d}'.format(inside) +
               ' {:0.3e}'.format(pi_est[-1]))

        if do_plot:
            plot_darts(x_d, y_d, color)
            plot_est(darts_thrown, pi_est[-1])

    if not do_plot:
        plot_darts(x_i_vec, y_i_vec, 'g')
        plot_darts(x_o_vec, y_o_vec, 'm')
        plot_est(np.linspace(1, darts_thrown, darts_thrown), pi_est)

    plt.figure(1)
    draw_board(board_rad)


import Neurons
import random
import matplotlib.pyplot as plt
from contextlib import suppress

# Training data
x_train = [[1,1],[1,0],[0,1],[0,0],[0.5,0],[0,0.5],[1,0.5],[0.5,1]]
y_train = [[0],[0],[0],[0],[1],[1],[1],[1]]

# Network
i1 = Neurons.Input()
i2 = Neurons.Input()

a1 = Neurons.Sigmoid([i1, i2])
a2 = Neurons.Sigmoid([i1, i2])
a3 = Neurons.Sigmoid([i1, i2])
a4 = Neurons.Sigmoid([i1, i2])

b1 = Neurons.Sigmoid([a1, a2, a3, a4])
b2 = Neurons.Sigmoid([a1, a2, a3, a4])

o1 = Neurons.Sigmoid([b1, b2])

w1 = Neurons.Watch([a1, a2, a3, a4])
w2 = Neurons.Watch([b1, b2], w1)
w3 = Neurons.Watch([o1], w2)

def backpropagate(iterations):
    # Backpropagation
    for i in range(iterations):
        rand = random.randint(0,len(y_train) - 1)
        i1.value = x_train[rand][0]
        i2.value = x_train[rand][1]
        w1.activate()

        o1.quadratic_cost(y_train[rand][0])

        w3.backpropagate(10)

def test_network():
    # Plot color map
    resolution = 200
    plot = [[] for i in range(resolution)]
    for i in range (resolution):
        for j in range (resolution):
            i1.value = i / (resolution - 1)
            i2.value = j / (resolution - 1)
            w1.activate()
            plot[i].append(o1.value)

    # Plot scatterplots and plots
    fig, axs = plt.subplots(3,2, figsize = (16,12))
    axs[0, 0].imshow(plot, cmap=plt.cm.Blues)
    axs[0, 0].axis('off')
    axs[0, 0].set_title('Color Map')

    x_axis = [x for x in range(len(o1.deltas_history))]

    axs[1, 0].scatter(x_axis, o1.deltas_history)
    axs[0, 0].axis('off')
    axs[1, 0].axes.get_xaxis().set_visible(False)
    axs[2, 0].axes.get_xaxis().set_visible(False)
    axs[1, 0].set_title('B Deltas')
    axs[2, 0].set_title('A Deltas')
    for n in w2.neurons:
        axs[1,0].scatter(x_axis, n.deltas_history)
    for n in w1.neurons:
        axs[2,0].scatter(x_axis, n.deltas_history)

    axs[0, 1].axes.get_xaxis().set_visible(False)
    axs[1, 1].axes.get_xaxis().set_visible(False)
    axs[2, 1].axes.get_xaxis().set_visible(False)
    axs[0, 1].set_title('O1 Weights')
    axs[1, 1].set_title('B Weights')
    axs[2, 1].set_title('A Weights')
    axs[0, 1].plot(o1.weights_history)
    for n in w2.neurons:
        axs[1,1].plot(n.weights_history)
    for n in w1.neurons:
        axs[2,1].plot(n.weights_history)

    plt.show()

answer = 1000
while (answer != 0):
    backpropagate(answer)
    test_network()

    answer = int(input("Backpropagation iterations: "))


import json
import logging
from nornir import InitNornir
from nornir_netmiko.tasks import netmiko_send_command
from nornir_utils.plugins.functions import print_result
from nornir.core.task import Result

nr = InitNornir(config_file="config.yaml")

def new_random_test(task):
    configuration = task.run(
        task=netmiko_send_command,
        severity_level=logging.DEBUG,
        command_string="show configuration interfaces | display json",
    )
    dict_configuration = json.loads(configuration.result)
    interface = dict_configuration["configuration"]["interfaces"]["interface"]
    result_list = []
    for intf in interface:
        target_interface = intf["name"]
        unit = intf["unit"]
        for element in unit:
            names = element["family"]["inet"]["address"]
            for name in names:
                ip = name["name"]
        result_list.append(f"{target_interface} has an IP address of {ip}")
    return Result(host=task.host, result=result_list)

result = nr.run(task=new_random_test)
print_result(result)


""" module to method to processing """

import os
import json
import string
import logging
from typing import Dict
from jc_decrypter.utils import request, files
from jc_decrypter import config

ALFABETO = string.ascii_lowercase
logger = logging.getLogger(__name__)

def decrypter(api_token: str) -> Dict:
    """ method to processing to descypter data from api """

    data = request.get(config.API_GENERATE_DATA, params={"token": api_token}).json()

    # Salvando Arquivo Inicial
    files.write_file(os.path.join(config.BASE_PATH, "answer.json"), json.dumps(data))

    numero_casas = data["numero_casas"]
    cifrado = data["cifrado"]
    decifrado = ""

    logger.info("Texto cifrado: %s", cifrado)
    for letra in cifrado:
        if letra in ALFABETO:
            index_letra_decifrada = ALFABETO.index(letra) - numero_casas
            try:
                decifrado += ALFABETO[index_letra_decifrada]
            except IndexError:
                decifrado += ALFABETO[index_letra_decifrada - 26]
        else:
            decifrado += letra

    logger.info("Texto decifrado: %s", decifrado)
    print(decifrado)

    data["decifrado"] = decifrado
    data["resumo_criptografico"] = files.sha1(decifrado)

    # Salvando Arquivo Final
    files.write_file(os.path.join(config.BASE_PATH, "answer.json"), json.dumps(data))

    submit_data = request.post(
        config.API_SUBMIT_DATA,
        path_to_file=os.path.join(config.BASE_PATH, "answer.json"),
        params={"token": api_token},
    ).json()

    return {"return_submit": submit_data, "result_processing": data}