from flask import Flask
from flask import request
from flask import Response
from flask_cors import CORS, cross_origin
from RobieLegs import *
from RobieEyes import *

app = Flask(__name__)

cors = CORS(app, resources={"/robie/legs": {"origins": "http://192.168.1.172:80"}})

@app.route('/robie/legs', methods=['POST'])
@cross_origin(origin='192.168.1.172', headers=['Content- Type', 'Authorization'])
def api_Legs():

    if request.headers['Content-Type'] == 'application/json':
        x = request.json['x']
        y = request.json['y']
        RobieLegs().roll(x, y)
        resp = Response()
        resp.status_code = 200
        resp.headers['server'] = ""
        return resp

    else:
        resp = Response("Try Again :-(", status=415, mimetype='text/plain')
        resp.headers['server'] = ""
        return resp

@app.route('/robie/eyes', methods=['POST'])
@cross_origin(origin='192.168.1.172', headers=['Content- Type', 'Authorization'])
def api_Eyes():

    if request.headers['Content-Type'] == 'application/json':
        channel = request.json['eye']
        red = request.json['red']
        green = request.json['green']
        blue = request.json[' blue']
        RobieEyes().setColor(channel, red, green, blue)
        resp = Response()
        resp.status_code = 200
        response.headers['server'] = ""
        return resp

    else:
        resp = Response("Try Again :-(", status=415, mimetype='text/plain')
        resp.headers['server'] = ""
        return resp

@app.route('/robie/eyes/close', methods=['POST'])
@cross_origin(origin='192.168.1.172', headers=['Content- Type', 'Authorization'])
def api_Eyes_Close():

    if request.headers['Content-Type'] == 'application/json':
        RobieEyes().blankEyes()
        resp = Response()
        resp.status_code = 200
        response.headers['server'] = ""
        return resp

    else:
        resp = Response("Try Again :-(", status=415, mimetype='text/plain')
        resp.headers['server'] = ""
        return resp


"""
Definitions related to implied imports.

The implies in this file are based on manual
inspection of the stdlib sources for CPython.
"""

import os
import sys
from typing import Dict, Sequence, Tuple, Union

class Alias(str):
    """
    Alias for a module name

    Aliases are used in "implies" configuration to specify
    that a module name is actually an alias for some other
    name. An instance of this class is used to represent.
    the name of the other module.
    """

    __slots__ = ()

class Virtual(str):
    """
    Virtual package provided by a module

    Virtuals are used in "implies" configuration to specify
    that a module name is actually the name of a virtual
    module provided by another module.  An instance of
    this class is used to represent the name of the
    other module.
    """

    __slots__ = ()

#: The type for the value in an implies dictionary.
ImpliesValueType = Union[None, Alias, Virtual, Sequence[str]]

#: Implies dictionary for the standard library.
STDLIB_IMPLIES: Dict[str, ImpliesValueType] = {
    #
    # C extensions
    #
    "_asyncio": (
        "asyncio",
        "asyncio.events",
        "asyncio.base_futures",
        "asyncio.base_tasks",
        "asyncio.coroutines",
        "inspect",
        "traceback",
        "weakref",
    ),
    "_curses": ("curses",),
    "_datetime": ("time", "_strptime"),
    "_elementtree": ("copy", "xml.etree.ElementPath", "pyexpat"),
    "_json": ("json.decoder",),
    "_operator": ("functools",),
    "_pickle": ("copyreg", "_compat_pickle", "codecs", "functools"),
    "_posixsubprocess": ("gc",),
    "_ssl": ("_socket",),
    "_overlapped": ("_socket",),
    "parser": ("copyreg",),
    "posix": ("resource",),
    "signal": ("_signal",),
    "time": ("_strptime",),
    "zipimport": ("importlib.resources", "zlib"),
    #
    # Python module
    #
    # typing.io is "just" a namespace created by "typing", not a
    # real module.
    "typing.io": Virtual("typing"),
    "typing.re": Virtual("typing"),
    # os.path is a virtual package
    "os.path": Alias(os.path.__name__),
    # sysconfig users __import__ to load platform specific data
    "sysconfig": (
        "_sysconfigdata_{abi}_{platform}_{multiarch}".format(
            abi=getattr(sys, "abiflags", ""),
            platform=sys.platform,
            multiarch=getattr(sys.implementation, "_multiarch", ""),
        ),
    ),
    # turtledemo uses __import__ to load the actual demos
    "turtledemo": (
        "turtledemo.colormixer",
        "turtledemo.nim",
        "turtledemo.rosette",
        "turtledemo.yinyang",
        "turtledemo.forest",
        "turtledemo.paint",
        "turtledemo.round_dance",
        "turtledemo.bytedesign",
        "turtledemo.fractalcurves",
        "turtledemo.peace",
        "turtledemo.sorting_animate",
        "turtledemo.chaos",
        "turtledemo.lindenmayer",
        "turtledemo.penrose",
        "turtledemo.tree",
        "turtledemo.clock",
        "turtledemo.minimal_hanoi",
        "turtledemo.planet_and_moon",
        "turtledemo.two_canvases",
    ),
    # Uses __import__
    "dbm": ("dbm.gnu", "dbm.ndbm", "dbm.dumb"),
}

#: Updates to the base :data:`STDLIB_IMPLIES` for specific platforms.
STDLIB_PLATFORM_IMPLIES: Dict[str, Dict[str, ImpliesValueType]] = {
    "win32": {
        "signal": ("_signal", "_socket"),
        "ctypes": ("comtypes.server.inprocserver",),
        "sysconfig": (),
        "posix": (),
    }
}

STDLIB_IMPLIES.update(STDLIB_PLATFORM_IMPLIES.get(sys.platform, {}))

#: Updates to the base :data:`STDLIB_IMPLIES` for specific Python releases.
STDLIB_VERSION_IMPLIES: Dict[Tuple[int, int], Dict[str, ImpliesValueType]] = {
    (3, 6): {
        "zipimport": ("zlib",),
        "turtledemo": (
            "turtledemo.chaos",
            "turtledemo.fractalcurves",
            "turtledemo.paint",
            "turtledemo.round_dance",
            "turtledemo.two_canvases",
            "turtledemo.clock",
            "turtledemo.lindenmayer",
            "turtledemo.peace",
            "turtledemo.sorting_animate",
            "turtledemo.wikipedia",
            "turtledemo.colormixer",
            "turtledemo.minimal_hanoi",
            "turtledemo.penrose",
            "turtledemo.tree",
            "turtledemo.yinyang",
            "turtledemo.bytedesign",
            "turtledemo.forest",
            "turtledemo.nim",
            "turtledemo.planet_and_moon",
        ),
    }
}

STDLIB_IMPLIES.update(STDLIB_VERSION_IMPLIES.get(sys.version_info[:2], {}))


n = int(input())
a = [int(i) for i in list(input().split(' '))]
count = 0
coins = 0
for k in range(n):
    count += 1
    maximum = max(a)
    coins += max(a)
    a.remove(maximum)
    sum = 0
    for j in a:
        sum += j
    if coins > sum:
        print(count)
        break


from catalogoPeliculas.catalogo_peliculasUbaldo.dominio.Pelicula import Pelicula
from catalogoPeliculas.catalogo_peliculasUbaldo.servicio.catalogo_peliculas import CatalogoPeliculas as cp

opcion = None

while opcion != 4:
    try:
        print('Opciones: ')
        opcion = int(input('''
1. Agregar Película
2. Listar Películas
3. Eliminar catálogo películas
4. Salir
Ingrese la opcion(1-4): '''))
        if opcion == 1:
            nombre_pelicula = input('Por favor proporciona el nombre de la pelicula: ')
            pelicula = Pelicula(nombre_pelicula)
            cp.agregar_pelicula(pelicula)
        elif opcion == 2:
            cp.listar_peliculas()
        elif opcion == 3:
            cp.eliminar_peliculas()
        else:
            print("Opcion invalida")
    except Exception as e:
        print(f"Ocurrio un erro {e}")
        opcion = None
else:
    print("Salimos del programa....")


# -- coding:utf-8 --
# 对tf.multiply的学习

import tensorflow as tf
import numpy as np

X = tf.constant([[1,2],[2,2]])
Y = tf.constant([1,3])

Z = tf.multiply(X,Y)

with tf.Session() as sess:
   #sess.run(Z)
   print(sess.run(Z))


from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import NameList
from .forms import NameForm
from django.urls import reverse

def home(request):
    order_list = NameList.objects.order_by('name')
    return render(request, 'home.html', {'order_list': order_list})

def recipe(request):
    if request.method == "POST":
        rform = NameForm(request.POST)
        if rform.is_valid():
            name = request.POST.get('name', '')
            data = NameList(name=name)
            data.save()
            return HttpResponseRedirect('home.html')
        else:
            return HttpResponse('Not save')
    else:
        rform = NameForm()
        return render(request, 'recipe.html', {'fform': rform})

def details(request, id):
    order_list = NameList.objects.get(pk=id)
    return render(request, 'details.html', {'order_list': order_list})

def results(request, recipe):
    recipe = get_object_or_404(NameList, pk=NameList)
    try:
        select_choice = get_object_or_404(pk=request.POST['choice'])
    except(KeyError, get_object_or_404):
        return render(request, 'details.html', {'recipe': recipe})
    else:
        select_choice.Process += 1
        select_choice.save()
        return HttpResponseRedirect(reverse('recipe', args=(recipe.name,)))


"""
Author: Darby Lim
Modified by: Muhammad Luqman
Organization: Robotisim

This launch file starts a Gazebo simulation, spawns a TurtleBot3 model and a maze, and then starts the navigation2 functionality along with Rviz2 for visualization.

Packages used:
- gazebo_ros
- drive_tb3
- turtlebot3_gazebo
- nav2_bringup
- rviz2

Arguments used:
- map: Full path to map file to load
- params_file: Full path to param file to load
- use_sim_time: Use simulation (Gazebo) clock if true
"""

#!/usr/bin/env python3
import os

from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node

TURTLEBOT3_MODEL = os.environ['TURTLEBOT3_MODEL']

def generate_launch_description():
    ############# Paths Setting
    # This section sets the paths of the launch file directory, maze model, Rviz configuration file, and navigation2 bringup.
    pkg_gazebo_ros = get_package_share_directory('gazebo_ros')
    pkg_tb3_drive = get_package_share_directory('drive_tb3')
    maze_path = os.path.join(pkg_tb3_drive,'models','maze','model.sdf')
    use_sim_time = LaunchConfiguration('use_sim_time', default='false')
    launch_file_dir = os.path.join(get_package_share_directory('turtlebot3_gazebo'), 'launch')

    map_dir = LaunchConfiguration(
        'map',
        default=os.path.join(
            get_package_share_directory('drive_tb3'),
            'map',
            'maze_map.yaml'))

    param_file_name = TURTLEBOT3_MODEL + '.yaml'
    param_dir = LaunchConfiguration(
        'params_file',
        default=os.path.join(
            get_package_share_directory('drive_tb3'),
            'config',
            param_file_name))

    nav2_launch_file_dir = os.path.join(get_package_share_directory('nav2_bringup'), 'launch')

    rviz_config_dir = os.path.join(
        get_package_share_directory('drive_tb3'),
        'config',
        'nav2.rviz')

    return LaunchDescription([
        # Arguments
        # This section declares the launch arguments.
        DeclareLaunchArgument(
            'map',
            default_value=map_dir,
            description='Full path to map file to load'),

        DeclareLaunchArgument(
            'params_file',
            default_value=param_dir,
            description='Full path to param file to load'),

        DeclareLaunchArgument(
            'use_sim_time',
            default_value='false',
            description='Use simulation (Gazebo) clock if true'),

        # Launch Files included
        # These sections start the Gazebo server and client and the robot_state_publisher node.
        IncludeLaunchDescription(
            PythonLaunchDescriptionSource(
                os.path.join(pkg_gazebo_ros, 'launch', 'gzserver.launch.py')
            ),
        ),

        IncludeLaunchDescription(
            PythonLaunchDescriptionSource(
                os.path.join(pkg_gazebo_ros, 'launch', 'gzclient.launch.py')
            )
        ),

        IncludeLaunchDescription(
            PythonLaunchDescriptionSource(
                os.path.join(launch_file_dir, 'robot_state_publisher.launch.py')
            ),
            launch_arguments={'use_sim_time': 'True'}.items()
        ),

        # Spawning Robot
        # This section spawns a TurtleBot3 model at a specified location.
        IncludeLaunchDescription(
            PythonLaunchDescriptionSource(
                os.path.join(pkg_tb3_drive, 'launch', 'p2_a_spawn_tb3.launch.py')
            ),
            launch_arguments={
                'x_pos': '-6.1',
                'y_pos': '-7.1',
                'yaw_rot': '1.57',
                'robot_name' :'turtlebot_3',
            }.items()
        ),

        # Integerating Nav2 Stack
        # This section starts the bringup_launch.py launch file from the nav2_bringup package for navigation2 functionality.
        IncludeLaunchDescription(
            PythonLaunchDescriptionSource([nav2_launch_file_dir, '/bringup_launch.py']),
            launch_arguments={
                'map': map_dir,
                'use_sim_time': use_sim_time,
                'params_file': param_dir}.items(),
        ),

        # Spawn Maze
        # This section spawns a maze.
        Node(
            package='drive_tb3',
            executable='p6_b_sdf_spawner',
            name='maze_model',
            arguments=[maze_path,"Maze","0.0","0.0"]
        ),

        # Launch Rviz2 with Configuration
        # This section starts the Rviz2 node for visualization.
        Node(
            package='rviz2',
            executable='rviz2',
            name='rviz2',
            arguments=['-d', rviz_config_dir],
            parameters=[{'use_sim_time': use_sim_time}],
            output='screen'),
    ])


#####################################################
# Written by Kyle Michaels, see README.md for notes #
#####################################################

import tkinter as tk
import ctypes
from ctypes import wintypes
import time
import tempfile
import os
import sys

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

##### ADD DATA #####
iconFile='HoneyBadgers48.ico'

if getattr(sys, 'frozen', False):
    application_path = sys._MEIPASS
elif __file__:
    application_path = os.path.dirname(__file__)

###### C struct definitions #####

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

###### Classes #####
#a signle preplanned point object
class Point:
    def __init__(self, lat, lon, alt):
        if(lat>=0):
            self.NS=2 #North
        else:
            self.NS=8 #South
        self.lat=str(abs(lat)).zfill(8)[0:6]
        self.latd=str(abs(lat)).zfill(8)[6:8]

        if(lon>=0):
            self.EW=6 #East
        else:
            self.EW=3 #West
        self.lon=str(abs(lon)).zfill(8)[0:6]
        self.lond=str(abs(lon)).zfill(8)[6:8]

        if(alt < 0):
            self.alt = str(0)
        else:
            self.alt = str(alt)

###### Functions #####
def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

# msdn.microsoft.com/en-us/library/dd375731 source for scan codes
def numK(num):
    if(num<0 or num>9):
        print("num out of bounds func only handles int 0-9")
        return 0x61
    else:
        return num+0x60

def LALT():
    return 0xA4

def LCTRL():
    return 0xA2

#couldn't find a scan code for Num Enter
def ENTER():
    return 0x0D

def NUMDEC(): #Num.
    return 0x6E

def sendNum(num):
    numStr=str(num)
    for ltr in numStr:
        key=int(ltr)
        sendKey(numK(key))
        time.sleep(.2)

def sendKey(key):
    PressKey(key)
    time.sleep(.2)
    ReleaseKey(key)

def sendCombo(mod, key):
    PressKey(mod)
    PressKey(key)
    time.sleep(.1)
    ReleaseKey(key)
    ReleaseKey(mod)

#Create the points from file for now
def CreatePlan():
    coord=entCoords.get("1.0",'end-1c')
    coord=coord.split("\n")
    plan=[]
    plans=1
    loop=0
    for line in coord:
        if(line=="" or plans==6):
            print("plans equalled " + str(plans))
            break
        elif(loop==0):
            lat=int(line)
            loop=1
        elif(loop==1):
            lon=int(line)
            loop=2
        elif(loop==2):
            elev=int(line)
            plan.append(Point(lat, lon, elev))
            loop=0
            plans+=1
    return plan

def main():
    PP=CreatePlan()
    # give time for user to switch back to dcs
    try:
        ddd=int(boxDelay.get())
    except:
        ddd=15
    time.sleep(ddd)
    #start sending keys
    #ONCE AGAIN ASSUMING JDAMS ARE ALREAD SELECTED
    #should prevent the Main to support bug     L MDI PB 4
    sendCombo(LCTRL(),numK(7))
    time.sleep(.5)
    #Menu           L MDI PB 18
    sendCombo(LCTRL(),numK(6))
    time.sleep(.5)
    #JDAM DISPLAY   L MDI PB 11
    sendCombo(LCTRL(),numK(8))
    time.sleep(.5)
    #MSN Button     L MDI PB 4
    sendCombo(LCTRL(),numK(7))
    time.sleep(.5)
    #PP1            L MDI PB 6
    sendCombo(LCTRL(),numK(1))
    time.sleep(.5)
    #UFC CLEAR      Make sure TGT UFC is unboxed
    sendKey(NUMDEC())
    time.sleep(.5)
    sendKey(NUMDEC())
    time.sleep(.5)
    #TGT UFC        L MDI PB 14
    sendCombo(LCTRL(),numK(9))
    time.sleep(.5)
    #POSITION       UFC OPTION 3
    sendCombo(LALT(),numK(3))
    time.sleep(.5)
    #lat            UFC OPTION 1
    sendCombo(LALT(),numK(1))
    time.sleep(.5)
    #Type latitude
    x=1
    for pnt in PP:
        sendCombo(LCTRL(),numK(x))
        time.sleep(.3)
        x+=1
        sendNum(pnt.NS)
        time.sleep(.2)
        sendNum(pnt.lat)
        sendKey(ENTER())
        time.sleep(1)
        sendNum(pnt.latd)
        sendKey(ENTER())
        time.sleep(.2)

    #lon            UFC OPTION 3
    sendCombo(LALT(),numK(3))
    #Type longitude
    x=1
    for pnt in PP:
        sendCombo(LCTRL(),numK(x))
        time.sleep(.3)
        x+=1
        sendNum(pnt.EW)
        time.sleep(.2)
        sendNum(pnt.lon)
        sendKey(ENTER())
        time.sleep(1)
        sendNum(pnt.lond)
        sendKey(ENTER())
        time.sleep(.2)

    #reselect elevation
    #TGT UFC        L MDI PB 14
    sendCombo(LCTRL(),numK(9))
    time.sleep(.5)
    #TGT UFC        L MDI PB 14
    sendCombo(LCTRL(),numK(9))
    time.sleep(.5)
    #ELEVATION      UFC OPTION 4
    sendCombo(LALT(),numK(4))
    time.sleep(.5)
    #FEET           UFC OPTION 3
    sendCombo(LALT(),numK(3))
    time.sleep(.5)
    #type elevations
    x=1
    for pnt in PP:
        sendCombo(LCTRL(),numK(x))
        time.sleep(.3)
        x+=1
        sendNum(pnt.alt)
        sendKey(ENTER())
        time.sleep(.2)

##### Create the GUI #####
#Create the window container
w=tk.Tk()
w.title("F18 JDAM \"Cartridge Loader\"")
w.iconbitmap(default=os.path.join(application_path, iconFile))
w.resizable(False, False)
#create a label
lblHere=tk.Label(w,text="Paste Coordinates here:")
lblHere.grid(row=0, sticky="W", padx=10)
#create data entry box
entCoords=tk.Text(w, height=13, width=50)
entCoords.grid(row=1, column=0, columnspan=2, padx=10)
#create another label for the delay
lblDelay=tk.Label(w,text="Set Alt-tab Delay(sec):")
lblDelay.grid(row=2, column=0, sticky="E", padx=10, pady=10)
#create spin box
boxDelay=tk.Spinbox(w, values=(5,10,15,20,25,30,35,40,45,50,55,60), validate="all")
boxDelay.grid(row=2, column=1, sticky="W", padx=10)
#create run button
btnRun=tk.Button(w, text='Run', width=25, command=main)
btnRun.grid(row=3, column=0, columnspan=2, pady=7)
##### Run some code #####
w.mainloop()
# main()


#!/usr/bin/env python3
import string
template = """
	public class LetterBlock{name}: LetterBlock<Items.Placeable.LetterBlock{name}> {{
		public override int _getFrame() {{ return {frame}; }}
	}}"""

# all names have a Z in front so they sort at the end of the list.
# (this does not apply to blocks, but they need to match the items.)
# funny how blocks that don't do anything have taken the most effort
# so far, aside from trying to make the stupid gravity shit work.
names = {
	'`':  "ZGrave",
	'-':  "ZHyphen",
	'=':  "ZEqual",
	'[':  "ZLeftBracket",
	']':  "ZRightBracket",
	'\\': "ZBackslash",
	';':  "ZSemicolon",
	"'":  "ZApostrophe",
	',':  "ZComma",
	'.':  "ZPeriod",
	'/':  "ZSlash",
}

for i, c in enumerate(string.ascii_uppercase + string.digits + "-=[]\\;',./`"):
	name = names.get(c, c)
	print(template.format(name=name, frame=i).replace('\t', '    '), end='')

# you will have to manually fix instances of \ and " in the output


# Name: Tan Tze Guang
# Class: 13S28
# Date: 6 April 2013
# This program saves the data of employees working salary

def check_ID(ID, invalid): # Checks ID in correct format, loops otherwise
    if ID[0].isalpha() and ID[1:6].isdigit():
        invalid = False
        return ID,invalid
    else:
        invalid = True
        print("Error, invalid ID")
        return ID, invalid

def check_name(name,invalid): # Checks Name of Employee is within 20 characters long, loops otherwise
    if len(name) <= 20:
        invalid = False
        return name,invalid
    else:
        invalid = True
        print("Error, Name must be shorter than 20 characters")
        return name, invalid

def check_type(Type,invalid): # Checks Type of payment is hourly or salary, loops otherwise
    if Type == "S" or Type == "s":
        invalid = False
        return Type,invalid
    elif Type == "H" or Type == "h":
        invalid = False
        return Type,invalid
    else:
        invalid = True
        print("Error, invalid employee type")
        return Type,invalid

def check_salary(salary,invalid): # Checks Salary is in range of $600 to $5000, loops otherwise
    if salary >= 600.00 and salary <= 5000.00:
        invalid = False
        return salary,invalid
    else:
        invalid = True
        print("Error, salary out of range")
        return salary,invalid

def check_rate(rate,invalid): # Checks hourly rate is in range $5 to $120,loops otherwise
    if rate >= 5.00 and rate <= 120.00:
        invalid = False
        return rate,invalid
    else:
        invalid = True
        print("Error, Rate out of range")
        return rate,invalid

def check_hours(hours,invalid): # Checks hours worked is in range 5 to 40 hours,loops otherwise
    if hours >= 5.00 and hours <= 40.00:
        invalid = False
        return hours,invalid
    else:
        invalid = True
        print("Error, hours out of range")
        return hours,invalid

def check_repeat(repeat,invalid): # Checks if there are any more entries to be input
    if repeat[0] == "N" or repeat[0] == "n":
        invalid = False
        return repeat,invalid
    else:
        invalid = True
        return repeat,invalid

def output(ID,Name,Type,Salary,Rate,Hours,outfile): # Writes the data to file in the following format
    print("ID:",ID, file = outfile)
    print("Name:",Name, file = outfile)
    print("Type:",Type, file = outfile)
    print("Salary:",Salary, file = outfile)
    print("Hourly Rate:",Rate, file = outfile)
    print("Hours Worked:",Hours, file = outfile)
    print("",file = outfile)

def main():
    print("This program writes the employees working salary into a different file.")
    outfileName = input("Enter the file to save the data to: ")
    outfile = open(outfileName,"w") # Prepares the file to receive data

    repeat = True # Forces the program to repeat if left unchanged
    while repeat:
        invalid_ID = True
        while invalid_ID: # Constantly asks for an input until ID is valid
            EmployeeID = input("Enter your ID: ")
            EmployeeID, invalid_ID = check_ID(EmployeeID, invalid_ID)

        invalid_name = True
        while invalid_name: # Asks for name lesser than 20 characters
            Name = input("Enter your name: ")
            Name,invalid_name = check_name(Name,invalid_name)

        invalid_Type = True
        while invalid_Type: # Asks for payment mode. If not valid, it will ask again
            EmployeeType = input("Enter the form of payment: ")
            EmployeeType,invalid_Type = check_type(EmployeeType,invalid_Type)

        if EmployeeType == "S" or EmployeeType == "s":
            invalid_salary = True
            while invalid_salary: # Ask for monthly salary and checks if it is in range
                Salary = eval(input("Enter your monthly salary: (between $600 to $5000) "))
                Salary,invalid_salary = check_salary(Salary,invalid_salary)

            output(EmployeeID,Name,EmployeeType,Salary,"NIL","NIL",outfile) # Calls function to write to file

        elif EmployeeType == "H" or EmployeeType == "h":
            invalid_rate = True
            while invalid_rate: # Ask for hourly wage and check if it is in range
                HourlyRate = eval(input("Enter the your hourly pay: (between $5 to $120) "))
                HourlyRate, invalid_rate = check_rate(HourlyRate,invalid_rate)

            invalid_hour = True
            while invalid_hour: # Ask for hours worked and check if it is in range
                HoursWorked = eval(input("Enter hours worked: (between 5 hours to 40 hours) "))
                HoursWorked , invalid_hour = check_hours(HoursWorked, invalid_hour)

            output(EmployeeID,Name,EmployeeType,"NIL",HourlyRate,HoursWorked,outfile) # Calls function to write to file

        redo = input("Any more entries: (Y/N)")
        redo,repeat = check_repeat(redo,repeat) # Checks if there is any more data to process

    outfile.close()

main()


def solution(n, m, x, y, r, c, k):
    stack = [(x, y, '')]
    result = "impossible"
    while stack:
        yy, xx, path = stack.pop()
        if len(path) == k and (yy, xx) == (r, c):
            result = path
            break
        remain, shortest_path = k - len(path), abs(yy - r) + abs(xx - c)
        if remain < shortest_path or remain % 2 != shortest_path % 2:
            continue
        if yy > 1:
            stack.append((yy - 1, xx, path + 'u'))
        if xx < m:
            stack.append((yy, xx + 1, path + 'r'))
        if xx > 1:
            stack.append((yy, xx - 1, path + 'l'))
        if yy < n:
            stack.append((yy + 1, xx, path + 'd'))
    return result

프로그래머스/level3/미로 탈출 명령어.py

미로 탈출 명령어.py


#Imports the arguments module from the system
from sys import argv

#From the system line, the argv pulls the script name and the filename it took as an arguments
script, filename = argv

#Open the filename and assign it to the variable txt
txt = open(filename)

#print a simple leadup
print("Here's your file %r:" % filename)
#print the txt file contents by calling the read function (a function of text objects)
print(txt.read())

#print a simple question
print("Type the filename again:")
#assign the inputted filename to the variable file_again
file_again = input("> ")

#opens the file again using the new user-input name
txt_again = open(file_again)

#print the txt file contents again
print(txt_again.read())

#Benefits of argv method
#Can be called as part of the function without further input from user-input
#Benefits of input() method
#Explicitly asks user to enter the file name before continuing code (whereas argv would create an error)

txt.close()
txt_again.close()

#print(txt.read())
#The last print will fail because the txt file has already been closed


import pandas as pd
from scipy.stats import ttest_ind, ttest_rel
import math
import matplotlib.pyplot as plt
import numpy as np

totalDf = pd.read_csv('Люшер_fatigue_.csv', sep=',', header=0)

results = []

for i in range(0,12):
    data = totalDf[totalDf['Gr_ug'] == i + 1]

    data1 = data['before'].tolist()
    data2 = data['in'].tolist()
    data3 = data['after'].tolist()

    row = []

    stat, p = ttest_rel(data2, data3)
    print(stat, p)
    if math.isnan(p):
        p = 0
    row.append(p)

    results.append(row)

with open('ttest.csv', 'w') as f:
    for r in results:
        f.write(",".join(list(map(str, r))))
        f.write("\n")

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(results,cmap='binary', vmin=0, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,len(results),1)
ticks_labels = np.arange(1,len(results) + 1,1)
ax.set_xticks(np.arange(1))
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(np.arange(1))
ax.set_yticklabels(ticks_labels)

plt.show()

print(results)


import numpy as np
import cv2
import time
from cv2 import aruco

aruco_dict = aruco.Dictionary_get(aruco.DICT_ARUCO_ORIGINAL)
parameters =  aruco.DetectorParameters_create()
cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Flip the frame depending on how pi camera is mounted
    # flipped = cv2.flip(frame.copy(), -1)

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
    markers = aruco.drawDetectedMarkers(frame.copy(), corners, ids)

    # Display the resulting frame
    cv2.imshow('frame', markers)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


from datetime import datetime
import random
import time
from typing import Dict

import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session

from app import crud
from app.api.api_v1.api import tasks as m
from app.config import settings
from app.utils.timeutil import convert_datetime_to_timestamp
from tests.utils.tasks import create_task

@pytest.fixture(scope="function")
def mock_controller(mocker):
    c = mocker.Mock()

    c.get_labels_of_user.return_value = {
        "cat": {
            "name": "cat",
            "aliases": [],
            "create_time": 1647075201.0,
            "update_time": 1647075202.0,
            "id": 0,
        },
        "dog": {
            "id": 1,
            "name": "dog",
            "aliases": ["puppy"],
            "create_time": 1647076203.0,
            "update_time": 1647076404.0,
        },
    }
    return c

@pytest.fixture(scope="function")
def mock_controller_request(mocker):
    r = mocker.Mock()
    mocker.patch.object(m, "ControllerRequest", return_value=r)

@pytest.fixture(scope="function")
def mock_db(mocker):
    return mocker.Mock()

@pytest.fixture(scope="function")
def mock_viz(mocker):
    return mocker.Mock()

class TestListTasks:
    def test_list_tasks_succeed(
        self,
        db: Session,
        client: TestClient,
        user_id: int,
        normal_user_token_headers: Dict[str, str],
        mocker,
        mock_controller,
    ):
        for _ in range(3):
            create_task(db, user_id)
        r = client.get(f"{settings.API_V1_STR}/tasks/", params={"limit": 100}, headers=normal_user_token_headers)
        items = r.json()["result"]["items"]
        total = r.json()["result"]["total"]
        assert len(items) == total != 0

class TestDeleteTask:
    def test_delete_task(
        self,
        db: Session,
        client: TestClient,
        normal_user_token_headers,
        mocker,
        mock_controller,
        user_id: int,
    ):
        task = create_task(db, user_id)
        task_id = task.id
        r = client.delete(f"{settings.API_V1_STR}/tasks/{task_id}", headers=normal_user_token_headers)
        assert r.json()["result"]["is_deleted"]

class TestGetTask:
    def test_get_single_task(
        self,
        db: Session,
        client: TestClient,
        normal_user_token_headers,
        mocker,
        mock_controller,
        user_id: int,
    ):
        task = create_task(db, user_id)
        name = task.name
        task_id = task.id

        r = client.get(f"{settings.API_V1_STR}/tasks/{task_id}", headers=normal_user_token_headers)
        assert r.json()["result"]["name"] == name

    def test_get_single_task_not_found(self, client: TestClient, normal_user_token_headers, mocker):
        task_id = random.randint(100000, 900000)
        r = client.get(f"{settings.API_V1_STR}/tasks/{task_id}", headers=normal_user_token_headers)
        assert r.status_code == 404

class TestTerminateTask:
    def test_terminate_task_discard_result(
        self,
        db: Session,
        client: TestClient,
        normal_user_token_headers,
        mocker,
        mock_controller,
        user_id: int,
    ):
        task = create_task(db, user_id)
        task_id = task.id
        r = client.post(
            f"{settings.API_V1_STR}/tasks/{task_id}/terminate",
            headers=normal_user_token_headers,
            json={"fetch_result": False},
        )
        assert r.json()["result"]["state"] == m.TaskState.terminate.value

    def test_terminate_task_keep_result(
        self,
        db: Session,
        client: TestClient,
        normal_user_token_headers,
        mocker,
        mock_controller,
        user_id: int,
    ):
        task = create_task(db, user_id)
        task_id = task.id
        r = client.post(
            f"{settings.API_V1_STR}/tasks/{task_id}/terminate",
            headers=normal_user_token_headers,
            json={"fetch_result": True},
        )
        # Note that we map premature back to terminate for frontend
        assert r.json()["result"]["state"] == m.TaskState.terminate.value

class TestUpdateTaskStatus:
    def test_update_task_status_to_done(
        self,
        db: Session,
        client: TestClient,
        normal_user_token_headers,
        api_key_headers,
        mocker,
        mock_controller,
        user_id: int,
    ):
        task = create_task(db, user_id)
        task_hash = task.hash
        assert task.last_message_datetime is None

        data = {
            "user_id": 233,
            "hash": task_hash,
            "state": m.TaskState.running,
            "percent": 0.5,
            "timestamp": time.time(),
        }
        r = client.post(
            f"{settings.API_V1_STR}/tasks/status",
            headers=api_key_headers,
            json=data,
        )
        assert r.json()["result"]["state"] == m.TaskState.running.value
        assert r.json()["result"]["percent"] == 0.5

    def test_update_task_status_skip_obsolete_msg(
        self,
        db: Session,
        client: TestClient,
        normal_user_token_headers,
        api_key_headers,
        mocker,
        mock_controller,
        user_id: int,
    ):
        task = create_task(db, user_id)
        task_hash = task.hash
        task = crud.task.update_last_message_datetime(db, id=task.id, dt=datetime.utcnow())

        data = {
            "user_id": 233,
            "hash": task_hash,
            "state": m.TaskState.running,
            "percent": 0.5,
            "timestamp": convert_datetime_to_timestamp(task.last_message_datetime) - 1,
        }
        r = client.post(
            f"{settings.API_V1_STR}/tasks/status",
            headers=api_key_headers,
            json=data,
        )
        assert r.json()["code"] == m.ObsoleteTaskStatus.code


# encoding: utf-8

from __future__ import unicode_literals

import pytest

from common import FieldExam
from marrow.mongo import Document
from marrow.mongo.field import Embed, String
from marrow.mongo.trait import Derived

class Concrete(Derived, Document):
	__collection__ = 'collection'

	foo = String()
	bar = String()

class TestSingularEmbedField(FieldExam):
	__field__ = Embed
	__args__ = (Concrete, )

	def test_native_ingress(self, Sample):
		inst = Sample.from_mongo({'field': Concrete(foo=27, bar=42)})
		assert isinstance(inst.field, Concrete)

	def test_native_ingress_cast(self, Sample):
		inst = Sample.from_mongo({'field': {'foo': 27, 'bar': 42}})
		assert isinstance(inst.field, Concrete)
		assert inst.field.foo == 27
		assert inst.field.bar == 42

	def test_native_egress_cast(self, Sample):
		inst = Sample(field=Concrete())
		assert isinstance(inst.field, Concrete)

	def test_foreign_assignment_cast(self, Sample):
		inst = Sample()
		inst.field = {}
		assert isinstance(inst['field'], Concrete)

	def test_unsupported_native_cast(self, Sample):
		inst = Sample.from_mongo({'field': Document()})

		with pytest.raises(ValueError):
			inst.field

	def test_unsupported_foreign_cast(self, Sample):
		inst = Sample()

		with pytest.raises(ValueError):
			inst.field = Document()

class TestEmbedByName(FieldExam):
	__field__ = Embed
	__args__ = ('Document', )

	def test_native_ingress_cast(self, Sample):
		inst = Sample.from_mongo({'field': {'foo': 27, 'bar': 42}})
		assert isinstance(inst.field, Document)
		assert inst.field['foo'] == 27
		assert inst.field['bar'] == 42


import re
from datetime import date, datetime, time, timedelta, timezone

import pytest
from dirty_equals import HasRepr

from pydantic import BaseModel, FutureDate, PastDate, ValidationError, condate

from .conftest import Err

def create_tz(minutes):
    return timezone(timedelta(minutes=minutes))

@pytest.fixture(scope='module', name='DateModel')
def date_model_fixture():
    class DateModel(BaseModel):
        d: date

    return DateModel

@pytest.mark.parametrize(
    'value,result',
    [
        # Valid inputs
        (1_493_942_400, date(2017, 5, 5)),
        (1_493_942_400_000, date(2017, 5, 5)),
        (0, date(1970, 1, 1)),
        ('2012-04-23', date(2012, 4, 23)),
        (b'2012-04-23', date(2012, 4, 23)),
        (date(2012, 4, 9), date(2012, 4, 9)),
        (datetime(2012, 4, 9, 0, 0), date(2012, 4, 9)),
        # Invalid inputs
        (datetime(2012, 4, 9, 12, 15), Err('Datetimes provided to dates should have zero time - e.g. be exact dates')),
        ('x20120423', Err('Input should be a valid date or datetime, input is too short')),
        ('2012-04-56', Err('Input should be a valid date or datetime, day value is outside expected range')),
        (19_999_958_400, date(2603, 10, 11)),  # just before watershed
        (20000044800, Err('type=date_from_datetime_inexact,')),  # just after watershed
        (1_549_238_400, date(2019, 2, 4)),  # nowish in s
        (1_549_238_400_000, date(2019, 2, 4)),  # nowish in ms
        (1_549_238_400_000_000, Err('Input should be a valid date or datetime, dates after 9999')),  # nowish in μs
        (1_549_238_400_000_000_000, Err('Input should be a valid date or datetime, dates after 9999')),  # nowish in ns
        ('infinity', Err('Input should be a valid date or datetime, input is too short')),
        (float('inf'), Err('Input should be a valid date or datetime, dates after 9999')),
        (int('1' + '0' * 100), Err('Input should be a valid date or datetime, dates after 9999')),
        (1e1000, Err('Input should be a valid date or datetime, dates after 9999')),
        (float('-infinity'), Err('Input should be a valid date or datetime, dates before 1600')),
        (float('nan'), Err('Input should be a valid date or datetime, NaN values not permitted')),
    ],
)
def test_date_parsing(DateModel, value, result):
    if isinstance(result, Err):
        with pytest.raises(ValidationError, match=result.message_escaped()):
            DateModel(d=value)
    else:
        assert DateModel(d=value).d == result

@pytest.fixture(scope='module', name='TimeModel')
def time_model_fixture():
    class TimeModel(BaseModel):
        d: time

    return TimeModel

@pytest.mark.parametrize(
    'value,result',
    [
        # Valid inputs
        ('09:15:00', time(9, 15)),
        ('10:10', time(10, 10)),
        ('10:20:30.400', time(10, 20, 30, 400_000)),
        (b'10:20:30.400', time(10, 20, 30, 400_000)),
        (time(4, 8, 16), time(4, 8, 16)),
        (3610, time(1, 0, 10)),
        (3600.5, time(1, 0, 0, 500000)),
        (86400 - 1, time(23, 59, 59)),
        # Invalid inputs
        ('4:8:16', Err('Input should be in a valid time format, invalid character in hour [type=time_parsing,')),
        (86400, Err('Input should be in a valid time format, numeric times may not exceed 86,399 seconds')),
        ('xxx', Err('Input should be in a valid time format, input is too short [type=time_parsing,')),
        ('091500', Err('Input should be in a valid time format, invalid time separator, expected `:`')),
        (b'091500', Err('Input should be in a valid time format, invalid time separator, expected `:`')),
        ('09:15:90', Err('Input should be in a valid time format, second value is outside expected range of 0-59')),
        ('11:05:00Y', Err('Input should be in a valid time format, unexpected extra characters at the end of the inp')),
        # # https://github.com/pydantic/speedate/issues/10
        # ('11:05:00-05:30', time(11, 5, 0, tzinfo=create_tz(-330))),
        # ('11:05:00-0530', time(11, 5, 0, tzinfo=create_tz(-330))),
        # ('11:05:00Z', time(11, 5, 0, tzinfo=timezone.utc)),
        # ('11:05:00+00', time(11, 5, 0, tzinfo=timezone.utc)),
        # ('11:05-06', time(11, 5, 0, tzinfo=create_tz(-360))),
        # ('11:05+06', time(11, 5, 0, tzinfo=create_tz(360))),
        # ('11:05:00-25:00', errors.TimeError),
    ],
)
def test_time_parsing(TimeModel, value, result):
    if isinstance(result, Err):
        with pytest.raises(ValidationError, match=result.message_escaped()):
            TimeModel(d=value)
    else:
        assert TimeModel(d=value).d == result

@pytest.fixture(scope='module', name='DatetimeModel')
def datetime_model_fixture():
    class DatetimeModel(BaseModel):
        dt: datetime

    return DatetimeModel

@pytest.mark.parametrize(
    'value,result',
    [
        # Valid inputs
        # values in seconds
        (1_494_012_444.883_309, datetime(2017, 5, 5, 19, 27, 24, 883_309)),
        (1_494_012_444, datetime(2017, 5, 5, 19, 27, 24)),
        # values in ms
        (1_494_012_444_000, datetime(2017, 5, 5, 19, 27, 24)),
        ('2012-04-23T09:15:00', datetime(2012, 4, 23, 9, 15)),
        ('2012-04-23T09:15:00Z', datetime(2012, 4, 23, 9, 15, 0, 0, timezone.utc)),
        ('2012-04-23T10:20:30.400+02:30', datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(150))),
        ('2012-04-23T10:20:30.400+02:00', datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(120))),
        ('2012-04-23T10:20:30.400-02:00', datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))),
        (b'2012-04-23T10:20:30.400-02:00', datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))),
        (datetime(2017, 5, 5), datetime(2017, 5, 5)),
        (0, datetime(1970, 1, 1, 0, 0, 0)),
        # # Invalid inputs
        ('1494012444.883309', Err('Input should be a valid datetime, invalid date separator')),
        ('1494012444', Err('Input should be a valid datetime, invalid date separator')),
        (b'1494012444', Err('Input should be a valid datetime, invalid date separator')),
        ('1494012444000.883309', Err('Input should be a valid datetime, invalid date separator')),
        ('-1494012444000.883309', Err('Input should be a valid datetime, invalid character in year')),
        ('2012-4-9 4:8:16', Err('Input should be a valid datetime, invalid character in month')),
        ('x20120423091500', Err('Input should be a valid datetime, invalid character in year')),
        ('2012-04-56T09:15:90', Err('Input should be a valid datetime, day value is outside expected range')),
        ('2012-04-23T11:05:00-25:00', Err('Input should be a valid datetime, timezone offset must be less than 24 ho')),
        (19_999_999_999, datetime(2603, 10, 11, 11, 33, 19)),  # just before watershed
        (20_000_000_001, datetime(1970, 8, 20, 11, 33, 20, 1000)),  # just after watershed
        (1_549_316_052, datetime(2019, 2, 4, 21, 34, 12, 0)),  # nowish in s
        (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000)),  # nowish in ms
        (1_549_316_052_104_324, Err('Input should be a valid datetime, dates after 9999')),  # nowish in μs
        (1_549_316_052_104_324_096, Err('Input should be a valid datetime, dates after 9999')),  # nowish in ns
        ('infinity', Err('Input should be a valid datetime, input is too short')),
        (float('inf'), Err('Input should be a valid datetime, dates after 9999')),
        (float('-inf'), Err('Input should be a valid datetime, dates before 1600')),
        (1e50, Err('Input should be a valid datetime, dates after 9999')),
        (float('nan'), Err('Input should be a valid datetime, NaN values not permitted')),
    ],
)
def test_datetime_parsing(DatetimeModel, value, result):
    if isinstance(result, Err):
        with pytest.raises(ValidationError, match=result.message_escaped()):
            DatetimeModel(dt=value)
    else:
        assert DatetimeModel(dt=value).dt == result

@pytest.fixture(scope='module', name='TimedeltaModel')
def timedelta_model_fixture():
    class TimedeltaModel(BaseModel):
        d: timedelta

    return TimedeltaModel

@pytest.mark.parametrize(
    'delta',
    [
        timedelta(days=4, minutes=15, seconds=30, milliseconds=100),  # fractions of seconds
        timedelta(hours=10, minutes=15, seconds=30),  # hours, minutes, seconds
        timedelta(days=4, minutes=15, seconds=30),  # multiple days
        timedelta(days=1, minutes=00, seconds=00),  # single day
        timedelta(days=-4, minutes=15, seconds=30),  # negative durations
        timedelta(minutes=15, seconds=30),  # minute & seconds
        timedelta(seconds=30),  # seconds
    ],
)
def test_parse_python_format(TimedeltaModel, delta):
    assert TimedeltaModel(d=delta).d == delta
    # assert TimedeltaModel(d=str(delta)).d == delta

@pytest.mark.parametrize(
    'value,result',
    [
        # seconds
        (timedelta(seconds=30), timedelta(seconds=30)),
        (30, timedelta(seconds=30)),
        (30.1, timedelta(seconds=30, milliseconds=100)),
        (9.9e-05, timedelta(microseconds=99)),
        # minutes seconds
        ('00:15:30', timedelta(minutes=15, seconds=30)),
        ('00:05:30', timedelta(minutes=5, seconds=30)),
        # hours minutes seconds
        ('10:15:30', timedelta(hours=10, minutes=15, seconds=30)),
        ('01:15:30', timedelta(hours=1, minutes=15, seconds=30)),
        # ('100:200:300', timedelta(hours=100, minutes=200, seconds=300)),
        # days
        ('4d,00:15:30', timedelta(days=4, minutes=15, seconds=30)),
        ('4d,10:15:30', timedelta(days=4, hours=10, minutes=15, seconds=30)),
        # fractions of seconds
        ('00:15:30.1', timedelta(minutes=15, seconds=30, milliseconds=100)),
        ('00:15:30.01', timedelta(minutes=15, seconds=30, milliseconds=10)),
        ('00:15:30.001', timedelta(minutes=15, seconds=30, milliseconds=1)),
        ('00:15:30.0001', timedelta(minutes=15, seconds=30, microseconds=100)),
        ('00:15:30.00001', timedelta(minutes=15, seconds=30, microseconds=10)),
        ('00:15:30.000001', timedelta(minutes=15, seconds=30, microseconds=1)),
        (b'00:15:30.000001', timedelta(minutes=15, seconds=30, microseconds=1)),
        # negative
        ('-4d,00:15:30', timedelta(days=-4, minutes=-15, seconds=-30)),
        (-172800, timedelta(days=-2)),
        ('-00:15:30', timedelta(minutes=-15, seconds=-30)),
        ('-01:15:30', timedelta(hours=-1, minutes=-15, seconds=-30)),
        (-30.1, timedelta(seconds=-30, milliseconds=-100)),
        # iso_8601
        ('30', Err('Input should be a valid timedelta, "day" identifier')),
        ('P4Y', timedelta(days=1460)),
        ('P4M', timedelta(days=120)),
        ('P4W', timedelta(days=28)),
        ('P4D', timedelta(days=4)),
        ('P0.5D', timedelta(hours=12)),
        ('PT5H', timedelta(hours=5)),
        ('PT5M', timedelta(minutes=5)),
        ('PT5S', timedelta(seconds=5)),
        ('PT0.000005S', timedelta(microseconds=5)),
        (b'PT0.000005S', timedelta(microseconds=5)),
    ],
)
def test_parse_durations(TimedeltaModel, value, result):
    if isinstance(result, Err):
        with pytest.raises(ValidationError, match=result.message_escaped()):
            TimedeltaModel(d=value)
    else:
        assert TimedeltaModel(d=value).d == result

@pytest.mark.parametrize(
    'field, value, error_message',
    [
        ('dt', [], 'Input should be a valid datetime'),
        ('dt', {}, 'Input should be a valid datetime'),
        ('dt', object, 'Input should be a valid datetime'),
        ('d', [], 'Input should be a valid date'),
        ('d', {}, 'Input should be a valid date'),
        ('d', object, 'Input should be a valid date'),
        ('t', [], 'Input should be a valid time'),
        ('t', {}, 'Input should be a valid time'),
        ('t', object, 'Input should be a valid time'),
        ('td', [], 'Input should be a valid timedelta'),
        ('td', {}, 'Input should be a valid timedelta'),
        ('td', object, 'Input should be a valid timedelta'),
    ],
)
def test_model_type_errors(field, value, error_message):
    class Model(BaseModel):
        dt: datetime = None
        d: date = None
        t: time = None
        td: timedelta = None

    with pytest.raises(ValidationError) as exc_info:
        Model(**{field: value})
    assert len(exc_info.value.errors()) == 1
    error = exc_info.value.errors()[0]
    assert error['msg'] == error_message

@pytest.mark.parametrize('field', ['dt', 'd', 't', 'dt'])
def test_unicode_decode_error(field):
    class Model(BaseModel):
        dt: datetime = None
        d: date = None
        t: time = None
        td: timedelta = None

    with pytest.raises(ValidationError) as exc_info:
        Model(**{field: b'\x81\x81\x81\x81\x81\x81\x81\x81'})
    assert exc_info.value.error_count() == 1
    # errors vary

def test_nan():
    class Model(BaseModel):
        dt: datetime
        d: date

    with pytest.raises(ValidationError) as exc_info:
        Model(dt=float('nan'), d=float('nan'))
    # insert_assert(exc_info.value.errors())
    assert exc_info.value.errors() == [
        {
            'type': 'datetime_parsing',
            'loc': ('dt',),
            'msg': 'Input should be a valid datetime, NaN values not permitted',
            'input': HasRepr('nan'),
            'ctx': {'error': 'NaN values not permitted'},
        },
        {
            'type': 'date_from_datetime_parsing',
            'loc': ('d',),
            'msg': 'Input should be a valid date or datetime, NaN values not permitted',
            'input': HasRepr('nan'),
            'ctx': {'error': 'NaN values not permitted'},
        },
    ]

@pytest.mark.parametrize(
    'constraint,msg,ok_value,error_value',
    [
        ('gt', 'greater than', date(2020, 1, 2), date(2019, 12, 31)),
        ('gt', 'greater than', date(2020, 1, 2), date(2020, 1, 1)),
        ('ge', 'greater than or equal to', date(2020, 1, 2), date(2019, 12, 31)),
        ('ge', 'greater than or equal to', date(2020, 1, 1), date(2019, 12, 31)),
        ('lt', 'less than', date(2019, 12, 31), date(2020, 1, 2)),
        ('lt', 'less than', date(2019, 12, 31), date(2020, 1, 1)),
        ('le', 'less than or equal to', date(2019, 12, 31), date(2020, 1, 2)),
        ('le', 'less than or equal to', date(2020, 1, 1), date(2020, 1, 2)),
    ],
)
def test_date_constraints(constraint, msg, ok_value, error_value):
    class Model(BaseModel):
        a: condate(**{constraint: date(2020, 1, 1)})

    assert Model(a=ok_value).dict() == {'a': ok_value}

    with pytest.raises(ValidationError, match=re.escape(f'Input should be {msg} 2020-01-01')):
        Model(a=error_value)

@pytest.mark.parametrize(
    'value,result',
    (
        ('1996-01-22', date(1996, 1, 22)),
        (date(1996, 1, 22), date(1996, 1, 22)),
    ),
)
def test_past_date_validation_success(value, result):
    class Model(BaseModel):
        foo: PastDate

    assert Model(foo=value).foo == result

@pytest.mark.parametrize(
    'value',
    (
        date.today(),
        date.today() + timedelta(1),
        '2064-06-01',
    ),
)
def test_past_date_validation_fails(value):
    class Model(BaseModel):
        foo: PastDate

    with pytest.raises(ValidationError) as exc_info:
        Model(foo=value)
    # insert_assert(exc_info.value.errors())
    assert exc_info.value.errors() == [
        {
            'type': 'date_past',
            'loc': ('foo',),
            'msg': 'Date should be in the past',
            'input': value,
        }
    ]

@pytest.mark.parametrize(
    'value,result',
    (
        (date.today() + timedelta(1), date.today() + timedelta(1)),
        ('2064-06-01', date(2064, 6, 1)),
    ),
)
def test_future_date_validation_success(value, result):
    class Model(BaseModel):
        foo: FutureDate

    assert Model(foo=value).foo == result

@pytest.mark.parametrize(
    'value',
    (
        date.today(),
        date.today() - timedelta(1),
        '1996-01-22',
    ),
)
def test_future_date_validation_fails(value):
    class Model(BaseModel):
        foo: FutureDate

    with pytest.raises(ValidationError) as exc_info:
        Model(foo=value)
    # insert_assert(exc_info.value.errors())
    assert exc_info.value.errors() == [
        {
            'type': 'date_future',
            'loc': ('foo',),
            'msg': 'Date should be in the future',
            'input': value,
        }
    ]


"""Algo
1. left & right ptr are initialised at 0
2. r is used to iterate, such that if the value at right ptr is 0 we increment r
if its non-zero we swap the values of left and right ptr and increment both left
and right ptr
3. note that left and right ptr denote the indices of the array which will be swapped"""

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        l,r=0,0
        while r<len(nums):
            if nums[r]==0:
                r+=1
            else:
                nums[l],nums[r]=nums[r],nums[l]
                l+=1
                r+=1


# -*- coding: utf-8 -*-
# @Time    : 2020/7/28 下午3:52
# @Author  : gavin
# @FileName: 2.二维数据查找.py
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/weixin_35154281

"""
问题描述：
    在一个二维数组中（每个一维数组的长度相同），每一行都按照从左到右递增
的顺序排序，每一列都按照从上到下递增的顺序排序。请完成一个函数，输入这样
的一个二维数组和一个整数，判断数组中是否含有该整数,形式如下:
1  2  3  4
2  3  4  5
6  7  8  9
10 11 12 13

解决方案：
时间复杂度：O(M + N), M和N为行数和列数
空间复杂度：O(1)，没有使用额外的空间存储

原题链接：https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
"""

class Solution:

    def findNumberIn2DArray(self, matrix, target):
        """在二维数组中找到指定数字"""

        i, j = len(matrix) - 1, 0
        while i >= 0 and j < len(matrix[0]):
            if matrix[i][j] > target:
                i -= 1
            elif matrix[i][j] < target:
                j += 1
            else:
                return True

        return False


from django.shortcuts import redirect
from django.views.generic import CreateView

from surveys.models import SurveyAnswer
from surveys.models.annotation import Annotation, Classification, Word
from surveys.models.survey import Survey, Question, Choice, PersonalInformation
from surveys.models.analysis import AnalysisSingle
from surveys.forms.analysis import AnalysisCreator

from django.core import serializers
from ast import literal_eval
from urllib import parse

from ...views.error import permission_user_logged_in, permission_user_owns_survey, permission_user_owns_analysis, \
                            permission_user_owns_annotation
from ...views.helper import get_age_ranges

class AnalysisSingleTerm(CreateView):
    template_name = 'analysis/single.html'
    model = Annotation
    form_class = AnalysisCreator

    def get(self, request, *args, **kwargs):
        permission_user_logged_in(request)

        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        carry_over_terms = []
        carry_over_constraints = {}

        get_variables = request.GET

        if 'analysis' in get_variables:
            analysis = AnalysisSingle.objects.get(pk=get_variables['analysis'])

            permission_user_owns_analysis(request, analysis)

            analysis_name = analysis.name
            analysis_pk = analysis.pk
            survey = Survey.objects.get(pk=analysis.survey.pk)
            annotation = Annotation.objects.get(pk=analysis.annotation.pk)
            operation = "overwrite"

            # this is a little spaghetti, be careful if you're making changes to it
            # if we have no saved terms, just put carry over as an empty list
            if analysis.terms == "":
                carry_over_terms = []
            else:
                # if we have only one saved carry over term
                if isinstance(literal_eval(analysis.terms), int):
                    carry_over_terms = [analysis.terms]
                # if we have many saved carry over terms
                else:
                    carry_over_terms = list(literal_eval(analysis.terms))

            # since carried over constraints are saved in a more verbose way, they experience no issue
            carry_over_constraints = literal_eval(analysis.constraints)

        else:
            analysis_name = get_variables['name']
            analysis_pk = 0
            survey = Survey.objects.get(pk=get_variables['survey'])
            annotation = Annotation.objects.get(pk=get_variables['annotation'])

            permission_user_owns_survey(request, survey)
            permission_user_owns_annotation(request, annotation)

            operation = "save"

        classifications = Classification.objects.filter(annotation=annotation)
        questions = Question.objects.filter(survey=survey)
        choices = Choice.objects.filter(question__in=questions)
        words = Word.objects.filter(classification__in=classifications, choice__in=choices)

        class_ids_used = []
        for w in words.values_list('classification'):
            class_ids_used.append(w[0])

        for classif in classifications:
            if classif.pk not in class_ids_used:
                classifications = classifications.exclude(pk=classif.pk)

        survey_answers = SurveyAnswer.objects.filter(survey=survey)

        pi_js_droplist = {}
        for answer in survey_answers:
            for pi in literal_eval(survey.pi_choices):
                answer_value = getattr(answer.pi_questions, pi)
                pi = pi.replace("_", " ").capitalize()
                if isinstance(answer_value, str):
                    answer_value = answer_value.capitalize()
                if pi in pi_js_droplist:
                    pi_js_droplist[pi].add(answer_value)
                else:
                    pi_js_droplist[pi] = {answer_value}

        pi_js_droplist = get_age_ranges(pi_js_droplist)

        keylist = []
        for k in pi_js_droplist.keys():
            keylist.append(k)

        # this is useful in js
        answers = literal_eval(serializers.serialize("json", survey_answers))
        for answ in answers:
            pi = PersonalInformation.objects.filter(pk=answ['fields']['pi_questions']).values()[0]
            newpi = {}
            for k in pi.keys():
                if pi[k] != '' and k != 'id':
                    nk = k.replace("_", " ").capitalize()
                    newpi[nk] = pi[k]
                    if isinstance(pi[k], str):
                        newpi[nk] = (pi[k]).capitalize()
            answ['fields']['pi_questions'] = newpi

        return self.render_to_response(
            self.get_context_data(form=form,
                                  analysis_name=analysis_name,
                                  survey=survey,
                                  classifications=classifications,
                                  classificiations_js=serializers.serialize("json", classifications),
                                  questions=serializers.serialize("json", questions),
                                  choices=serializers.serialize("json", choices),
                                  words=serializers.serialize("json", words),
                                  pi_choices=literal_eval(survey.pi_choices),
                                  answers=answers,
                                  pi_js_droplist=pi_js_droplist,
                                  constraints_keys=keylist,
                                  operation=operation,
                                  carry_over_terms=carry_over_terms,
                                  carry_over_constraints=carry_over_constraints,
                                  analysis_pk=analysis_pk,
                                  )
        )

    def post(self, request, *args, **kwargs):
        if "delete" in request.POST:
            analysis_pk = request.POST['delete']

            analysis = AnalysisSingle.objects.get(pk=analysis_pk)

            analysis.delete()
            return redirect('./')

        else:
            terms = request.POST['terms']
            constraints = {}

            # transform js serialized dict to a normal py dict
            con_post = parse.parse_qs(request.POST['constraints'])
            for key in con_post.keys():
                nk = key.replace("[]", "")
                constraints[nk] = con_post[key]

            if request.POST['operation'] == "save":

                analysis_name = request.GET['name']
                analysis_survey = Survey.objects.get(pk=request.GET['survey'])
                analysis_annotation = Annotation.objects.get(pk=request.GET['annotation'])

                new_analysis = AnalysisSingle.objects.create(creator=request.user,
                                                             name=analysis_name,
                                                             survey=analysis_survey,
                                                             annotation=analysis_annotation,
                                                             terms=terms,
                                                             constraints=constraints)
                new_analysis.save()

                redirect_pk = new_analysis.pk
                return redirect('./single?analysis=' + str(redirect_pk))

            elif request.POST['operation'] == "overwrite":
                analysis_pk = request.GET['analysis']

                analysis = AnalysisSingle.objects.get(pk=analysis_pk)
                analysis.terms = terms
                analysis.constraints = constraints
                analysis.save()

                redirect_pk = analysis.pk
                return redirect('./single?analysis=' + str(redirect_pk))


from django.shortcuts import render, redirect
from django.views import generic
from django.utils import timezone
from .models import Album, Images, Comments
from .forms import LoginForm, CommentsForm, RegistrationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm

data = '..created this website to showcase my technical skills and ability to design a website using Django framework.'

def index(request):
    context = {'data':data}
    return render(request, 'photos/home.html', context)

def home(request, home):
    albums = Album.objects.all()
    context = {'albums':albums,
               'data':data
              }
    return render(request, 'photos/home.html', context)

class albumsView(generic.ListView):
    template_name = 'photos/albums.html'
    context_object_name = 'albums'
    albums = Album.objects.all()

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

def contact(request, contact):
    context = {"email" : "Email : maneesha.vinayak@gmail.com"}
    return render(request, 'photos/contact.html', context)

def register(request):
    if request.method=='POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            reg = form.save(commit=False)
            reg.save()
            context = {'success':'Successfully Registered. Login to continue', 'data':data}
            return render(request, 'photos/home.html', context)
        else:
            context = {'form':form}
            return render(request, 'photos/register.html', context)
    else:
        form = RegistrationForm()
        context = {'form':form, 'data':data}
        return render(request, 'photos/register.html', context)

def random(request, album_name):
    images = Images.objects.filter(album_name=album_name)
    comments = Comments.objects.all()

    if request.method == 'POST':
        if 'Likes' in request.POST:
            input_image_name = request.POST.get('image_name')
            image = Images.objects.get(image_name=input_image_name)
            image.like_cntr += 1
            image.save()
        elif 'Comment' in request.POST:
            pass

    context = {'album_name':album_name, 'images' :images, 'comments':comments}
    return render(request, 'photos/random.html', context)


import base64
import datetime
import dateutil.relativedelta as relativedelta
import lxml
import urlparse
from datetime import date, datetime
from datetime import timedelta
from openerp.osv.orm import setup_modifiers
from openerp.tools.safe_eval import safe_eval as eval
import logging
from openerp.tools.translate import _
from openerp import tools, api, modules
from openerp import SUPERUSER_ID, tools
from openerp.osv import osv, fields
from urllib import urlencode, quote as quote
from openerp.exceptions import ValidationError

from openerp.fields import Date

_logger = logging.getLogger(__name__)

def format_tz(pool, cr, uid, dt, tz=False, format=False, context=None):
    context = dict(context or {})
    if tz:
        context['tz'] = tz or pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] or "UTC"
    timestamp = datetime.datetime.strptime(dt, tools.DEFAULT_SERVER_DATETIME_FORMAT)

    ts = fields.datetime.context_timestamp(cr, uid, timestamp, context)

    if format:
        return ts.strftime(format)
    else:
        lang = context.get("lang")
        lang_params = {}
        if lang:
            res_lang = pool.get('res.lang')
            ids = res_lang.search(cr, uid, [("code", "=", lang)])
            if ids:
                lang_params = res_lang.read(cr, uid, ids[0], ["date_format", "time_format"])
        format_date = lang_params.get("date_format", '%B-%d-%Y')
        format_time = lang_params.get("time_format", '%I-%M %p')

        fdate = ts.strftime(format_date)
        ftime = ts.strftime(format_time)
        return "%s %s%s" % (fdate, ftime, (' (%s)' % tz) if tz else '')

try:
    # We use a jinja2 sandboxed environment to render mako templates.
    # Note that the rendering does not cover all the mako syntax, in particular
    # arbitrary Python statements are not accepted, and not all expressions are
    # allowed: only "public" attributes (not starting with '_') of objects may
    # be accessed.
    # This is done on purpose: it prevents incidental or malicious execution of
    # Python code that may break the security of the server.
    from jinja2.sandbox import SandboxedEnvironment
    mako_template_env = SandboxedEnvironment(
        block_start_string="<%",
        block_end_string="%>",
        variable_start_string="${",
        variable_end_string="}",
        comment_start_string="<%doc>",
        comment_end_string="</%doc>",
        line_statement_prefix="%",
        line_comment_prefix="##",
        trim_blocks=True,               # do not output newline after blocks
        autoescape=True,                # XML/HTML automatic escaping
    )
    mako_template_env.globals.update({
        'str': str,
        'quote': quote,
        'urlencode': urlencode,
        'datetime': datetime,
        'len': len,
        'abs': abs,
        'min': min,
        'max': max,
        'sum': sum,
        'filter': filter,
        'reduce': reduce,
        'map': map,
        'round': round,

        # dateutil.relativedelta is an old-style class and cannot be directly
        # instanciated wihtin a jinja2 expression, so a lambda "proxy" is
        # is needed, apparently.
        'relativedelta': lambda *a, **kw : relativedelta.relativedelta(*a, **kw),
    })
except ImportError:
    _logger.warning("jinja2 not available, templating features will not work!")

# Formulas
class contracts_pro_formula(osv.osv):
    _name = "contracts_pro.formula"
    _inherit = "contracts_pro.formula"

    _columns={
        'update_formula_date': fields.date(u'Fecha de actualización de fórmula',
                                           help=u"Fecha usada en el cálculo del botón 'Actualizar valor'. En caso de no estar definida será usada la fecha actual para los mismos.")
    }

    def button_update_value(self, cr, uid, formula_id, context=None):
        formula = self.browse(cr, uid, formula_id)
        self.update_value(cr, uid, formula_id, formula.update_formula_date, context=context)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


import pandas as pd
df = pd.read_csv('../Datasets/crimeRates.csv')

import plotly.express as px

fig1 = px.choropleth(df, locations='State',
                            locationmode="USA-states",
                            color ="homicideRate2017",
                           color_continuous_scale="Viridis_r",
                           range_color=(0, 14),
                           scope="usa",
                           labels={'homicideRate2017':'Homicide Rate'},
                            title ='Homicide Rates by State in 2017',
                            height = 750
                          )

fig2 = px.choropleth(df, locations='State',
                     locationmode="USA-states",
                     color="firearmDeathRate",
                     color_continuous_scale="Viridis_r",
                     range_color=(0, 20),
                     scope="usa",
                     labels={'firearmDeathRate': 'Firearm Death Rate'},
                     title ='Firearm Death Rates by State in 2017',
                     height = 750

                     )

fig3 = px.choropleth(df, locations='State',
                     locationmode="USA-states",
                     color="firearmDeaths",
                     color_continuous_scale="Viridis_r",
                     range_color=(0, 4000),
                     scope="usa",
                     labels={'firearm Deaths': 'FirearmDeaths'},
                    title ='Firearm Deaths by State in 2017',
                     height = 750
                     )

with open('graph.html', 'a') as f:
    f.write(fig1.to_html(full_html=False, include_plotlyjs='cdn'))
    f.write(fig2.to_html(full_html=False, include_plotlyjs='cdn'))
    f.write(fig3.to_html(full_html=False, include_plotlyjs='cdn'))


import numpy as np

best_hr, best_mrr, best_ndcg = 0.0, 0.0, 0.0

def hit(gt_item, pred_items):
    if gt_item in pred_items:
        return 1
    return 0

def mrr(gt_item, pred_items):
    if gt_item in pred_items:
        index = pred_items.index(gt_item)
        return np.reciprocal(float(index + 1))
    else:
        return 0

def ndcg(gt_item, pred_items):
    if gt_item in pred_items:
        index = pred_items.index(gt_item)
        return np.reciprocal(np.log2(index + 2))
    return 0

def display(epoch, epoch_num, loss, hr, mrr, ndcg):
    print(
        "Running Epoch {:03d}/{:03d}".format(epoch + 1, epoch_num),
        "loss:{:.3f}".format(float(loss)),
        "Hr {:.3f}, Mrr {:.3f}, Ndcg {:.3f}".format(hr, mrr, ndcg),
        flush=True)
    global best_hr, best_mrr, best_ndcg
    if hr >= best_hr:
        best_hr     = hr
        best_mrr    = mrr
        best_ndcg   = ndcg
    if epoch + 1 == epoch_num:
        print('-----------Best Result:-----------')
        print('Hr: {:.3f}, Mrr: {:.3f}, Ndcg: {:.3f}'.format(best_hr, best_mrr, best_ndcg))
        print('----------------------------------')


#Example 1.7.20
#Python 3.6.5
#Created By Jooompot Sriyapan

def example_720(x,y):
    if x>y:
        return x
    elif x<y:
        return y
    else:
        return "x=y"

print (example_720(10,20))
print (example_720(9,1))
print (example_720(100,100))

'''
return ตามเงื่อนไขที่แตกต่างกันได้

อาจเปลี่ยน code เป็น
def example_720(x,y):
    if x>y:
        r=x
    elif x<y:
        r=y
    else:
        r= "x=y"
    return r

ก็ได้ผลเหมือนกัน

แสดงผล
20
9
x=y
'''