from cs1lib import *

# starting and end points of stick
x1a = 50
y1a = 200
x2a = 150
y2a = 350
x1b = 360
y1b = 20
x2b = 320
y2b = 250
num_strings = 36

# main drawing function
def draw_string_art():
    set_clear_color(0,0,0)
    clear()
    draw_sticks()
    draw_strings()

# draws strings
def draw_strings():

    set_stroke_width(1)
    f = 0

    # change in f from one string to the next
    change = (1 / (num_strings -1))

    while f <= (1 + change):

        # changes color from string to string
        set_stroke_color(0, f, .9)

        # sets tacks based on f value
        xa = x1a + f * (x2a - x1a)
        ya = y1a + f * (y2a-y1a)
        xb = x1b + (1.0 - f) * (x2b - x1b)
        yb = y1b + (1.0 - f) * (y2b - y1b)

        # draws new string
        draw_line(xa,ya,xb,yb)

        # increments f to draw the next string
        f = f + change

# draws two red sticks
def draw_sticks():
    set_stroke_width(3)
    set_stroke_color(1, 0, 0)
    draw_line(x1a, y1a, x2a, y2a)
    draw_line(x1b, y1b, x2b, y2b)

# main function that calls drawing function
def main():
    draw_string_art()

start_graphics(main)


from os import times
import math

def readData(fileName):
    departTime = 0
    timestamps = list()
    print("Reading data from: " + fileName)
    with open(fileName, 'r') as dataFile:
        departTime = int(dataFile.readline().rstrip())
        timestamps = dataFile.readline().rstrip().split(',')
    minDiff = -1
    diffId = -1
    minDivVal = -1
    tsCleaned = list()
    for ts in timestamps.copy():
        if ts != 'x':
            tsCleaned.append(int(ts))
    for ts in tsCleaned:
        if ts == 'x':
            continue
        divVal = departTime/int(ts)
        diff = math.ceil(divVal)-divVal

        if minDiff < 0 or diff < minDiff:
            minDiff = diff
            diffId = ts
            minDivVal = divVal

    waitTime = math.ceil(minDivVal)*diffId-departTime
    print(
        f"Part1:answer={diffId*waitTime} bus id: {diffId}, waitTime: {waitTime}, {minDiff}")

def readData2(data):
    timestamps = list()
    timestamps = data.split(',')
    tsCleaned = list()
    tsData = dict({})
    pos = 0
    idx = 0
    for ts in timestamps.copy():
        if ts != 'x':
            ts = int(ts)
            tsCleaned.append(ts)
            tsData[ts] = {'offset': pos, 'idx': idx}
            idx = idx + 1
        pos = pos + 1

    # find higest ts
    tsHigest = max(tsCleaned)
    offsetHighest = tsData[tsHigest]['offset']

    found = False
    testTs = int(100000000000000/tsHigest)*int(tsHigest)+tsHigest
    while not found:
        fail = False
        if testTs == 1068785:
            print('break')

        for ts in tsCleaned:
            offsetAtPos = tsData[ts]['offset']-offsetHighest
            tsAtPos = testTs+offsetAtPos
            test = tsAtPos/ts
            if math.ceil(test)-test > 0:
                fail = True
                break
        if not fail:
            break
        testTs = testTs+tsHigest
    print(f"Answer={testTs-offsetHighest} for {data}", flush=True)

def main():

    readData2("7,13,x,x,59,x,31,19")
    readData2("17,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,937,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,13,x,x,x,x,23,x,x,x,x,x,29,x,397,x,x,x,x,x,37,x,x,x,x,x,x,x,x,x,x,x,x,19")
    readData2("17,x,13,19")
    readData2("67,7,59,61")
    readData2("67,x,7,59,61")
    readData2("67,7,x,59,61")
    readData2("1789,37,47,1889")
    # readData("input.txt")

if __name__ == "__main__":
    main()


import numpy as np
import json

# board = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
#          [6, 0, 0, 1, 9, 5, 0, 0, 0],
#          [0, 9, 8, 0, 0, 0, 0, 6, 0],
#          [8, 0, 0, 0, 6, 0, 0, 0, 3],
#          [4, 0, 0, 8, 0, 3, 0, 0, 1],
#          [7, 0, 0, 0, 2, 0, 0, 0, 6],
#          [0, 6, 0, 0, 0, 0, 2, 8, 0],
#          [0, 0, 0, 4, 1, 9, 0, 0, 5],
#          [0, 0, 0, 0, 8, 0, 0, 7, 9]]

game = {
    # the board is represented as a list of lists containing the number at that location in the grid
    # 0 means the location is not filled
    "board": [[0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 4, 0, 0, 0, 0],
              [0, 0, 3, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0]],

    # each thermometer is represented as a list of tuples where the first tuple is the bulb
    # this is a list of thermometers
    "thermometers": [[(2, 0), (1, 0), (0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3)],
                     [(4, 2), (3, 2)],
                     [(4, 2), (5, 2)],
                     [(4, 2), (4, 3), (4, 4), (4, 5)],
                     [(7, 5), (6, 5), (6, 6), (6, 7), (6, 8), (7, 8), (8, 8)],
                     [(7, 5), (8, 5)]],

    # sum_areas is a list of distionanies
    "sum_areas": [{
        "sum": 10,
        "locations": [(0, 0), (0, 1)],
    },
    {
        "sum": 10,
        "locations": [(1, 0), (1, 1)],
    },
    {
        "sum": 10,
        "locations": [(0, 3), (1, 3)],
    },
    {
        "sum": 10,
        "locations": [(5, 3), (5, 4)],
    },
    {
        "sum": 10,
        "locations": [(7, 3), (7, 4)],
    },
    {
        "sum": 10,
        "locations": [(8, 3), (8, 4)],
    },
    {
        "sum": 10,
        "locations": [(0, 4), (1, 4)],
    },
    {
        "sum": 10,
        "locations": [(4, 5), (5, 5)],
    },
    {
        "sum": 10,
        "locations": [(8, 6), (8, 7)],
    },
    {
        "sum": 10,
        "locations": [(2, 7), (2, 8)],
    },
    {
        "sum": 10,
        "locations": [(3, 7), (4, 7)],
    }],

    "constraints": {
        "sudoku_row": True,
        "sudoku_column": True,
        "sudoku_box": True,
        "chess_knight": True,
        "thermometers": True
    }
}

i = 0

# returns true if n can be placed in row r
# false if n is already in row r
def constraint_row(game, x, y, n):
    board = game.get('board')

    for c in range(9):
        if board[y][c] == n:
            return False
    return True

# returns true if n can be placed in column c
# false if n is already in column c
def constraint_column(game, x, y, n):
    board = game.get('board')

    for r in range(9):
        if board[r][x] == n:
            return False
    return True

# returns true if n can be placed in box b
# false if n is already in box b
def constraint_box(game, x, y, n):
    board = game.get('board')

    bx = (x // 3) * 3
    by = (y // 3) * 3
    for r in range(3):
        for c in range(3):
            if board[by + r][bx + c] == n:
                return False
    return True

# returns true if n can be placed at x,y in the board breaking the chess knights rule
# false if n is a knights move away
def constraint_chess_knight(game, x, y, n):
    board = game.get('board')

    for r in range(9):
        for c in range(9):
            distance = abs(r - y) + abs(c - x)
            if not distance == 3:
                continue
            if r == y:
                continue
            if c == x:
                continue
            if board[r][c] == n:
                return False
    return True

# returns true if n can be placed at x,y in the board without breaking the chess king rule
# false if n is a kings move away
def constraint_chess_king(game, x, y, n):
    board = game.get('board')

    for r in range(3):
        for c in range(3):

            #   x x x
            #   x K x   we can skip 1, 1 because this represents the current
            #   x x x   location as illustrated here
            if r == 1 and c == 1:
                continue

            lx = x+c-1 # location x and y are the current location we are evaluating in the board
            ly = y+r-1
            if lx < 0 or lx > 8 or ly < 0 or ly > 8:
                continue

            # check surrounding square
            if board[ly][lx] == n:
                return False

    # if we didnt find a reason to fail, it succeeds
    return True

# returns true if n can be placed at x,y in the board without breaking the thermometer rule
# false if placing n at x,y breaks a thermometer
# thermometer sudoku is where there is a line on the sudoku board, and the numbers on the line
# can only grow as they get further from the start (aka the bulb) of the thermometer
def constraint_thermometer(game, x, y, n):
    board = game.get('board')
    thermometers = game.get('thermometers')

    if not isinstance(thermometers, list):
        return True

    # search over all the thermometers
    for t in thermometers:

        # check if x, y exists on this thermometer
        found = False
        for pos in t:
            if pos[0] == x and pos[1] == y:
                found = True
                break

        # this x,y was not found on this thermometer,
        # so check the next thermomemter
        if not found:
            continue

        before = True # this keeps track if out current pos is before the given x,y along the thermometer
        for pos in t:
            if pos[0] == x and pos[1] == y:
                before = False
                continue

            # if this position on the board is empty, skip this one
            if board[pos[1]][pos[0]] == 0:
                continue

            if before:
                if n <= board[pos[1]][pos[0]]:
                    return False
            else:
                if n >= board[pos[1]][pos[0]]:
                    return False

    # we havent failed, so we good?
    return True

# returns true if the x,y cell is not consecutive to the orthogonally adjacent cells
# returns false if at least 1 neighbor cell is consecutive to n
def constraint_consecutive_orthogonally_adjacent(game, x, y, n):
    board = game.get('board')

    # check that we arent at the border of the board
    if x > 0:
        # check if the difference between the adjacent cell and x,y cell is 1
        if not board[y][x - 1] == 0:
            if abs(board[y][x - 1] - n) == 1:
                # if so return false
                return False
    if x < 8:
        if not board[y][x + 1] == 0:
            if abs(board[y][x + 1] - n) == 1:
                return False
    if y > 0:
        if not board[y - 1][x] == 0:
            if abs(board[y - 1][x] - n) == 1:
                return False
    if y < 8:
        if not board[y + 1][x] == 0:
            if abs(board[y + 1][x] - n) == 1:
                return False

    # none of the adjacent test failed, so we pass
    return True

def constraint_sum_areas(game, x, y, n):
    board = game.get('board')
    sum_areas = game.get('sum_areas')

    for sa in sum_areas:
        sa_sum = sa.get('sum')
        sa_locs = sa.get('locations')

        # check if x, y exists on this sum_area
        found = False
        for pos in sa_locs:
            if pos[0] == x and pos[1] == y:
                found = True
                break

        if not found:
            continue

        # iterate over all the positions in the sum_area
        sum = 0
        exact = True # if all the locations in the sum_area are filled in, then the sum needs to be exact
        for pos in sa_locs:
            if pos[0] == x and pos[1] == y:
                sum += n
                continue

            bval = board[pos[1]][pos[0]]

            # if one location is not filled in, then the sum doesnt have to be exact
            if bval == 0:
                exact = False

            sum += bval

        if exact:
            return sum == sa_sum
        else:
            if sum > sa_sum:
                return False

    return True

def possible(game, x, y, n):
    board = game.get('board')
    constraints = game.get('constraints', {'sudoku_row': True, 'sudoku_column': True, 'sudoku_box': True})

    if True == constraints.get('sudoku_row', False):
        if not constraint_row(game, x, y, n):
            return False

    if True == constraints.get('sudoku_column', False):
        if not constraint_column(game, x, y, n):
            return False

    if True == constraints.get('sudoku_box', False):
        if not constraint_box(game, x, y, n):
            return False

    if True == constraints.get('chess_knight', False):
        if not constraint_chess_knight(game, x, y, n):
            return False

    if True == constraints.get('chess_king', False):
        if not constraint_chess_king(game, x, y, n):
            return False

    if True == constraints.get('thermometers', False):
        if not constraint_thermometer(game, x, y, n):
            return False

    if True == constraints.get('consecutive_orthogonally_adjacent', False):
        if not constraint_consecutive_orthogonally_adjacent(game, x, y, n):
            return False

    if True == constraints.get('sum_areas', False):
        if not constraint_sum_areas(game, x, y, n):
            return False

    return True

def solve(game):
    board = game.get('board')
    #print(np.matrix(board))
    #input('Step?')

    global i
    if i % 100000 == 0:
        print(np.matrix(board))
    i += 1

    for y in range(9):
        for x in range(9):
            if board[y][x] == 0:
                for n in range(1, 10):
                    if possible(game, x, y, n):
                        board[y][x] = n
                        solve(game)
                        board[y][x] = 0
                return
    print(np.matrix(board))
    input('More?')

if __name__ == "__main__":
    game_name = input('Game name: ')

    with open(f'games/{game_name}.json', 'r') as game_file:
        game_data = json.loads(game_file.read())
        solve(game_data)


#!/usr/bin/env python
#
# Megan Rich, HRL, 8/25/14
# This node checks if the tf frame '/head_frame' obtained from
# head registration is currently within reach of the PR2. If the
# head frame is not within reach of the PR2, it will move the PR2 base
# to within range of the subject's head.

import roslib
roslib.load_manifest('tf')
roslib.load_manifest('actionlib')
roslib.load_manifest('move_base')
import actionlib
#from actionlib_msgs.msg import MoveBaseAction
from move_base_msgs.msg import MoveBaseAction, MoveBaseActionGoal
import rospy
import math
import tf
from geometry_msgs.msg import Twist, PointStamped, Pose, Quaternion, PoseStamped
from std_msgs.msg import String
import os

class check_head():

    def __init__(self):
        rospy.init_node('check_head')
        self.listener = tf.TransformListener()
        self.pub=rospy.Publisher('head_check', String)
        self.head=rospy.Publisher('head_check_confirm', String)
        self.move=rospy.Publisher('base_controller/command', Twist)
        rospy.Subscriber('head_check', String, self.head_check)
        rospy.sleep(1)
        self.cmd=Twist()
        self.l=0
        self.r=0
        self.t=0
        self.trans14=(0.13928415716177617, 0.6565833449408256, -1.357303916796)
        self.rot14=(0.2789777273842869, -0.05907426262263365, 0.8767308579569227, -0.3873301715916394)
        self.transh=(0.13895118715509372, 0.6563869581415823, -1.3570648116919164)
        self.roth=(0.2675468812908289, -0.052590910844725884, 0.8789907250153403, -0.39118814877892155)
        #precalculated values of the maximum length of both arms (form /(l or r)_shoulder_pan_link
        #to the the appropriate tool frame
        #assumes spoon tool is in left gripper
        self.l_arm_length=1.36
        self.r_arm_length=0.94
        #check if left and right arms are within reach of the registered head
        self.calc_left()
        self.calc_right()

    #check if head check is complete
    def head_check(self, data):
        self.mess=data.data
        if self.mess == 'Ready':
            self.t=self.t+1
            if self.t==2:
                self.head.publish('Ready')
                print('Head check complete')
                os._exit(0)

    def calc_left (self):

        try:
            #look up transforms of /l_shoulder_pan_link and /head_frame
            #with respect to same coordinate frame (/odom_combined)
            (trans1, rot1)=self.listener.lookupTransform('/l_shoulder_pan_link', '/odom_combined', rospy.Time(0))
            #(trans14, rot14)=self.listener.lookupTransform('/head_frame', '/odom_combined', rospy.Time(0))
            #calculate the distance between them (distance to head)
            self.l_dist2head=math.sqrt((self.trans14[0]-trans1[0])**2+(self.trans14[1]-trans1[1])**2+(self.trans14[2]-trans1[2])**2)
            print('Left distance: %s'%self.l_dist2head)

        except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException): #check for tf exceptions
            print ('Error! Most likely cause: tf lookup Exception')
            self.l_dist2head=1.

        #check if the head is within reach
        if self.l_dist2head >(self.l_arm_length):
            print('Head not reachable!')
            print('Left arm too short')
            #send message to master control, so it will not start yet
            self.pub.publish('Too far')
            #move base to be within reach of left arm
            self.base_mover('l')
        elif self.l_dist2head==1.:
            #if there was a tf exception try again 3 times before quitting
            print('calculation failed')
            self.l=self.l+1
            if self.l<=3:
                print('trying again')
                self.calc_left()
            else:
                print('exiting')
                os._exit(0)
        else:
            #if head within reach of left arm, publish a message to the master control node
            #this message allows it to begin
            print('Head within reach')
            self.pub.publish('Ready')
    def calc_right(self):
        try:
            #look up transforms of /r_shoulder_pan_link and /head_frame
            #with respect to same coordinate frame (/odom_combined)
            (trans1, rot1)=self.listener.lookupTransform('/r_shoulder_pan_link', '/odom_combined', rospy.Time(0))
            #(trans14, rot14)=self.listener.lookupTransform('/head_frame', '/odom_combined', rospy.Time(0))
            #calculate the distance between them (distance to head)
            self.r_dist2head=math.sqrt((self.trans14[0]-trans1[0])**2+(self.trans14[1]-trans1[1])**2+(self.trans14[2]-trans1[2])**2)
            print('Right distance: %s'%self.r_dist2head)
        except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException): #check for tf exceptions
            print ('Error! Most Likely a tf lookup exception')
            self.r_dist2head=1.

        #check if head is within reach of the right arm
        if self.r_dist2head >(self.r_arm_length):
            print('Head not reachable')
            print('Right arm too short')
             #send message to master control, so it will not start yet
            self.pub.publish('Too far')
            #move base to be within reach of right arm
            self.base_mover('r')
        elif self.r_dist2head==1.:
            #if there was a tf exception try again 3 times before quitting
            print('calculation failed')
            self.r=self.r+1
            if self.r<=3:
                print('trying again')
                self.calc_right()
            else:
                print('exiting')
                os._exit(0)
        else:
            print ('Head within reach')
            self.pub.publish('Ready')

    def base_mover(self, side):
        if side == 'l':
            #make sure it won't run over someone's foot
            #move base so left arm is within range of head
            print('moving better location for the left arm')
            while  not rospy.is_shutdown() and self.l_dist2head>self.l_arm_length:
                (trans1, rot1)=self.listener.lookupTransform('/l_shoulder_pan_link', '/odom_combined', rospy.Time(0))
                (trans2, rot2)=self.listener.lookupTransform('/base_footprint', '/odom_combined', rospy.Time(0))
                #(trans14, rot14)=self.listener.lookupTransform('/head_frame', '/odom_combined', rospy.Time(0))

                self.l_dist2head=math.sqrt((trans1[0]-self.trans14[0])**2+(trans1[1]-self.trans14[1])**2+(trans1[2]-self.trans14[2])**2)
                self.cmd.linear.x=trans2[0]-self.trans14[0]
                self.cmd.linear.y=trans2[1]-self.trans14[1]
                self.cmd.linear.z=0.
                self.cmd.angular.x=0.
                self.cmd.angular.y=0.
                self.cmd.angular.z=0.
                self.move.publish(self.cmd)
                rospy.sleep(1)
            #when done moving
            print('done moving')
            print('performing final head check')
            #check to make sure it worked and moving the base didn't mess up the other arm
            self.t=0
            self.calc_left()
            self.calc_right()
        if side == 'r':
            #make sure it won't run over someone's foot
            #move base so right arm is within range of head
            print('moving to better location for right arm')
            while not rospy.is_shutdown() and self.r_dist2head>self.r_arm_length:
                (trans1, rot1)=self.listener.lookupTransform('/r_shoulder_pan_link', '/odom_combined', rospy.Time(0))
                (trans2, rot2)=self.listener.lookupTransform('/base_footprint', '/odom_combined', rospy.Time(0))
                #(trans14, rot14)=self.listener.lookupTransform('/head_frame', '/odom_combined', rospy.Time(0))
                self.r_dist2head=math.sqrt((trans1[0]-self.trans14[0])**2+(trans1[1]-self.trans14[1])**2+(trans1[2]-self.trans14[2])**2)
                self.cmd.linear.x=trans2[0]-self.trans14[0]
                self.cmd.linear.y=trans2[1]-self.trans14[1]
                self.cmd.linear.z=0.
                self.cmd.angular.x=0.
                self.cmd.angular.y=0.
                self.cmd.angular.z=0.
                self.move.publish(self.cmd)
                rospy.sleep(1)
            #when done moving
            print('done moving')
            print('performing final head check')
            #check to make sure it worked and that moving the base didn't mess up the other arm
            self.t=0
            self.calc_left()
            self.calc_right()

if __name__=='__main__':
    a = check_head()
    while not rospy.is_shutdown():
        rospy.spin()


from flask import Blueprint, render_template, request, jsonify, redirect, url_for, flash, abort
from studyup.models import Question, Choice, Answer, Comment, User
from studyup import db
from studyup.discussion.forms import CommentForm
from flask_login import login_required, current_user
from datetime import datetime

discussion = Blueprint('discussion', __name__)
comment = Blueprint('comment', __name__)

#returns topic name of given topicNo
@discussion.route("/api/topic/<int:topic_no>")
def topic(topic_no):
    TOPICS = [
        (1, 1, 1, 'Standards and units, Unit consistency, Uncertainty and significant figures'),
        (1, 1, 2, 'Vectors and vector addition, Components of vectors, Unit vectors'),
        (1, 2, 3, 'Displacement, time, and average velocity, Instantaneous velocity'),
        (1, 2, 4, 'Average and instantaneous acceleration'),
        (1, 2, 5, 'Motion with constant acceleration, Freely falling bodies'),
        (1, 3, 6, 'Position and velocity vectors, Acceleration vector'),
        (1, 3, 7, 'Projectile motion'),
        (1, 3, 8, 'Motion in a circle'),
        (1, 3, 9, 'Relative velocity'),
        (1, 4, 10, 'Force and interactions, Mass and weight, Newton\'s first law, Inertial frames of reference'),
        (1, 4, 11, 'Free-body diagrams, Newton\'s second law, Newton\'s third law'),
        (1, 5, 12, 'Newton\'s 1st law: particles in equilibrium'),
        (1, 5, 13, 'Newton\'s 2nd law: dynamics of particles'),
        (1, 5, 14, 'Frictional forces'),
        (1, 5, 15, 'Dynamics of circular motion'),
        (2, 6, 16, 'Scalar product, Work'),
        (2, 6, 17, 'Work and kinetic energy'),
        (2, 6, 18, 'Work and energy with varying forces, Power'),
        (2, 7, 19, 'Gravitational potential energy, Conservation of mechanical energy (gravitational force), Conservative and nonconservative forces'),
        (2, 7, 20, 'Elastic potential energy, Conservation of mechanical energy'),
        (2, 7, 21, 'Force and potential energy, Energy diagrams'),
        (2, 8, 22, 'Momentum and Impulse'),
        (2, 8, 23, 'Conservation of momentum, Momentum conservation and collisions'),
        (2, 8, 24, 'Elastic collisions'),
        (2, 8, 25, 'Center of mass'),
        (2, 9, 26, 'Angular velocity and acceleration, Rotation with constant angular acceleration'),
        (2, 9, 27, 'Relating linear and angular kinematics'),
        (2, 9, 28, 'Energy in rotational motion, Parallel-axis theorem'),
        (2, 10, 29, 'Vector product, Torque'),
        (2, 10, 30, 'Torque and Angular acceleration for a rigid body'),
        (2, 10, 31, 'Rigid-body rotation about a moving axis'),
        (2, 10, 32, 'Angular momentum, Conservation of angular momentum'),
        (3, 11, 33, 'Conditions for equilibrium, Center of gravity'),
        (3, 11, 34, 'Solving rigid-body equilibrium problems'),
        (3, 11, 35, 'Stress, strain, elastic moduli, Elasticity and plasticity'),
        (3, 12, 36, 'Density, Pressure in a fluid'),
        (3, 12, 37, 'Buoyancy'),
        (3, 12, 38, 'Fluid flow, Bernoulli\'s equation'),
        (3, 13, 39, 'Newton\'s law of gravitation, Weight'),
        (3, 13, 40, 'Gravitational potential energy, Motion of satellites'),
        (3, 13, 41, 'Kepler\'s laws and the motion of the planets'),
        (3, 14, 42, 'Describing oscillation, Simple harmonic motion'),
        (3, 14, 43, 'Energy in simple harmonic motion'),
        (3, 14, 44, 'Applications of simple harmonic motion, The simple pendulum, The physical pendulum'),
        (3, 14, 45, 'Damped Oscillations, Forced Oscillations'),
        (3, 15, 46, 'Types of mechanical waves, Periodic waves, Mathematical description of wave, Speed of a transverse wave'),
        (3, 15, 47, 'Energy in wave motion, Wave interference, boundary conditions, and superposition'),
        (3, 15, 48, 'Standing waves on a string, Normal modes of a string'),
        (3, 16, 49, 'Doppler Effect')
            ]

    return jsonify({'name': TOPICS[topic_no - 1][3]})

@discussion.route("/api/topic/<int:topic_num>/questions")
def questionPerTopic(topic_num):
    q = Question.query.filter_by(topic_no=int(topic_num)).all()

    qList = []
    for question in q:
        questionObj = {}
        questionObj['id'] = question.id
        questionObj['body'] = question.body
        qList.append(questionObj)
    return jsonify({'questions': qList})

@discussion.route('/discussion')
def select():
    return render_template('discussion.html')

@discussion.route('/discussion/<int:question_id>', methods=['GET','POST'])
@login_required
def add_comment(question_id):
    form = CommentForm()
    question = Question.query.filter_by(id=question_id).first()
    if form.validate_on_submit():
        comment = Comment()
        comment.time_posted = datetime.utcnow()
        comment.comment = form.body.data
        user = User.query.filter_by(username=current_user.username).first()
        comment.user_id = user.id
        comment.question_id = question_id
        db.session.add(comment)
        db.session.commit()
        flash('Comment added!', 'success')
        comments = Comment.query.filter_by(question_id=question_id).all()
        return redirect(url_for('discussion.add_comment', question_id=question_id, comments=comments, tempRemove=0))

    comments = Comment.query.filter_by(question_id=question_id).all()
    return render_template('view-question.html', form=form, question=question, comments=comments, tempRemove=0)

@discussion.route('/discussion/<int:question_id>/edit/<int:comment_id>', methods=['GET','POST'])
@login_required
def edit_comment(question_id, comment_id):
    question = Question.query.filter_by(id=question_id).first()
    comments = Comment.query.filter_by(question_id=question_id).all()
    comment = Comment.query.filter_by(id=comment_id).first()
    form = CommentForm()
    if comment.user != current_user:
        abort(403)
    if form.validate_on_submit():
        comment.comment = form.body.data
        comment.edited = True
        db.session.commit()
        flash('Comment edited', 'success')
        return redirect(url_for('discussion.add_comment', question_id=question_id, comments=comments, tempRemove=0))
    return render_template('view-question.html', question=question, form=form, comments=comments, tempRemove=comment_id, editComment=comment)

@discussion.route('/discussion/<int:question_id>/delete/<int:comment_id>', methods=['POST'])
@login_required
def delete_comment(question_id,comment_id):
    # question = Question.query.filter_by(id=question_id).first()
    comments = Comment.query.filter_by(question_id=question_id).all()
    comment = Comment.query.filter_by(id=comment_id).first()
    if current_user.user_type != 2: # not a moderator
        abort(403)
    db.session.delete(comment)
    db.session.commit()
    flash('Comment has been deleted!', 'success')
    return redirect(url_for('discussion.add_comment',question_id=question_id, comments=comments))


#!/usr/bin/env python

# encoding: utf-8
'''

@author: natty

@file: commands.py

@time: 2017/12/13 17:45

@desc:  行处理函数
'''
from Scanner import scanner,scanner_map

def processline(line):
    if line[0] == '*':
        pro_line = 'Mr.' + line[1:]
    elif line[0] == '+':
        pro_line = 'Ms.' + line[1:]
    else:
        pro_line = line
    print(pro_line)

if __name__ == "__main__":
    scanner("resources\\hillbillies",processline)
    scanner_map("resources\\hillbillies", processline)


from dataclasses import dataclass
import os

@dataclass
class LfaInfo:
    endpoint_url: str
    bucket: str
    profile: str

def get_lfa() -> LfaInfo:
    """Get the LFA information from the LSST_DDS_PARTITION_PREFIX envvar

    Returns
    -------
    `LfaInfo`
        The information for the site LFA

    Raises
    ------
    RuntimeError
        If the value of LSST_DDS_PARTITION_PREFIX is not recognized
    """
    try:
        label = os.environ["LSST_DDS_PARTITION_PREFIX"]
        lfa = None
        if label == "tucson":
            lfa = LfaInfo("https://s3.tu.lsst.org", "rubinobs-lfa-tuc", "tts")
        if label == "base":
            lfa = LfaInfo("https://s3.ls.lsst.org", "rubinobs-lfa-ls", "bts")
        if label == "summit":
            lfa = LfaInfo("https://s3.cp.lsst.org", "rubinobs-lfa-cp", "summit")
        if lfa is not None:
            return lfa
        raise RuntimeError(f"Cannot provide EFD name for {label}.")
    except KeyError:
        raise RuntimeError("LSST_DDS_PARTITION_PREFIX not defined")


# -*- coding: utf-8 -*-

from collections import namedtuple
from functools import partial
from uuid import uuid4

import falcon
from django.apps import apps
from elasticsearch_dsl import Q

from mcod.applications.depricated.schemas import ApplicationsList, ApplicationSuggestion
from mcod.applications.depricated.serializers import ApplicationsSerializer, ApplicationsMeta
from mcod.applications.deserializers import ApplicationApiRequest, ApplicationApiSearchRequest, CreateSubmissionRequest
from mcod.applications.documents import ApplicationsDoc
from mcod.applications.serializers import ApplicationApiResponse, SubmissionApiResponse
from mcod.applications.tasks import send_application_proposal
from mcod.core.api.handlers import CreateOneHdlr
from mcod.core.api.handlers import SearchHdlr, RetrieveOneHdlr
from mcod.core.api.hooks import login_optional
from mcod.core.api.views import BaseView
from mcod.core.versioning import versioned
from mcod.datasets.depricated.schemas import DatasetsList
from mcod.datasets.depricated.serializers import DatasetSerializer, DatasetsMeta
from mcod.datasets.deserializers import DatasetApiSearchRequest
from mcod.datasets.documents import DatasetsDoc
from mcod.datasets.serializers import DatasetApiResponse
from mcod.following.handlers import FollowingSearchHandler
from mcod.following.handlers import RetrieveOneFollowHandler
from mcod.lib.handlers import (
    CreateHandler)
from mcod.lib.handlers import SearchHandler

class ApplicationSearchApiView(BaseView):
    @falcon.before(login_optional)
    @versioned
    def on_get(self, request, response, *args, **kwargs):
        self.handle(request, response, self.GET, *args, **kwargs)

    @falcon.before(login_optional)
    @on_get.version('1.0')
    def on_get(self, request, response, *args, **kwargs):
        self.handle(request, response, self.GET_1_0, *args, **kwargs)

    class GET(SearchHdlr):
        deserializer_schema = partial(ApplicationApiSearchRequest, many=False)
        serializer_schema = partial(ApplicationApiResponse, many=True)
        search_document = ApplicationsDoc()

        def _queryset_extra(self, queryset, **kwargs):
            return queryset.filter('term', status='published')

    class GET_1_0(FollowingSearchHandler):
        meta_serializer = ApplicationsMeta()
        deserializer_schema = ApplicationsList()
        serializer_schema = ApplicationsSerializer(many=True)
        search_document = ApplicationsDoc()

class ApplicationApiView(BaseView):
    @falcon.before(login_optional)
    @versioned
    def on_get(self, request, response, *args, **kwargs):
        self.handle(request, response, self.GET, *args, **kwargs)

    @falcon.before(login_optional)
    @on_get.version('1.0')
    def on_get(self, request, response, *args, **kwargs):
        self.handle(request, response, self.GET_1_0, *args, **kwargs)

    class GET_1_0(RetrieveOneFollowHandler):
        database_model = apps.get_model('applications', 'Application')
        serializer_schema = ApplicationsSerializer(many=False)

    class GET(RetrieveOneHdlr):
        deserializer_schema = partial(ApplicationApiRequest, many=False)
        database_model = apps.get_model('applications', 'Application')
        serializer_schema = partial(ApplicationApiResponse, many=False)

        def _get_instance(self, id, *args, **kwargs):
            instance = getattr(self, '_cached_instance', None)
            if not instance:
                model = self.database_model
                try:
                    self._cached_instance = model.objects.get(pk=id, status='published')
                except model.DoesNotExist:
                    raise falcon.HTTPNotFound
            return self._cached_instance

class ApplicationDatasetsView(BaseView):
    @falcon.before(login_optional)
    @versioned
    def on_get(self, request, response, *args, **kwargs):
        self.handle(request, response, self.GET, *args, **kwargs)

    @falcon.before(login_optional)
    @on_get.version('1.0')
    def on_get(self, request, response, *args, **kwargs):
        self.handle(request, response, self.GET_1_0, *args, **kwargs)

    class GET_1_0(SearchHandler):
        meta_serializer = DatasetsMeta()
        deserializer_schema = DatasetsList()
        serializer_schema = DatasetSerializer(many=True, include_data=('institution',))
        search_document = DatasetsDoc()

        def _queryset(self, cleaned, *args, **kwargs):
            qs = super()._queryset(cleaned, *args, **kwargs)
            if 'id' in kwargs:
                qs = qs.query("nested", path="applications",
                              query=Q("term", **{'applications.id': kwargs['id']}))
            return qs

    class GET(SearchHdlr):
        deserializer_schema = partial(DatasetApiSearchRequest, many=False)
        serializer_schema = partial(DatasetApiResponse, many=True)
        search_document = DatasetsDoc()

        def _queryset_extra(self, queryset, id=None, **kwargs):
            if id:
                queryset = queryset.query("nested", path="applications",
                                          query=Q("term", **{'applications.id': id}))
            return queryset.filter('term', status='published')

class ApplicationSubmitView(BaseView):
    @versioned
    def on_post(self, request, response, *args, **kwargs):
        self.handle_post(request, response, self.POST, *args, **kwargs)

    @on_post.version('1.0')
    def on_post(self, request, response, *args, **kwargs):
        self.handle(request, response, self.POST_1_0, *args, **kwargs)

    class POST_1_0(CreateHandler):
        databse_model = apps.get_model('applications', 'Application')
        deserializer_schema = ApplicationSuggestion()

        def _data(self, request, cleaned, *args, **kwargs):
            send_application_proposal.delay(cleaned)
            return cleaned

        def _serialize(self, data, meta, links=None, *args, **kwargs):
            return {}

    class POST(CreateOneHdlr):
        databse_model = apps.get_model('applications', 'Application')
        deserializer_schema = partial(CreateSubmissionRequest)
        serializer_schema = partial(SubmissionApiResponse, many=False)

        def clean(self, *args, **kwargs):
            cleaned = super().clean(*args, **kwargs)
            return cleaned

        def _get_data(self, cleaned, *args, **kwargs):
            _data = cleaned['data']['attributes']
            send_application_proposal.s(dict(_data)).apply_async(countdown=1)
            fields, values = [], []
            for field, val in _data.items():
                fields.append(field)
                values.append(val)
            fields.append('id')
            values.append(str(uuid4()))
            result = namedtuple('Submission', fields)(*values)
            return result


from slips_files.common.imports import *
import ipaddress

class HorizontalPortscan():
    def __init__(self, db):
        self.db = db
        self.cache_det_thresholds = {}
        self.fieldseparator = self.db.get_field_separator()
        self.port_scan_minimum_dips = 5
        self.pending_horizontal_ps_evidence = {}
        self.alerted_once_horizontal_ps = {}

    def calculate_confidence(self, pkts_sent):
        if pkts_sent > 10:
            confidence = 1
        elif pkts_sent == 0:
            return 0.3
        else:
            confidence = pkts_sent / 10.0
        return confidence

    def combine_evidence(self):
        """
        Combines all the evidence in pending_horizontal_ps_evidence into 1 evidence and calls set_evidence
        this function is called every 3 pending ev
        """
        for key, evidence_list in self.pending_horizontal_ps_evidence.items():
            profileid, twid, state, protocol, dport = key.split('-')
            final_evidence_uids = []
            final_pkts_sent = 0
            for evidence in evidence_list:
                timestamp, pkts_sent, evidence_uids, amount_of_dips = evidence
                final_evidence_uids += evidence_uids
                final_pkts_sent += pkts_sent
            self.set_evidence_horizontal_portscan(
                timestamp,
                final_pkts_sent,
                protocol,
                profileid,
                twid,
                final_evidence_uids,
                dport,
                amount_of_dips
            )

        self.pending_horizontal_ps_evidence = {}

    def get_resolved_ips(self, dstips: dict) -> list:
        """
        returns the list of dstips that have dns resolution, we will discard them when checking for
        horizontal portscans
        """
        dstips_to_discard = []

        for dip in dstips:
            dns_resolution = self.db.get_dns_resolution(dip)
            dns_resolution = dns_resolution.get('domains', [])
            if dns_resolution:
                dstips_to_discard.append(dip)
        return dstips_to_discard

    def check(self, profileid, twid):
        def get_uids():
            """
            returns all the uids of flows to this port
            """
            uids = []
            for dip in dstips:
                for uid in dstips[dip]['uid']:
                     uids.append(uid)
            return uids

        saddr = profileid.split(self.fieldseparator)[1]
        try:
            saddr_obj = ipaddress.ip_address(saddr)
            if saddr == '255.255.255.255' or saddr_obj.is_multicast:
                return False
        except ValueError:
            pass

        direction = 'Dst'
        role = 'Client'
        type_data = 'Ports'
        for state in ('Established', 'Not Established'):
            for protocol in ('TCP', 'UDP'):
                dports = self.db.getDataFromProfileTW(
                    profileid, twid, direction, state, protocol, role, type_data
                )

                for dport in dports.keys():
                    dstips: dict = dports[dport]['dstips']
                    for ip in self.get_resolved_ips(dstips):
                        dstips.pop(ip)
                    amount_of_dips = len(dstips)
                    cache_key = f'{profileid}:{twid}:dport:{dport}:HorizontalPortscan'
                    prev_amount_dips = self.cache_det_thresholds.get(cache_key, 0)

                    if (
                        amount_of_dips >= self.port_scan_minimum_dips
                        and prev_amount_dips + 5 <= amount_of_dips
                    ):

                        pkts_sent = 0
                        for dip in dstips:
                            if 'spkts' not in dstips[dip]:
                                pkts_sent += int(dstips[dip]["pkts"])
                            else:
                                pkts_sent += int(dstips[dip]["spkts"])

                        uids: list = get_uids()
                        timestamp = next(iter(dstips.values()))['stime']

                        self.cache_det_thresholds[cache_key] = amount_of_dips

                        if not self.alerted_once_horizontal_ps.get(cache_key, False):
                            self.alerted_once_horizontal_ps[cache_key] = True
                            self.set_evidence_horizontal_portscan(
                                timestamp,
                                pkts_sent,
                                protocol,
                                profileid,
                                twid,
                                uids,
                                dport,
                                amount_of_dips
                            )
                        else:
                            evidence_details = (timestamp, pkts_sent, uids, amount_of_dips)
                            key = f'{profileid}-{twid}-{state}-{protocol}-{dport}'
                            try:
                                self.pending_horizontal_ps_evidence[key].append(evidence_details)
                            except KeyError:
                                self.pending_horizontal_ps_evidence[key] = [evidence_details]
                            if len(self.pending_horizontal_ps_evidence[key]) == 3:
                                self.combine_evidence()

    def set_evidence_horizontal_portscan(
            self,
            timestamp,
            pkts_sent,
            protocol,
            profileid,
            twid,
            uid,
            dport,
            amount_of_dips
    ):
        evidence_type = 'HorizontalPortscan'
        attacker_direction = 'srcip'
        source_target_tag = 'Recon'
        srcip = profileid.split('_')[-1]
        attacker = srcip
        threat_level = 'medium'
        category = 'Recon.Scanning'
        portproto = f'{dport}/{protocol}'
        port_info = self.db.get_port_info(portproto)
        port_info = port_info or ""
        confidence = self.calculate_confidence(pkts_sent)
        description = (
            f'horizontal port scan to port {port_info} {portproto}. '
            f'From {srcip} to {amount_of_dips} unique dst IPs. '
            f'Total packets sent: {pkts_sent}. '
            f'Threat Level: {threat_level}. '
            f'Confidence: {confidence}. by Slips'
        )

        self.db.setEvidence(evidence_type, attacker_direction, attacker, threat_level, confidence, description,
                                 timestamp, category, source_target_tag=source_target_tag, conn_count=pkts_sent,
                                 port=dport, proto=protocol, profileid=profileid, twid=twid, uid=uid)


from PIL import Image
import numpy as np
from os.path import join
from os import listdir

tdir='.'

# Google maps traffic levels
whitecol   = 0xffffff
greencol   = 0x63d668
orangecol  = 0xff974d
redcol     = 0xf23c32
darkredcol = 0x811f1f

levels={}
cachefn=join(tdir,'trafficlevels')
try:
  with open(cachefn,'r') as fp:
    for x in fp:
      if x[:1]!='#':
        y=x.strip().split()
        levels[(y[0],y[1])]=[int(z) for z in y[2:]]
except FileNotFoundError:
  pass

for fn in sorted(listdir(tdir)):
  if fn[:6]=='London' and fn[-4:]=='.png':
    f=fn[:-4].find('.')
    key=(fn[:f],fn[f+1:-4])
    if key not in levels:
      im_frame = Image.open(join(tdir,fn))
      np_frame = np.array(im_frame)
      im_frame.close()
      rgb = np_frame[:,:,0]*65536+np_frame[:,:,1]*256+np_frame[:,:,2]
      numcols = [np.sum(rgb==v) for v in [whitecol,greencol,orangecol,redcol,darkredcol]]
      if numcols[0]<1000000:
        levels[key]=numcols
        print("Read",fn)
      else:
        print("Discarding",fn)

# Work out overall congestion as weighted sum of orange, red and dark red
ll=sorted(levels);n=len(ll)
l0=[]
for x in sorted(ll):
  m=levels[x]
  c=m[2]+3*m[3]+10*m[4]
  l0.append(c)

# Work out cumulative version of l0 with padded ends
l0pad=l0[:168]+l0+l0[-168:]
cum=[]
t=0
for c in l0pad:
  cum.append(t)
  t+=c
cum.append(t)

# Create 24-hour and 168-hour moving averages
l1=[];l2=[]
for (a,l) in [(24,l1),(168,l2)]:
  assert a%2==0;a2=a//2
  for i in range(168,n+168):
    l.append(int((cum[i+a2]-cum[i-a2+1]+(l0pad[i-a2]+l0pad[i+a2])/2+a2)/a))

with open(cachefn,'w') as fp:
  print("# Location      LocalDateTime    White    Green   Orange      Red  Darkred     Cong   Cong24  Cong168",file=fp)
  for i in range(n):
    (loc,date)=ll[i]
    print(loc,date,' '.join("%8d"%x for x in levels[(loc,date)][:5]),"%8d %8d %8d"%(l0[i],l1[i],l2[i]),file=fp)


from django.urls import path, re_path
from . import views
from django.contrib.auth import views as auth_views

app_name = 'manager'
urlpatterns=[
    path('', views.manager_index, name='index'),
    path('login/', auth_views.LoginView.as_view(template_name='manager/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    re_path(r'^calendar/$', views.AdminCalendarView.as_view(), name='calendarAdmin'),
    re_path(f'^calendar/adminsave/$', views.admin_save, name='adminsave'),
    re_path(r'^reservation/group/(?P<reservation_id>\d+)$', views.group_form, name='group_form'),
    re_path(r'^reservation/group/(?P<reservation_id>\d+)/confirm$', views.group_confirm, name='confirm'),
    path('regular/', views.admin_regular_list, name='admin_regular_list'),
    re_path(r'^regular/(?P<reservation_id>\d+)/$', views.admin_regular_form, name='admin_regular_form'),
    re_path(r'^regular/(?P<reservation_id>\d+)/status/$', views.regular_status_change, name='regular_status_change'),
    path('regulardate/', views.regulardate_cud, name='regulardate_cud'),
    re_path(r'regulardate/(?P<date_id>\d+)/$', views.regulardate_cud, name='regulardate_cud'),
    ]


grammer = input('Enter the grammar: ')
lhs = grammer[0]
f = grammer[3:]
rhs = f.split('|')

grammar = {lhs: rhs}

def minimum_matched_string(a, b, len_a, len_b):
    if len_a == 0 or len_b == 0:
        return 0
    elif a[len_a - 1] == b[len_b - 1]:
        return 1 + minimum_matched_string(a, b, len_a - 1, len_b - 1)
    else:
        return max(minimum_matched_string(a, b, len_a, len_b - 1), minimum_matched_string(a, b, len_a - 1, len_b))

length = 1000
for key in grammar.copy():
    item = grammar[key]
    for i in range(0, len(item) - 1):
        for j in range(i, len(item)):
            if i != j:
                # print(item[i], item[j], len(item[i]), len(item[j]))
                l = minimum_matched_string(item[i], item[j], len(item[i]), len(item[j]))
                if l > 0:
                    if length > l:
                        length = l

exp2 = []
if length > 0:
    common_val = grammar[key][0][:length]
    for i in range(len(grammar[key])):
        if common_val in grammar[key][i]:
            grammar[key][i] = grammar[key][i][length:]
            exp2.append(grammar[key][i])
            grammar[key][i] = ''

exp1 = grammar[key]
for i in range(len(exp1)):
    if '' in exp1:
        exp1.remove('')

exp1.append(common_val + f"{lhs}'")

for i in exp2:
    if i == '':
        ind = exp2.index(i)
        exp2[ind] = 'ε'

fi = f' {lhs}->'
fii = f" {lhs}'->"
# print(exp1)
for i in exp1:
    fi += i + '|'

for i in exp2:
    fii += i + '|'

fi = fi[:-1]
fii = fii[:-1]

print(fi)
print(fii)

# S->iEtS|iEtSeS|a
# A->aab|aac|aaaf|d


from hdmf.utils import docval, call_docval_func, get_docval
from pynwb import register_class, NWBContainer
from pynwb.core import NWBDataInterface, MultiContainerInterface
from pynwb.device import Device

@register_class('ShanksElectrode', 'ndx-franklab-novela')
class ShanksElectrode(NWBContainer):
    ''' Representation of ShanksElectrode object in NWB '''

    @docval(
        {'name': 'name', 'type': str, 'doc': 'name of the shank'},
        {'name': 'rel_x', 'type': float, 'doc': 'the rel_x value of this electrode'},
        {'name': 'rel_y', 'type': float, 'doc': 'the rel_y value of this electrode'},
        {'name': 'rel_z', 'type': float, 'doc': 'the rel_z value of this electrode'},
    )
    def __init__(self, **kwargs):
        super(ShanksElectrode, self).__init__(name=kwargs['name'])
        self.rel_x = kwargs['rel_x']
        self.rel_y = kwargs['rel_y']
        self.rel_z = kwargs['rel_z']

@register_class('Shank', 'ndx-franklab-novela')
class Shank(MultiContainerInterface):
    ''' Representation of Shank object in NWB '''

    @docval(
        {'name': 'name', 'type': str, 'doc': 'name of the shank'},
        {'name': 'shanks_electrodes', 'type': (list, tuple), 'doc': 'electrodes in shank', 'default': list()}
    )
    def __init__(self, **kwargs):
        super(Shank, self).__init__(name=kwargs['name'])
        self.shanks_electrodes = kwargs['shanks_electrodes']

    __clsconf__ = [
        {
            'attr': 'shanks_electrodes',
            'type': ShanksElectrode,
            'add': 'add_shanks_electrode',
            'get': 'get_shanks_electrode'
        }
    ]

@register_class('Probe', 'ndx-franklab-novela')
class Probe(Device, MultiContainerInterface):
    ''' Representation of Probe object in NWB '''

    @docval(*get_docval(Device.__init__) + (
            {'name': 'id', 'type': 'int', 'doc': 'unique id of the probe'},
            {'name': 'probe_type', 'type': 'str', 'doc': 'type of probe'},
            {'name': 'units', 'type': 'str', 'doc': 'units in device'},
            {'name': 'probe_description', 'type': 'str', 'doc': 'description of the probe'},
            {'name': 'contact_side_numbering', 'type': 'bool', 'doc': 'is contact_side_numbering enabled'},
            {'name': 'contact_size', 'type': 'float', 'doc': 'value of contact size as float'},
            {'name': 'shanks', 'type': (list, tuple), 'doc': 'shanks in probe', 'default': list()}
    ))
    def __init__(self, **kwargs):
        super().__init__(**{kwargs_item: kwargs[kwargs_item]
                            for kwargs_item in kwargs.copy()
                            if kwargs_item != 'id'
                            if kwargs_item != 'probe_type'
                            if kwargs_item != 'units'
                            if kwargs_item != 'probe_description'
                            if kwargs_item != 'contact_side_numbering'
                            if kwargs_item != 'contact_size'
                            if kwargs_item != 'shanks'
                            })
        call_docval_func(super(Probe, self).__init__, kwargs)
        self.id = kwargs['id']
        self.probe_type = kwargs['probe_type']
        self.units = kwargs['units']
        self.probe_description = kwargs['probe_description']
        self.contact_side_numbering = kwargs['contact_side_numbering']
        self.contact_size = kwargs['contact_size']
        self.shanks = kwargs['shanks']

    __nwbfields__ = ('id', 'probe_type', 'units', 'probe_description', 'contact_side_numbering',
                     'contact_size')

    __clsconf__ = [
        {
            'attr': 'shanks',
            'type': Shank,
            'add': 'add_shank',
            'get': 'get_shank'
        }
    ]


import  random
class Dices(object):
    def Random1(self):
        r = list(range(1,7))
        print("You Got:",random.choice(r))

d = Dices()

while True:
    n = input("Press any to Roll a dice..!\n Press X to Exit:")
    if n == 'X' or n == 'x':
        break
    else:
        d.Random1()


from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class FilterPage:
    SEARCHBAR = (By.XPATH, "/html/body/app-root/app-clients/header/form")
    LOYALTYFILTER = (
        By.XPATH,
        "/html/body/app-root/app-clients/header/aside/div[1]/app-client-loyality-level-filter/div/div[1]",
    )
    OPTION = (
        By.XPATH,
        "/html/body/app-root/app-clients/header/aside/div[1]/app-client-loyality-level-filter/div/div[2]/mat-checkbox[1]/label/div",
    )
    SEARCH_BTN = (
        By.XPATH,
        "/html/body/app-root/app-clients/header/aside/div[2]/button[1]",
    )

    def __init__(self, driver):
        self.driver = driver

    def check_filters(self):
        wait = WebDriverWait(self.driver, 20)
        searchbar = wait.until(EC.visibility_of_element_located(self.SEARCHBAR))
        searchbar.click()
        loyaltyfilter = wait.until(EC.visibility_of_element_located(self.LOYALTYFILTER))
        loyaltyfilter.click()
        option = wait.until(EC.visibility_of_element_located(self.OPTION))
        option.click()
        loyaltyfilter.click()
        search_btn = wait.until(EC.visibility_of_element_located(self.SEARCH_BTN))
        search_btn.click()


import sys

def input():
    return sys.stdin.readline().rstrip()

def mov(A, m, i):
    B = A.copy()
    for k in range(i):
        for j in range(m):
            B[j] = A[B[j] - 1]
    return B

def main():
    def li():
        return list(map(int, input().split()))

    def mi():
        return map(int, input().split())

    def ii():
        return int(input())

    cycles = [2 ** 2, 3 ** 2, 5, 7, 11, 13, 17, 19, 23]

    def gen_seq():
        seq = []
        for c in cycles:
            seq.extend([(i + 1) % c + len(seq) + 1 for i in range(c)])
        return seq

    seq = gen_seq()
    print(len(seq))
    print(*seq)

    seq2 = list(map(int, input().split()))
    # seq2 = mov(seq, len(seq), 2)
    assert len(seq2) == len(seq)
    # print(*seq2)

    rems = []
    offset = 0
    for size in cycles:
        rems.append(seq2[offset] - (offset + 1))
        offset += size

    x, mm = 0, 1
    for r, m in zip(rems, cycles):
        while x % m != r:
            x += mm
        mm *= m

    print(x)

if __name__ == '__main__':
    main()


#!/usr/bin/python

import argparse
import os
import sys

REASON_PHRASES = {
    400: "Bad Request",
    403: "Forbidden",
    451: "Unavailable",
    502: "Bad Gateway",
    503: "Service Unavailable",
    504: "Gateway Timeout",
}

def status_from_file(f):
    filepath = f.name
    filename = os.path.basename(filepath)
    status_code_str = filename.split(".", 1)[0]
    return int(status_code_str)

def compress_markup(content):
    return content.replace("\n", "")

def write_http_response(stream, status_code, content):
    reason_phrase = REASON_PHRASES[status_code]
    stream.write("HTTP/1.1 %d %s\r\n" % (status_code, reason_phrase))
    stream.write("Content-Type: text/html; charset=UTF-8\r\n")
    stream.write("Content-Length: %d\r\n" % len(content))
    stream.write("\r\n")
    stream.write(content)

def main():
    parser = argparse.ArgumentParser(description="generate an http response")
    parser.add_argument("--no-compress",
                        action="store_false",
                        dest="compress",
                        default=True)
    parser.add_argument("file", type=open)
    args = parser.parse_args()

    status_code = status_from_file(args.file)
    content = args.file.read()
    if args.compress:
        content = compress_markup(content)
    write_http_response(sys.stdout, status_code, content)

if __name__ == "__main__":
    sys.exit(main())


#
# copy_marlin_variant_to_framework.py
#
Import("env")

# Detect that 'vscode init' is running
from SCons.Script import COMMAND_LINE_TARGETS
if "idedata" in COMMAND_LINE_TARGETS:
    env.Exit(0)

import os,shutil
from SCons.Script import DefaultEnvironment
from platformio import util
from platformio.package.meta import PackageSpec

def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

env = DefaultEnvironment()
platform = env.PioPlatform()
board = env.BoardConfig()
variant = board.get("build.variant")

platform_packages = env.GetProjectOption('platform_packages')
# if there's no framework defined, take it from the class name of platform
framewords = {
    "Ststm32Platform": "framework-arduinoststm32",
    "AtmelavrPlatform": "framework-arduino-avr"
}
if len(platform_packages) == 0:
    platform_name = framewords[platform.__class__.__name__]
else:
    platform_name = PackageSpec(platform_packages[0]).name

FRAMEWORK_DIR = platform.get_package_dir(platform_name)
assert os.path.isdir(FRAMEWORK_DIR)
assert os.path.isdir("buildroot/share/PlatformIO/variants")

variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant)

source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant)
assert os.path.isdir(source_dir)

if os.path.isdir(variant_dir):
    shutil.rmtree(variant_dir)

if not os.path.isdir(variant_dir):
    os.mkdir(variant_dir)

copytree(source_dir, variant_dir)


import pygame
from game_objects.puck import Puck
from game_objects.paddle import Paddle
import utils.Color as Color

pygame.init()
clock = pygame.time.Clock()

FPS = 60
DISPLAY_X = 600
DISPLAY_Y = 400
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 50
PADDLE_DISTANCE_FROM_GOAL = 30
PUCK_RADIUS = 10
PUCK_SPEED = 5
PADDLE_SPEED = 10
gameDisplay = pygame.display.set_mode((DISPLAY_X, DISPLAY_Y))

puck = Puck(gameDisplay, board_width=DISPLAY_X, board_height=DISPLAY_Y,
            speed=PUCK_SPEED, radius=PUCK_RADIUS)
paddle_left = Paddle(gameDisplay, x=PADDLE_DISTANCE_FROM_GOAL,
                     board_height=DISPLAY_Y, height=PADDLE_HEIGHT,
                     width=PADDLE_WIDTH, speed = PADDLE_SPEED)
paddle_right = Paddle(gameDisplay, x=DISPLAY_X-PADDLE_DISTANCE_FROM_GOAL,
                      board_height=DISPLAY_Y, height=PADDLE_HEIGHT,
                      width=PADDLE_WIDTH, speed = PADDLE_SPEED)

def game_loop():
    game_exit = False
    while not game_exit:

        # EVENT HANDLER
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    game_exit = True
                if event.key == pygame.K_UP:
                    paddle_right.set_speed(-1)
                elif event.key == pygame.K_DOWN:
                    paddle_right.set_speed(1)
                if event.key == pygame.K_w:
                    paddle_left.set_speed(-1)
                elif event.key == pygame.K_s:
                    paddle_left.set_speed(1)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    paddle_right.set_speed(0)
                if event.key == pygame.K_DOWN:
                    paddle_right.set_speed(0)
                if event.key == pygame.K_w:
                    paddle_left.set_speed(0)
                elif event.key == pygame.K_s:
                    paddle_left.set_speed(0)

        puck.checkPaddle(paddle_left)
        puck.checkPaddle(paddle_right)
        puck.update()
        paddle_left.update()
        paddle_right.update()

        gameDisplay.fill(Color.BLACK)
        puck.show()
        paddle_left.show()
        paddle_right.show()
        pygame.display.update()

        clock.tick(FPS)

game_loop()

pygame.quit()
quit()


# coding=utf-8
from __future__ import unicode_literals

from .. import Provider as AutomotiveProvider

class Provider(AutomotiveProvider):

    # From: https://pt.wikipedia.org/wiki/Matr%C3%ADculas_de_autom%C3%B3veis_em_Portugal
    license_formats = (
        '##-##-??',
        '##-??-##',
        '??-##-##',
    )


class Node:
    def __init__(self,k):
        self.left=None
        self.right=None
        self.key=k

root=Node(10)
root.left=Node(20)
root.right=Node(30)
root.left.left=Node(40)

print(root.key)


import sys
sys.setrecursionlimit(10 ** 6)

dx = [-1, -1, -1, 1, 1, 1, 0, 0]
dy = [-1, 0, 1, -1, 0, 1, -1, 1]

def dfs(x, y):
    visit[x][y] = True

    for i in range(8):
        nx = x + dx[i]
        ny = y + dy[i]

        if nx >= 0 and nx < h and ny >= 0 and ny < w:
            if not visit[nx][ny] and li[nx][ny] == 1:
                dfs(nx, ny)

while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    else:
        li = [[] for _ in range(h)]
        visit = [[False] * w for _ in range(h)]
        cnt = 0

        for i in range(h):
            li[i] = list(map(int, input().split()))

        for i in range(h):
            for j in range(w):
                if not visit[i][j] and li[i][j] == 1:
                    cnt += 1
                    dfs(i, j)
        print(cnt)


import random
import torch
import torch.nn as nn
from torch.distributions import kl_divergence
from torch.nn.modules.rnn import GRU, GRUCell
from torch.nn.utils.rnn import pack_padded_sequence
from torch.distributions.normal import Normal
from torchdiffeq import odeint as odeint
import utils

class ODEFunc(nn.Module):
    def __init__(self, ode_func_net, nonlinear=None):
        super(ODEFunc, self).__init__()
        self.net = ode_func_net
        self.nonlinear = nonlinear

    def forward(self, t, x):
        """
        Perform one step in solving ODE.
        """
        return self.nonlinear(self.net(x)) if self.nonlinear else self.net(x)

class DiffeqSolver(nn.Module):

    def __init__(self, ode_func, method, odeint_rtol, odeint_atol):
        super(DiffeqSolver, self).__init__()
        self.ode_func = ode_func
        self.ode_method = method
        self.odeint_rtol = odeint_rtol
        self.odeint_atol = odeint_atol

    def forward(self, first_point, time_steps, odeint_rtol=None, odeint_atol=None, method=None):
        """
            Decode the trajectory through ODE Solver
            @:param first_point, shape [N, D]
                    time_steps, shape [T,]
            @:return predicted the trajectory, shape [N, T, D]
        """
        if not odeint_rtol:
            odeint_rtol = self.odeint_rtol
        if not odeint_atol:
            odeint_atol = self.odeint_atol
        if not method:
            method = self.ode_method
        pred = odeint(self.ode_func, first_point, time_steps,
                      rtol=odeint_rtol, atol=odeint_atol, method=method)  # [T, N, D]
        pred = pred.permute(1, 0, 2)  # [N, T, D]
        assert (torch.mean(pred[:, 0, :] - first_point) < 0.001)  # the first prediction is same with first point
        assert pred.size(0) == first_point.size(0)
        assert pred.size(1) == time_steps.size(0)
        assert pred.size(2) == first_point.size(1)
        return pred

class Encoder_z0_RNN(nn.Module):

    def __init__(self, latent_dim, input_dim, device, hidden_to_z0_units=20, bidirectional=False):
        super(Encoder_z0_RNN, self).__init__()
        self.device = device
        self.latent_dim = latent_dim  # latent dim for z0 and encoder rnn
        self.input_dim = input_dim
        self.hidden_to_z0 = nn.Sequential(
            nn.Linear(2 * latent_dim if bidirectional else latent_dim, hidden_to_z0_units),
            nn.Tanh(),
            nn.Linear(hidden_to_z0_units, 2 * latent_dim))
        self.rnn = GRU(input_dim, latent_dim, batch_first=True, bidirectional=bidirectional).to(device)

    def forward(self, data, time_steps, lengths):
        """
            Encode the mean and log variance of initial latent state z0
            @:param data, shape [N, T, D]
                    time_steps, shape [N, T]
                    lengths, shape [N,]
            @:return mean, logvar of z0, shape [N, D_latent]
        """
        data_packed = pack_padded_sequence(data, lengths, batch_first=True, enforce_sorted=False)
        _, hidden = self.rnn(data_packed)
        assert hidden.size(1) == data.size(0)
        assert hidden.size(2) == self.latent_dim

        # check if bidirectional
        if hidden.size(0) == 1:
            hidden = hidden.squeeze(0)
        elif hidden.size(0) == 2:
            hidden = torch.cat((hidden[0], hidden[1]), dim=-1)
        else:
            raise ValueError('Incorrect RNN hidden state.')

        # extract mean and logvar
        mean_logvar = self.hidden_to_z0(hidden)
        assert mean_logvar.size(-1) == 2 * self.latent_dim
        mean, logvar = mean_logvar[:, :self.latent_dim], mean_logvar[:, self.latent_dim:]
        return mean, logvar

class Decoder(nn.Module):
    def __init__(self, latent_dim, input_dim, n_layers=0, n_units=0):
        super(Decoder, self).__init__()
        self.decoder = utils.create_net(latent_dim, input_dim, n_layers=n_layers, n_units=n_units, nonlinear=nn.ReLU)

    def forward(self, data):
        return self.decoder(data)

class Timer(nn.Module):
    """
        Timer without learning to timing
    """

    def __init__(self, input_dim, output_dim, min_t, max_t, max_time_length, device):
        super(Timer, self).__init__()
        self.device = device
        self.input_dim = input_dim
        self.output_dim = output_dim
        if output_dim > 1:  # discrete
            assert max_t - min_t + 1 == output_dim
            self.is_continuous = False
        else:
            self.is_continuous = True
        self.min_t = min_t
        self.max_t = max_t
        self.max_time_length = max_time_length
        self.t = 0

    def __repr__(self):
        return 'Timer'

    def compute_loss(self, x, dts, masks):
        raise NotImplementedError

    def deliver_dt(self, x, choice='random'):
        if choice == 'min':
            dt = self.min_t
        elif choice == 'max':
            dt = self.max_t
        elif choice == 'mean':
            t_mean = (self.min_t + self.max_t) / 2
            dt = t_mean if self.is_continuous else int(t_mean)
        elif choice == 'random':
            dt = random.uniform(self.min_t, self.max_t) if self.is_continuous \
                else random.randint(self.min_t, self.max_t)
        elif (type(choice) == int or type(choice) == float) and self.min_t <= choice <= self.max_t:
            dt = choice
        else:
            raise NotImplementedError
        self.t += dt
        return dt

    def get_time_info(self):
        return self.min_t, self.max_t, self.is_continuous

    def is_terminal(self):
        return self.t >= self.max_time_length

    def reset(self):
        self.t = 0

class MLPTimer(Timer):
    """
        Timer with learning to timing using MLP
    """

    def __init__(self, input_dim, output_dim, min_t, max_t, max_time_length, device):
        super(MLPTimer, self).__init__(input_dim, output_dim, min_t, max_t, max_time_length, device)
        self.net = utils.create_net(input_dim, output_dim, n_layers=1, n_units=20, nonlinear=nn.Tanh)
        self.criterion = nn.MSELoss() if self.is_continuous else nn.CrossEntropyLoss()

    def __repr__(self):
        return 'MLPTimer'

    def compute_loss(self, x, dts, masks):
        """
            Compute MSE or CE loss for learning time interval
            @:param x, input [N, T, D]
                    dts, target [N, T]
                    lengths, shape [N,]
            @:return loss
        """
        pred_dts = self.net(x)
        assert pred_dts.size(0) == dts.size(0)
        assert pred_dts.size(1) == dts.size(1)
        if self.is_continuous:
            return self.criterion(pred_dts[masks].squeeze(-1), dts[masks])
        else:
            return self.criterion(pred_dts[masks], dts[masks].long() - self.min_t)

    def deliver_dt(self, x, choice='learned'):
        """
            Generate one-step time gap given current state and action
            @:param x, input, [D,]
            @:return: dt
        """
        if choice == 'learned':
            with torch.no_grad():
                x = self.net(x)
                dt = self.min_t + x.argmax(dim=-1).item() if not self.is_continuous \
                    else torch.clamp(x, self.min_t, self.max_t).item()
                self.t += dt
        else:
            dt = super().deliver_dt(x, choice)
        return dt

    def deliver_dt_in_batch(self, x):
        """
            Generate a batch of one-step time gap given current states and actions
            @:param x, input, [N, D]
            @:return: dt, [N,]
        """
        with torch.no_grad():
            x = self.net(x)
            dts = self.min_t + x.argmax(dim=-1) if not self.is_continuous \
                else torch.clamp(x, self.min_t, self.max_t).squeeze(-1)
        return dts.float()

class BaseRecurrentModel(nn.Module):
    """
        Base recurrent model as an abstract class
    """

    def __init__(self, input_dim, latent_dim, eps_decay, decoder, timer, device):
        super(BaseRecurrentModel, self).__init__()
        self.input_dim = input_dim
        self.latent_dim = latent_dim
        self.device = device
        self.decoder = decoder
        self.timer = timer
        self.eps = 1.
        self.eps_decay = eps_decay
        self.i_step = 0
        self.criterion = nn.MSELoss()

    def __repr__(self):
        return "BaseRecurrentModel"

    def decay_eps(self):
        """
            Linear decay
        """
        if self.eps_decay > 0 and self.eps > 0:
            self.eps = max(0, 1. - self.eps_decay * self.i_step)
        self.i_step += 1

    def encode_next_latent_state(self, data, latent_state, dts):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        raise NotImplementedError("Abstract class cannot be used.")

    def encode_latent_traj(self, states, actions, time_steps, train=True):
        """
            Encode latent trajectories given states, actions and timesteps
            @:param states, shape [N, T, D_state]
                    actions, shape [N, T, D_action]
                    time_steps, shape [N, T+1]
            @:return hs, shape [N, T+1, D_latent]
        """
        N = states.size(0)
        pred_next_states = []
        hs = [self.sample_init_latent_states(num_trajs=N)]  # hs[-1] [N, D_latent]
        for i in range(time_steps.size(1) - 1):
            if i == 0 or (train and self.eps_decay == 0):
                data = torch.cat((states[:, i, :], actions[:, i, :]), dim=-1)  # [N, D_state+D_action]
            else:
                data = torch.cat((pred_next_states[-1], actions[:, i, :]), dim=-1)
                if train and self.eps > 0:  # scheduled sampling
                    heads = torch.rand(N) < self.eps  # [N,]
                    data[heads] = torch.cat((states[:, i, :], actions[:, i, :]), dim=-1)[heads]
            hs.append(self.encode_next_latent_state(data, hs[-1], time_steps[:, i + 1] - time_steps[:, i]))
            pred_next_states.append(self.decode_latent_traj(hs[-1]))
        hs = torch.stack(hs).permute(1, 0, 2)  # [N, T+1, D_latent]
        pred_next_states = torch.stack(pred_next_states).permute(1, 0, 2)  # [N, T, D_state]
        if train:
            self.decay_eps()

        assert hs.size(0) == N
        assert hs.size(1) == time_steps.size(1)
        assert hs.size(2) == self.latent_dim
        return hs, pred_next_states

    def decode_latent_traj(self, hs):
        """
            Decode latent trajectories
            @:param hs, shape [N, T, D_latent]
            @:return shape [N, T, D_state]
        """
        return self.decoder(hs)

    def predict_next_states(self, states, actions, time_steps, train=True):
        """
            Predict next states given states, actions and timesteps
            @:param states, shape [N, T, D_state]
                    actions, shape [N, T, D_action]
                    time_steps, shape [N, T+1]
            @:return next_states, shape [N, T, D_state]
                     hs (current latent states), shape [N, T, D_latent]
        """
        # encoding and decoding
        hs, next_states = self.encode_latent_traj(states, actions, time_steps, train=train)  # [N, T+1, D_latent]
        return next_states, hs[:, :-1, :]

    def compute_loss(self, states, actions, time_steps, lengths, dt_coef=.01, train=True):
        """
            Compute RNN loss
            @:param states, shape [N, T+1, D_state]
                    actions, shape [N, T, D_action]
                    time_steps, shape [N, T+1]
                    lengths, shape [N,]
                    dt_coef, the coefficient before dt loss term
            @:return total loss = mse + dt loss,
                     mse loss
        """
        # predict next states
        traj_cur_states, traj_next_states = states[:, :-1, :], states[:, 1:, :]
        traj_pred_next_states, traj_cur_latent_states = self.predict_next_states(traj_cur_states, actions, time_steps,
                                                                                train=train)
        max_len = lengths.max()
        masks = torch.arange(max_len, device=self.device).expand(lengths.size(0), max_len) < lengths.unsqueeze(1)
        mse_loss = self.criterion(traj_next_states[masks], traj_pred_next_states[masks])

        # loss for time gap prediction
        if repr(self.timer) != 'Timer':
            dts = time_steps[:, 1:] - time_steps[:, :-1]
            dt_loss = self.timer.compute_loss(torch.cat((traj_cur_states, actions, traj_cur_latent_states), dim=-1),
                                              dts, masks)
        else:
            dt_loss = torch.tensor([0.], device=self.device)

        return {'total': mse_loss + dt_coef * dt_loss, 'mse': mse_loss, 'dt': dt_loss}

    def sample_init_latent_states(self, num_trajs=0):
        shape = (self.latent_dim,) if num_trajs == 0 else (num_trajs, self.latent_dim)
        return torch.zeros(shape, dtype=torch.float, device=self.device)

class VanillaGRU(BaseRecurrentModel):
    """
        Vanilla GRU
    """

    def __init__(self, input_dim, latent_dim, eps_decay, decoder, timer, device):
        super(VanillaGRU, self).__init__(input_dim, latent_dim, eps_decay, decoder, timer, device)
        self.gru_cell = GRUCell(input_dim, latent_dim)

    def __repr__(self):
        return "VanillaGRU"

    def encode_next_latent_state(self, data, latent_state, dts):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        return self.gru_cell(data, latent_state)

class DeltaTGRU(BaseRecurrentModel):
    """
        GRU by combining time gaps as input
    """

    def __init__(self, input_dim, latent_dim, eps_decay, decoder, timer, device):
        super(DeltaTGRU, self).__init__(input_dim, latent_dim, eps_decay, decoder, timer, device)
        # +1 dim for time gaps
        self.input_dim = input_dim + 1
        self.gru_cell = GRUCell(input_dim + 1, latent_dim).to(device)

    def __repr__(self):
        return "DeltaTGRU"

    def encode_next_latent_state(self, data, latent_state, dts):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        return self.gru_cell(torch.cat((data, dts.unsqueeze(-1)), dim=-1), latent_state)

class ExpDecayGRU(BaseRecurrentModel):
    """
        GRU with intermediate Exponential decay layer
    """

    def __init__(self, input_dim, latent_dim, eps_decay, decoder, timer, device):
        super(ExpDecayGRU, self).__init__(input_dim, latent_dim, eps_decay, decoder, timer, device)
        self.gru_cell = GRUCell(input_dim, latent_dim).to(device)
        self.decay_layer = nn.Linear(1, 1).to(device)

    def __repr__(self):
        return "ExpDecayGRU"

    def encode_next_latent_state(self, data, latent_state, dts):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        N = data.size(0)
        decay_coef = torch.exp(-torch.max(torch.zeros(N, 1, dtype=torch.float, device=self.device),
                                          self.decay_layer(dts.unsqueeze(-1))))
        assert decay_coef.size(0) == N
        assert decay_coef.size(1) == 1
        return self.gru_cell(data, decay_coef * latent_state)

class ODEGRU(BaseRecurrentModel):
    """
        GRU with intermediate ODE layer
    """

    def __init__(self, input_dim, latent_dim, eps_decay, decoder, diffeq_solver, timer, device):
        super(ODEGRU, self).__init__(input_dim, latent_dim, eps_decay, decoder, timer, device)
        self.diffeq_solver = diffeq_solver
        self.gru_cell = GRUCell(input_dim, latent_dim).to(device)

    def __repr__(self):
        return "ODEGRU"

    def encode_next_latent_state(self, data, latent_state, dts, odeint_rtol=None, odeint_atol=None, method=None):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        N = data.size(0)
        ts, inv_indices = torch.unique(dts, return_inverse=True)
        if ts[-1] == 0:
            return latent_state
        if ts[0] != 0:
            ts = torch.cat([torch.zeros(1, dtype=torch.float, device=self.device), ts])
            inv_indices += 1
        traj_latent_state = self.diffeq_solver(latent_state, ts, odeint_rtol, odeint_atol, method)
        selected_indices = tuple([torch.arange(N, dtype=torch.long, device=self.device), inv_indices])
        new_latent_state = traj_latent_state[selected_indices]  # [N, D_latent]
        assert new_latent_state.size(0) == N
        assert new_latent_state.size(1) == self.latent_dim
        return self.gru_cell(data, new_latent_state)

class BaseVAEModel(nn.Module):
    """
        Base VAE model as an abstract class
    """

    def __init__(self, input_dim, latent_dim, eps_decay, encoder_z0, decoder, timer, z0_prior, device):
        super(BaseVAEModel, self).__init__()
        self.input_dim = input_dim
        self.latent_dim = latent_dim
        self.device = device
        self.encoder_z0 = encoder_z0
        self.decoder = decoder
        self.timer = timer
        self.z0_prior = z0_prior
        self.eps = 1.
        self.eps_decay = eps_decay
        self.i_step = 0
        self.criterion = nn.MSELoss()

    def __repr__(self):
        return "BaseVAEModel"

    def decay_eps(self):
        """
            Linear decay
        """
        if self.eps_decay > 0 and self.eps > 0:
            self.eps = max(0, 1. - self.eps_decay * self.i_step)
        self.i_step += 1

    def encode_next_latent_state(self, data, latent_state, dts):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        raise NotImplementedError("Abstract class cannot be used.")

    def encode_latent_traj(self, states, actions, time_steps, lengths, train=True):
        """
            Encode latent trajectories given states, actions and timesteps
            @:param states, shape [N, T, D_state]
                    actions, shape [N, T, D_action]
                    time_steps, shape [N, T+1]
                    lengths, shape [N,]
            @:return hs, shape [N, T+1, D_latent]
        """
        N = states.size(0)
        if train:
            # encoding
            means_z0, logvars_z0 = self.encoder_z0(torch.cat((states, actions), dim=-1), time_steps, lengths)

            # reparam
            stds_z0 = torch.exp(0.5 * logvars_z0)
            eps = torch.randn_like(stds_z0)
            z0s = means_z0 + eps * stds_z0  # [N, D_latent]
        else:
            means_z0, stds_z0 = None, None
            z0s = self.sample_init_latent_states(num_trajs=N)

        # solve trajectory
        pred_next_states = []
        zs = [z0s]
        for i in range(time_steps.size(1) - 1):
            if i == 0 or (train and self.eps_decay == 0):
                data = torch.cat((states[:, i, :], actions[:, i, :]), dim=-1)  # [N, D_state+D_action]
            else:
                data = torch.cat((pred_next_states[-1], actions[:, i, :]), dim=-1)
                if train and self.eps > 0:  # scheduled sampling
                    heads = torch.rand(N) < self.eps  # [N,]
                    data[heads] = torch.cat((states[:, i, :], actions[:, i, :]), dim=-1)[heads]
            zs.append(self.encode_next_latent_state(data, zs[-1], time_steps[:, i + 1] - time_steps[:, i]))
            pred_next_states.append(self.decode_latent_traj(zs[-1]))
        zs = torch.stack(zs).permute(1, 0, 2)  # [T+1, N, D_latent]
        pred_next_states = torch.stack(pred_next_states).permute(1, 0, 2)  # [N, T, D_state]
        if train:
            self.decay_eps()

        assert zs.size(0) == N
        assert zs.size(1) == time_steps.size(1)
        assert zs.size(2) == self.latent_dim
        return zs, means_z0, stds_z0, pred_next_states

    def decode_latent_traj(self, zs):
        """
            Decode latent trajectories
            @:param zs, shape [N, T, D_latent]
            @:return shape [N, T, D_state]
        """
        return self.decoder(zs)

    def predict_next_states(self, states, actions, time_steps, lengths, train=True):
        """
            Predict next states given states, actions and timesteps
            @:param states, shape [N, T, D_state]
                    actions, shape [N, T, D_action]
                    time_steps, shape [N, T+1]
                    lengths, shape [N,]
            @:return next_states, shape [N, T, D_state]
                     zs (current latent states), shape [N, T, D_latent]
                     mean_z,
                     std_z
        """
        # encoding and decoding
        zs, means_z0, stds_z0, next_states = self.encode_latent_traj(states, actions, time_steps, lengths,
                                                                     train=train)  # [N, T+1, D_latent]
        return next_states, zs[:, :-1, :], means_z0, stds_z0

    def compute_loss(self, states, actions, time_steps, lengths, dt_coef=.01, kl_coef=1., train=True):
        """
            Compute VAE's loss
            @:param states, shape [N, T+1, D_state]
                    actions, shape [N, T, D_action]
                    time_steps, shape [N, T]
                    lengths, shape [N,]
                    dt_coef, the coefficient before dt loss term
                    kl_coef, the coefficient before kl term
            @:return total loss = mse + dt loss + kl_coef * kl_div
                     mse loss
        """
        # predict next states
        traj_cur_states, traj_next_states = states[:, :-1, :], states[:, 1:, :]
        traj_pred_next_states, traj_cur_latent_states, means_z0, stds_z0 = \
            self.predict_next_states(traj_cur_states, actions, time_steps, lengths, train=train)
        max_len = lengths.max()
        masks = torch.arange(max_len, device=self.device).expand(lengths.size(0), max_len) < lengths.unsqueeze(1)
        mse_loss = self.criterion(traj_next_states[masks], traj_pred_next_states[masks])

        # loss for time gap prediction
        if repr(self.timer) != 'Timer':
            dts = time_steps[:, 1:] - time_steps[:, :-1]
            dt_loss = self.timer.compute_loss(torch.cat((traj_cur_states, actions, traj_cur_latent_states), dim=-1),
                                              dts, masks)
        else:
            dt_loss = torch.tensor([0.], device=self.device)

        if train:
            # kl
            z0_dist = Normal(means_z0, stds_z0)
            kl_losses = kl_divergence(z0_dist, self.z0_prior)  # [N, D_latent]
            assert not torch.isnan(kl_losses).any()
            kl_loss = kl_losses.mean()
            return {'total': mse_loss + dt_coef * dt_loss + kl_coef * kl_loss, 'mse': mse_loss, 'dt': dt_loss,
                    'kl': kl_loss}
        else:
            return {'total': mse_loss + dt_coef * dt_loss, 'mse': mse_loss, 'dt': dt_loss}

    def sample_init_latent_states(self, num_trajs=0):
        shape = (self.latent_dim,) if num_trajs == 0 else (num_trajs, self.latent_dim)
        return self.z0_prior.sample(sample_shape=shape).squeeze(-1)

class VAEGRU(BaseVAEModel):
    """
        VAE with RNN encoder and RNN decoder
    """

    def __init__(self, input_dim, latent_dim, eps_decay, encoder_z0, decoder, timer, z0_prior, device):
        super(VAEGRU, self).__init__(input_dim, latent_dim, eps_decay, encoder_z0, decoder, timer, z0_prior, device)
        self.gru_cell = GRUCell(input_dim, latent_dim).to(device)

    def __repr__(self):
        return "VAEGRU"

    def encode_next_latent_state(self, data, latent_state, dts):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        return self.gru_cell(data, latent_state)

class LatentODE(BaseVAEModel):
    """
        Latent ODE
    """

    def __init__(self, input_dim, latent_dim, eps_decay, encoder_z0, decoder, diffeq_solver, timer, z0_prior, device):
        super(LatentODE, self).__init__(input_dim, latent_dim, eps_decay, encoder_z0, decoder, timer, z0_prior, device)
        self.diffeq_solver = diffeq_solver
        self.aug_layer = nn.Linear(input_dim + latent_dim, latent_dim).to(device)

    def __repr__(self):
        return "LatentODE"

    def encode_next_latent_state(self, data, latent_state, dts, odeint_rtol=None, odeint_atol=None, method=None):
        """
            predict the next latent state based on the input and the last latent state
            @:param data, shape [N, D]
                    latent_state, shape [N, D_latent]
                    dts, shape [N,]
            @:return shape [N, D_latent]
        """
        N = data.size(0)
        ts, inv_indices = torch.unique(dts, return_inverse=True)
        if ts[-1] == 0:
            return latent_state
        if ts[0] != 0:
            ts = torch.cat([torch.zeros(1, dtype=torch.float, device=self.device), ts])
            inv_indices += 1
        aug_latent_state = self.aug_layer(torch.cat((data, latent_state), dim=-1))
        traj_latent_state = self.diffeq_solver(aug_latent_state, ts, odeint_rtol, odeint_atol, method)
        selected_indices = tuple([torch.arange(N, dtype=torch.long, device=self.device), inv_indices])
        new_latent_state = traj_latent_state[selected_indices]  # [N, D_latent]
        assert new_latent_state.size(0) == N
        assert new_latent_state.size(1) == self.latent_dim
        return new_latent_state

    def rollout_timeline(self, data, latent_state, dts):
        aug_latent_state = self.aug_layer(torch.cat((data, latent_state), dim=-1))
        traj_latent_state = self.diffeq_solver(aug_latent_state, dts)
        return traj_latent_state  # [1, T, D]


import numpy as np
import utils
import datetime
import cpuinfo
import os
import sys
import uuid
import tensorcircuit as tc

def tensorcircuit_benchmark(
    uuid,
    tcbackend,
    n,
    nlayer,
    nitrs,
    timeLimit,
    isgpu,
    mpsd,
    dt="32",
    minus=1,
    contractor="auto",
):
    meta = {}

    if isgpu == 0:
        os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
        meta["isgpu"] = "off"

    else:
        # gpu = tf.config.list_physical_devices("GPU")
        # tf.config.experimental.set_memory_growth(device=gpu[0], enable=True)
        meta["isgpu"] = "on"
        meta["Gpuinfo"] = utils.gpuinfo()
    tc.set_backend(tcbackend)
    if dt == "32":
        tc.set_dtype("complex64")
        dtype = "complex64"
        vtype = "float32"
    else:  # dt == "64":
        tc.set_dtype("complex128")
        dtype = "complex128"
        vtype = "float64"
    if contractor not in ["auto", "cotengra"]:
        tc.set_contractor(contractor)
    elif contractor == "cotengra":
        import cotengra as ctg

        opt0 = ctg.ReusableHyperOptimizer(
            minimize="combo",
            max_repeats=512,
            max_time=90,
            progbar=True,
        )

        # def opt_reconf(inputs, output, size, **kws):
        #     tree = opt0.search(inputs, output, size)
        #     tree_r = tree.subtree_reconfigure_forest(
        #         progbar=True,
        #         num_trees=20,
        #         num_restarts=10,
        #         subtree_weight_what=("flops",),
        #     )
        #     return tree_r.get_path()

        tc.set_contractor(
            "custom",
            optimizer=opt0,
            contraction_info=True,
            preprocessing=True,
        )

    meta["contractor"] = contractor

    def tfi_energy(c, n, j=1.0, h=-1.0):
        e = 0.0
        for i in range(n):
            e += h * c.expectation((tc.gates.x(), [i]))
        for i in range(n - 1):
            e += j * c.expectation((tc.gates.z(), [i]), (tc.gates.z(), [(i + 1) % n]))
        return e

    meta["Software"] = "tensorcircuit[%s %s]" % (tcbackend, dt)
    meta["minus"] = minus
    meta["Cpuinfo"] = cpuinfo.get_cpu_info()["brand_raw"]
    meta["Version"] = {
        "sys": sys.version,
        "tensorcircuit": tc.__version__,
        "numpy": np.__version__,
    }
    meta["VQE test parameters"] = {
        "mpsd": mpsd,
        "nQubits": n,
        "nlayer": nlayer,
        "nitrs": nitrs,
        "timeLimit": timeLimit,
    }
    meta["UUID"] = uuid
    meta["Benchmark Time"] = (
        datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z")
    )
    meta["Results"] = {}

    paramx = tc.backend.ones(nlayer * n, dtype=vtype)
    paramzz = tc.backend.ones(nlayer * n, dtype=vtype)

    def energy_raw(paramx, paramzz):
        if mpsd is None:
            c = tc.Circuit(n)
        else:
            c = tc.MPSCircuit(n)
            c.set_split_rules({"max_singular_values": mpsd})
        paramx = tc.backend.cast(paramx, dtype)
        paramzz = tc.backend.cast(paramzz, dtype)

        for i in range(n):
            c.H(i)
        for j in range(nlayer):
            for i in range(n - minus):
                c.exp1(
                    i,
                    (i + 1) % n,
                    theta=paramzz[j * n + i],
                    unitary=tc.gates._zz_matrix,
                )
            for i in range(n):
                c.rx(i, theta=paramx[j * n + i])
        if mpsd is None:
            e = tfi_energy(c, n)
            fd = 1.0
        else:
            e = tfi_energy(c, n)
            fd = c._fidelity
        # tensorflow only works for complex case, while jax only works for real case, don't know how to solve it
        # if tcbackend != "tensorflow":
        e = tc.backend.real(e)

        return e, fd

    energy_raw = tc.backend.value_and_grad(energy_raw, argnums=(0, 1), has_aux=True)
    energy_raw = tc.backend.jit(energy_raw)

    def energy(paramx, paramzz):
        # paramx = tc.backend.convert_to_tensor(paramx)
        # paramzz = tc.backend.convert_to_tensor(paramzz)
        (value, f), grads = energy_raw(paramx, paramzz)
        print("fidelity: ", f, value)
        # print(tc.backend.numpy(f), tc.backend.numpy(value))
        # value = tc.backend.numpy(tc.backend.real(value))
        # grads = [tc.backend.numpy(tc.backend.real(g)) for g in grads]
        return value, grads

    opt = utils.Opt(energy, [paramx, paramzz], tuning=True, backend=tcbackend)
    ct, it, Nitrs = utils.timing(opt.step, nitrs, timeLimit)
    meta["Results"]["with jit"] = {
        "Construction time": ct,
        "Iteration time": it,
        "# of actual iterations": Nitrs,
    }
    print(meta)
    return meta

if __name__ == "__main__":
    _uuid = str(uuid.uuid4())
    (
        n,
        nlayer,
        nitrs,
        timeLimit,
        isgpu,
        minus,
        path,
        dtype,
        contractor,
        mpsd,
        tcbackend,
    ) = utils.arg(dtype=True, contractor=True, mps=True, tc=True)
    if dtype == 1:
        dtypestr = "32"
    else:
        dtypestr = "64"

    r = tensorcircuit_benchmark(
        _uuid,
        tcbackend,
        n,
        nlayer,
        nitrs,
        timeLimit,
        isgpu,
        mpsd,
        dtypestr,
        minus=minus,
        contractor=contractor,
    )
    utils.save(r, _uuid, path)


# -*- coding: utf-8 -*-
import numpy as np
from scipy.stats import norm as scipy_norm

from ._patcher import Patcher

class GaussianPatcher(Patcher):
    def __init__(self,
                 area_mean=10.0,
                 area_cov=5.0,
                 eccentricity=0.5,
                 neighbors_structure='rook',
                 avoid_aggregation=True,
                 nb_of_missing_to_fill=1,
                 proceed_even_if_no_probability=True,
                 n_tries_target_sample=1000,
                 equi_neighbors_proba=False):
        super().__init__(neighbors_structure = neighbors_structure,
                         avoid_aggregation = avoid_aggregation,
                         nb_of_missing_to_fill = nb_of_missing_to_fill,
                         proceed_even_if_no_probability = proceed_even_if_no_probability,
                         n_tries_target_sample=n_tries_target_sample,
                         equi_neighbors_proba=equi_neighbors_proba)

        self.area_mean = area_mean
        self.area_cov = area_cov
        self.eccentricity = eccentricity

    def _sample(self, n):
        eccentricities = np.ones(n) * self.eccentricity
        areas = scipy_norm.rvs(loc=self.area_mean,
                               scale=self.area_cov,
                               size=n)
        areas[areas < 1] = 1

        return (areas, eccentricities)


import os.path

from . import IpfsHttpServerError
from .request import iphttp_request_path

async def cli_get(ctx, *params, q={}, **kwargs):
    if not ctx.peer_id_current:
        raise ValueError('No peer set')

    q = kwargs.pop('q', {})
    headers = kwargs.pop('h', {})
    path = ctx.peer_id_current

    for param in params:
        path = os.path.join(path, param.lstrip('/'))

    try:
        await iphttp_request_path(ctx.client,
                                  path,
                                  headers=headers,
                                  params=q)
    except IpfsHttpServerError:
        raise

async def cli_post(ctx, *params, **kwargs):
    if not ctx.peer_id_current:
        raise ValueError('No peer set')

    q = kwargs.pop('q', {})
    headers = kwargs.pop('h', {})
    user_data = kwargs.pop('data', {})
    path = ctx.peer_id_current
    data = {}

    for param in params:
        if isinstance(param, str):
            path = os.path.join(path, param.lstrip('/'))

    if isinstance(user_data, dict):
        data.update(user_data)

    try:
        return await iphttp_request_path(ctx.client,
                                         path,
                                         headers=headers,
                                         params=q,
                                         data=data,
                                         method='POST')
    except IpfsHttpServerError:
        raise


#Exercise 3
# true, true, false, false, true, false,

#Exercise 4
my_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
print (len(my_text))

#Exercise 5
a_used = False
maxcounter = 0
while a_used == False:
    sentence = input('Enter the longest sentence you can write without using the A letter  ')
    counter = 0
    for char in sentence:
        if char == 'a' or char == 'A':
            a_used = True
            maxcounter = 0
            print ('You lost! Your record has been set to {}'.format(maxcounter))
            break
        else:
            counter = counter + 1
            if counter > maxcounter:
                print('Congratulations! Your record now is {}'.format(maxcounter))
                maxcounter = counter


import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging

class TezosRPCClient:
    TIMEOUT = 5.0  # seconds
    RETRIES = 3

    def __init__(self, node_url='http://localhost:8732'):
        self.node_url = node_url

    def send_request(self, uri):
        url = '{}/{}'.format(self.node_url, uri)
        logging.info('Performing get request {}'.format(url))
        response = None
        with requests.Session() as s:
            retries = Retry(
                total=self.RETRIES,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504])
            s.mount('http://', HTTPAdapter(max_retries=retries))
            s.mount('https://', HTTPAdapter(max_retries=retries))
            response = s.get(url, timeout=self.TIMEOUT)
            logging.info('Got response {}'.format(response))
        return response

    def get_current_block(self):
        r = self.send_request('monitor/bootstrapped')
        return r.json()['block']

    def get_current_level(self):
        current_block = self.get_current_block()
        r = self.send_request('chains/main/blocks/{}/header'.format(current_block))
        return r.json()['level']