import os
import time
import string
import nltk

# starterbot's ID as an environment variable
BOT_ID = os.environ.get("BOT_ID")

# constants
AT_BOT = "<@" + BOT_ID + ">"
test_breaks = [':', '/']
#keywords
keyword_lists = ["i'll", "me", "i", "im", "i'm"],\
                ["leaving", "gone", "left", "going", "out", "sick", "vacation",  "ill", "go"],\
                ["monday","tuesday","wendesday","thursday","friday","saturday","sunday"],\
                ["arrive", "arriving", "get", "until", "back"],\
                ["january", "february","march","april","may","june","july","august",\
                "september", "october", "november", "december","jan","feb","mar",\
                "apr","may","jun","jul","aug","sept", "oct","nov","dec"],\
                ["st", "nd", "rd", "th"],\
                ["am", "pm","a.m", "p.m"],\
                ["am", "pm"],\
                ["from", "between", ","]
#definitions for each list catagory
SELF_TARGET_DEF = 0
LEAVING_DEF = 1
DAY_DEF = 2
ARRIVING_DEF = 3
MONTH_DEF = 4
DATE_DEF = 5
TIME_DEF = 6
GOOD_TIME_DEF = 7
SPLIT_DEF = 8
#fail constants
FAIL_CONST = -1
FAIL_LIST = [-1,-1,-1,-1]

def check_num(str_val):
    """
        check if given string is an int
    """
    for test in test_breaks:
        if test in str_val:
            try:
                int(str_val.split(test)[0])
                int(str_val.split(test)[1])
                return True
            except ValueError:
                return False
    try:
        int(str_val)
        return True
    except ValueError:
        return False

def parse_slack_output(slack_rtm_output):
    """
        The Slack Real Time Messaging API is an events firehose.
        this parsing function returns None unless a message is
        directed at the Bot, based on its ID.
    """
    output_list = slack_rtm_output
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and AT_BOT in output['text']:
                # return text after the @ mention, whitespace removed
                return output['text'].split(AT_BOT)[1].strip().lower(), \
                       output['channel'], output['user']
    return None, None, None

def keyword_check(input_val, list_num ):
    """
        Generalized keyword search from a string list, given certain
        list inputs
    """
    for keyword in keyword_lists[list_num]:
        if input_val == keyword :
            return True
    return False

def person_find(first_name, last_name, users_list):
    """
        check if a person's name is in the users list
    """
    if last_name != "":
        for member in users_list['members']:
            if member['is_bot'] == False:
                if first_name == member['profile']['first_name'].lower():
                    if last_name == member['profile']['last_name'].lower():
                        return True, member['id'], member['profile']['last_name']
    for member in users_list['members']:
        if member['is_bot'] == False:
            if first_name == member['profile']['first_name'].lower():
                return True, member['id'], member['profile']['last_name']
    return False, None, None

def involvment_check(test_list, sending_user, users_list):
    """
        finds all users involved witha command from their name to the original
        sender
    """
    involved_list = list()
    for index, name in enumerate(test_list):
        if not isinstance(name, list):
            if keyword_check(name, SELF_TARGET_DEF):
                involved_list.append(['you',sending_user])
            else:
                last_name = ""
                if len(test_list) > index + 1:
                    last_name = test_list[index + 1]
                success, user_id, last_name = person_find(name,last_name, users_list)
                if success:
                    involved_list.append([name + " " + last_name, user_id])
    if not involved_list:
        involved_list.append(['you',sending_user])
    return involved_list

def find_action(test_list):
    """
        figures out what is the main command being sent
    """
    action_list = list()
    for index, word in enumerate(test_list):
        if not isinstance(word, list):
            if keyword_check(word, LEAVING_DEF) or keyword_check(word, ARRIVING_DEF):
                action_list.append([index,'sch'])
            #more to be added
            #TODO:setup other commands here and determine strength of each
    if not action_list:
        return None, None
    return 'sch', action_list[0][0]

def edit_time(test_list):
    """
        reorganizes the time slots to be readable by dateparser
    """
    month = ""
    num_list = list()
    date_list = list()
    min_one_date = False
    print(test_list)
    i = 0
    #iterate throughout the entire list
    while i < len(test_list):
        if 'a' == test_list[i]:
            test_list.pop(i)
        #splits up - into two seperate values
        if '-' in test_list[i] and '-' != test_list[i]:
            test_list.insert(i + 1, test_list[i].split("-")[1])
            test_list[i] = test_list[i].split("-")[0]
        #special case with the word to fix
        if 'to' == test_list[i]:
            test_list[i] = '-'
        #month handling/cases
        if test_list[i] in keyword_lists[MONTH_DEF]:
            month = test_list.pop(i)
            for num in num_list:
                test_list[num] = month + test_list[num]
                min_one_date = True
            num_list = list()
            for date in date_list:
                test_list[date] = month + test_list[date]
                min_one_date = True
            date_list = list()
            if len(test_list) > i + 1 and test_list[i] == ',':
                test_list.pop(i+1)
        #turn 1 p.m to 1pm
        if len(test_list) > i + 1:
            for index, time_am in enumerate(keyword_lists[TIME_DEF]):
                if  test_list[i+1] == time_am and check_num(test_list[i]):
                    test_list[i] = test_list[i] + keyword_lists[GOOD_TIME_DEF][index % 2]
                    break
            #turns 1 st into 1st
            for additive in keyword_lists[DATE_DEF]:
                if test_list[i+1] == additive and check_num(test_list[i]):
                    test_list[i] = test_list[i] + test_list.pop(i+1)
                    break
        #splits between month and date
        if test_list[i] in keyword_lists[SPLIT_DEF] and min_one_date == True:
            month = ""
            if test_list[i] == ',':
                test_list[i] = ' '
        #date for the num/num format
        elif "/" in test_list[i]:
            min_one_date = True
            month = MONTHS[int(test_list[i].split('/')[0])]
            test_list[i] = month + test_list[i].split('/')[1]
            for num in num_list:
                test_list[num] = month + test_list[num]
            num_list = list()
            for date in date_list:
                test_list[date] = month + test_list[date]
            date_list = list()
        elif check_num(test_list[i]):
            if month == "":
                num_list.append(i)
            else:
                test_list[i] = month + test_list[i]
        #checks for if the listed node is a date
        for date in keyword_lists[DATE_DEF]:
            if date in test_list[i] and check_num(test_list[i].split(date)[0]):
                if month != "":
                    test_list[i] = month + test_list[i]
                    min_one_date = True
                    break
                else:
                    date_list.append(i)
        for time in keyword_lists[GOOD_TIME_DEF]:
            if time in test_list[i]:
                for num in num_list:
                    test_list[num] = test_list + time;
                num_list = list()
        i = i + 1
    if len(num_list) != 0:
        for num in num_list:
            test_list[num] = test_list[num] + "pm"
    return test_list

def parse_text(slack_rtm_output, users_list):
    """
        Used to determine when the bot is targeted as well as figure
        out what the message wants.
    """
    garenteed_text, channel, sending_user = parse_slack_output(slack_rtm_output)
    if garenteed_text and channel:
        #makes a list out of the string
        test_list = nltk.word_tokenize(garenteed_text.lower())

        action, action_place = find_action(test_list)
        if action == None:
            return "no command", None, channel, sending_user, False
        elif action == 'sch':
            involved_list = involvment_check(test_list[:action_place], sending_user, users_list)
            edited_time_list= edit_time(test_list[action_place:])
            print(involved_list)
            print("action:  " + action)
            print(edited_time_list)
    return "no command", None, channel, sending_user, False


# from OrangeHRM_Common.Excel_utility import Excel_utilities
# from selenium import webdriver
# from PageObjects.OrangeHRM_LoginPages.Login_Page import LoginPages
# from PageObjects.OrangeHRM_HomePags.HomePage import HomePages
from Functionality_Cases.User_Management_utility import User_management_utility
# from Utils import Utils as utils
import pytest
from OrangeHRM_Common.OrangeHRM_ExceptionHandling import ExceptionUtility
from OrangeHRM_Common.OrangeHRM_ReportUtilities.LogGenerator import logger_obj
import os

@ pytest.mark.usefixtures("test_setup")
class TestUserManagement:

    # path = "E:\\HRM-OrangeHRM\\OrangeHRM_Common\\OrangeHRM_input_Sheet.xlsx"
    # sheet_Inputs = "Inputs"
    # url = Excel_utilities.getvalue(path,sheet_Inputs,"application_url")

    # @pytest.fixture(scope="class")
    # def test_setup(self):
    #     print("setup called")
    #     global driver
    #     driver = webdriver.Chrome(executable_path="E:\\OrangeHRMProject\\Driver_Directory\\chromedriver.exe")
    #     driver.maximize_window()
    #     driver.implicitly_wait(10)
    #     driver.get("https://opensource-demo.orangehrmlive.com/")
    #     login = LoginPages(driver)
    #     login.enter_username("Admin")
    #     login.enter_password("admin123")
    #     login.click_login()
    #     yield
    #     print("teardown called")
    #     homepage = HomePages(driver)
    #     homepage.click_welcome()
    #     homepage.click_logout()
    #     driver.close()

    def test_click_users(self):
        try:
            logger_obj.info("test_click_users called")
            driver = self.driver
            user_mgmt = User_management_utility(driver)
            user_mgmt.navigate_Users()
            user_mgmt.Collapse_System_users_Tab()

            users_list = user_mgmt.get_list_Users()
            print(users_list)
            print("User to Delete :",users_list[1])
            user_mgmt.select_user(users_list[1])
            #user_mgmt.delete_user(users_list[1],"Y")
            #self.assertFalse(user_mgmt.select_user(users_list[1]) == False, users_list[2] + " failed to delete")
        except Exception as e:
            logger_obj.exception("File Name : {current_py_file_name} ".format(current_py_file_name=os.path.basename(__file__)), exc_info=False)
            logger_obj.exception("Error : ", exc_info=False)
            logger_obj.exception("Type --> " + type(e).__name__, exc_info=False)
            logger_obj.exception("Details --> " + str(e), exc_info=False)
            ExceptionUtility.call_exception_utility(exit_code=1)


#!/usr/bin/python3
import math

filelist = '../data/scannet/seg/train_files.txt'
filelist_val = '../data/scannet/seg/test_files.txt'

num_class = 21

sample_num = 2048

max_point_num = 8192

batch_size = 16

num_epochs = 200

label_weights = [0.0] * 1 + [1.0] * (num_class - 1)

learning_rate_base = 0.005
decay_steps = 5000
step_val = 500
decay_rate = 0.8
learning_rate_min = 1e-6

weight_decay = 1e-8

jitter = 0.001
jitter_val = 0.0

sample_num_variance = 1 // 8
sample_num_clip = 1 // 4

rotation_range = [0, math.pi/32., 0, 'u']
rotation_range_val = [0, 0, 0, 'u']
rotation_order = 'rxyz'

scaling_range = [0.001, 0.001, 0.001, 'g']
scaling_range_val = [0, 0, 0, 'u']

ss = 8  # shell size (number of points contained in each shell)
sconv_param_name = ('K', 'D', 'P', 'C')
sconv_params = [dict(zip(sconv_param_name, sconv_param)) for sconv_param in
                [
                 (ss*4, 4, 512, 128),
                 (ss*2, 2, 128, 256),
                 (ss*1, 1, 32, 512)]]

sdconv_param_name = ('K', 'D', 'pts_layer_idx', 'qrs_layer_idx')
sdconv_params = [dict(zip(sdconv_param_name, sdconv_param)) for sdconv_param in
                [
                (ss*1,  1, 2, 1),
                (ss*2,  2, 1, 0),
                (ss*4,  4, 0, -1)]]

x=1
fc_param_name = ('C', 'dropout_rate')
fc_params = [dict(zip(fc_param_name, fc_param)) for fc_param in
            [(128 * x, 0.0),
            (64 * x, 0.2)]]

sampling = 'fps' # 'fps' or 'random'

optimizer = 'adam'

data_dim = 3


from pico2d import *

class Grass:
    PIXEL_PER_KMETER = (10.0 / 0.5)  # 10 pixel 0.5km
    RUN_SPEED_KMPH = 36000.0  # 180000km per hour
    RUN_SPEED_KMPM = RUN_SPEED_KMPH / 60  # 3000km per min
    RUN_SPEED_KMPS = RUN_SPEED_KMPM / 60  # 50km per sec
    RUN_SPEED_PPS = RUN_SPEED_KMPS * PIXEL_PER_KMETER

    def __init__(self,w,h):
        self.image=load_image('grass.png')
        self.speed = 0
        self.width = 0
        self.screen_width = w
        self.screen_height = h

    def exit(self):
        del(self.image)

    def draw(self):
        x = int(self.width)
        w = min(self.image.w - x, self.screen_width)
        self.image.clip_draw_to_origin(x, 0, w, self.screen_height, 0, 0)
        self.image.clip_draw_to_origin(0, 0, self.screen_width - w, self.screen_height, w, 0)
        # clip_draw_to_origin(self, left, botton, width, height, x, y, w, h)

    def update(self, frame_time):
        self.speed = Grass.RUN_SPEED_PPS
        self.width = (self.width + frame_time * self.speed) % self.image.w


#!/usr/bin/env python
import cv2
#import cv2.cv as cv
import numpy as np
#from cv2 import *

image_path="plate6.png"
carsample=cv2.imread(image_path)

# convert into grayscale
gray_carsample=cv2.cvtColor(carsample, cv2.COLOR_BGR2GRAY)

# blur the image
blur=cv2.GaussianBlur(gray_carsample,(5,5),0)

# find the sobel gradient. use the kernel size to be 3
sobelx=cv2.Sobel(blur, cv2.CV_8U, 1, 0, ksize=3)

#Otsu thresholding
_,th2=cv2.threshold(sobelx, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

#Morphological Closing
se=cv2.getStructuringElement(cv2.MORPH_RECT,(23,2))
closing=cv2.morphologyEx(th2, cv2.MORPH_CLOSE, se)

contours,_=cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for cnt in contours:
    rect=cv2.minAreaRect(cnt)
    box=cv2.cv.BoxPoints(rect)
    box=np.int0(box)
    cv2.drawContours(carsample, [box], 0, (0,255,0),2)

#validate a contour. We validate by estimating a rough area and aspect ratio check.
def validate(cnt):
    rect=cv2.minAreaRect(cnt)
    box=cv2.cv.BoxPoints(rect)
    box=np.int0(box)
    output=False
    width=rect[1][0]
    height=rect[1][1]
    if ((width!=0) & (height!=0)):
        if (((height/width>3) & (height>width)) | ((width/height>3) & (width>height))):
            if ((height*width<16000) & (height*width>3000)):
                output=True
    return output
#Lets draw validated contours with red.
for cnt in contours:
    if validate(cnt):
        rect=cv2.minAreaRect(cnt)
        box=cv2.cv.BoxPoints(rect)
        box=np.int0(box)
        cv2.drawContours(carsample, [box], 0, (0,0,255),2)

# defining a function doing this will come handy.
def generate_seeds(centre, width, height):
    minsize=int(min(width, height))
    seed=[None]*10
    for i in range(10):
        random_integer1=np.random.randint(1000)
        random_integer2=np.random.randint(1000)
        seed[i]=(centre[0]+random_integer1%int(minsize/2)-int(minsize/2),centre[1]+random_integer2%int(minsize/2)-int(minsize/2))
    return seed

#masks are nothing but those floodfilled images per seed.
def generate_mask(image, seed_point):
    h=carsample.shape[0]
    w=carsample.shape[1]
    #OpenCV wants its mask to be exactly two pixels greater than the source image.
    mask=np.zeros((h+2, w+2), np.uint8)
    #We choose a color difference of (50,50,50). Thats a guess from my side.
    lodiff=50
    updiff=50
    connectivity=4
    newmaskval=255
    flags=connectivity+(newmaskval<<8)+cv2.cv.CV_FLOODFILL_FIXED_RANGE+cv2.cv.CV_FLOODFILL_MASK_ONLY
    _=cv2.floodFill(image, mask, seed_point, (255, 0, 0),
                    (lodiff, lodiff, lodiff), (updiff, updiff, updiff), flags)
    return mask

# we will need a fresh copy of the image so as to draw masks.
carsample_mask=cv2.imread(image_path)

# for viewing the different masks later
mask_list=[]

for cnt in contours:
    if validate(cnt):
        rect=cv2.minAreaRect(cnt)
        centre=(int(rect[0][0]), int(rect[0][1]))
        width=rect[1][0]
        height=rect[1][1]
        seeds=generate_seeds(centre, width, height)

        #now for each seed, we generate a mask
        for seed in seeds:
            # plot a tiny circle at the present seed.
            cv2.circle(carsample, seed, 1, (0,0,255), -1)
            # generate mask corresponding to the current seed.
            mask=generate_mask(carsample_mask, seed)
            mask_list.append(mask)

cv2.imwrite('gray.jpg',gray_carsample)
cv2.imwrite('blur.jpg',blur)
cv2.imwrite('sobelx.jpg',sobelx)
cv2.imwrite('thresholding.jpg',th2)
cv2.imwrite('contours.jpg', carsample)
cv2.imwrite('test2.jpg',mask_list[2])
cv2.imwrite('test3.jpg',mask_list[3])
cv2.imwrite('test4.jpg',mask_list[4])
cv2.imwrite('test5.jpg',mask_list[5])
cv2.imwrite('test6.jpg',mask_list[6])
cv2.imwrite('test7.jpg',mask_list[7])
cv2.imwrite('test8.jpg',mask_list[8])
cv2.imwrite('test9.jpg',mask_list[9])


import discord
from discord.ext import commands
import psycopg2.extensions as sql
from typing import Iterable
from utils.sql_fetcher import SqlFetcher
from utils.utils import decode_mention

class CourseMentions:
	def __init__(
		self, conn: sql.connection, sql_fetcher: SqlFetcher, bot: commands.Bot
	) -> None:
		self.conn = conn
		self.sql_fetcher = sql_fetcher
		self.bot = bot

	def get_channel_full_name(self, channel: str) -> str:
		"""Searches the database for the course name given the channel id"""
		query = self.sql_fetcher["search_category_name.sql"]
		with self.conn as conn:
			with conn.cursor() as cursor:
				cursor.execute(query, {"channel": channel})
				row = cursor.fetchone()
		if row is not None:
			# return full matched category name from database
			return row[0]
		else:
			# return the channel name instead
			ch = self.bot.get_channel(int(channel))
			return ch.name if ch is not None else None

	def map_channel_mention(self, word: str):
		"""given a word in a string, return the channel name
		if it is a channel mention, otherwise return the original word"""
		mention_type, channel_id = decode_mention(word)
		# convert mention to full name if word is a mention
		if mention_type == "channel":
			return self.get_channel_full_name(channel_id)
		# not a channel mention
		return word

	def replace_channel_mentions(self, text: str):
		return " ".join(
			map(
				self.map_channel_mention,
				text.replace("<", " <").replace(">", "> ").split(),
			)
		)


empty_board = [['-', '-', '-'],
               ['-', '-', '-'],
               ['-', '-', '-']]
board_is_empty = True
turn = 'X'

def display_board(board):
    for i in range(len(board)):
        for j in range(len(board[0])):
            if j == 1 or j == 2:
                print(' | ', end='')
            print(board[i][j], end='')
        print()

def check_board(board, pos):
    #It checks the winner
    #check row
    pos_row = board[pos[0]]
    if ['X', 'X', 'X'] == pos_row or ['O', 'O', 'O'] == pos_row:
        return True

    #check col
    pos_col = [board[0][pos[1]], board[1][pos[1]], board[2][pos[1]]]
    if ['X', 'X', 'X'] == pos_col or ['O', 'O', 'O'] == pos_col:
        return True

    #check diagonal
    diagnol_positions = [(0, 0), (1, 1), (2, 2), (2, 0), (0, 2)]
    diagnol_1 = [board[0][0], board[1][1], board[2][2]]
    diagnol_2 = [board[2][0], board[1][1], board[0][2]]

    if pos in diagnol_positions:
        if ['X', 'X', 'X'] == diagnol_1 or ['O', 'O', 'O'] == diagnol_1:
            return True
    if pos in diagnol_2:
        if ['X', 'X', 'X'] == diagnol_2 or ['O', 'O', 'O'] == diagnol_2:
            return True

    return None

def check_tie(board):
    if '-' not in board[0] and '-' not in board[1] and '-' not in board[2]:
        return True

# choosing the position
def move():
    move_row = input(f'Choose a row(1, 2, 3) player {turn}: ')
    move_row = int(move_row) - 1
    move_col = input(f'Choose a col(1, 2, 3) player {turn}: ')
    move_col = int(move_col) - 1
    return (move_row, move_col)

def move_validation(board, move):
    if board[move[0]][move[1]] == '-':
        return True
    return False

def flip_turn(turn):
    if turn == 'X':
        return 'O'
    else:
        return 'X'

def play_game(board):
    global board_is_empty
    global turn
    display_board(board)
    #checking for intial turn or fliping the turn
    if board_is_empty:
        turn = 'X'
        board_is_empty = False
    else:
        turn = flip_turn(turn)
    # looping unless correct move is played
    while True:
        row, col = move()
        if move_validation(board, (row, col)):
            break
    # setting move played
    board[row][col] = turn
    # checking for tie
    if check_tie(board):
        display_board(board)
        print("It's a tie")
        return True
    #checking for win
    if check_board(board, (row, col)):
        display_board(board)
        print(f"{turn} won !!")
        return True
    else:
        # recursively calling the function until the end of game
        play_game(board)

play_game(empty_board)


import  itchat
#微信自动登录
itchat.auto_login(hotReload=True)
#获取微信好友的列表
friends = itchat.get_friends()
#print(friends)
for friend in friends:
    print(friend)
    print(friend['RemarkName'])
    # print(friend['Sex'])获取朋友信息表里的性别信息
    头像 = itchat.get_head_img(userName=friend['UserName'])
    path = "F:\program\微信\头像\\"
    filepath = path + friend['RemarkName'] + ".jpg"
    with open(filepath,'wb') as f:
        f.write(头像)


#!/usr/bin/python
import numpy as np

def count_male_female(data):
	'''
	Returns a tuple with (males, females)
	'''
	females=data[:,0].sum()
	males=data.shape[0]-females
	return (males, females)

def get_values(data, colomn, gender=-1):
	'''
	Returns the values by colomn and gender
	COLOMNS:
		1=Age
		2=Heart Rate
		3=Temperature
	GENDERS:
		-1 = BOTH
		0 = MALE
		1 = FEMALE
	'''
	if gender==-1 :
		return data[:,colomn]
	else :
		temp=data[:,colomn]
		mask=data[:,0]==gender
		return temp[mask]

def write_statistics(data):
	channel=open("BD_results.txt", "w")
	channel.write("Gender\t\tAge\t\tHeartR\tTemp\n")
	all_age=get_values(data, 1)
	all_heart=get_values(data, 2)
	all_temp=get_values(data, 3)
	male_age=get_values(data, 1)
	male_heart=get_values(data, 2)
	male_temp=get_values(data, 3)
	female_age=get_values(data, 1)
	female_heart=get_values(data, 2)
	female_temp=get_values(data, 3)
	channel.write("ALL MEAN\t%.2f\t%.2f\t%.2f\n" % (all_age.mean(), all_heart.mean(), all_temp.mean()))
	channel.write("ALL MIN \t%.2f\t%.2f\t%.2f\n" % (all_age.min(), all_heart.min(), all_temp.min()))
	channel.write("ALL MAX \t%.2f\t%.2f\t%.2f\n" % (all_age.max(), all_heart.max(), all_temp.max()))
	channel.write("MALE MEAN\t%.2f\t%.2f\t%.2f\n" % (male_age.mean(), male_heart.mean(), male_temp.mean()))
	channel.write("MALE MIN\t%.2f\t%.2f\t%.2f\n" % (male_age.min(), male_heart.min(), male_temp.min()))
	channel.write("MALE MAX\t%.2f\t%.2f\t%.2f\n" % (male_age.max(), male_heart.max(), male_temp.max()))
	channel.write("FEMALE MEAN\t%.2f\t%.2f\t%.2f\n" % (female_age.mean(), female_heart.mean(), female_temp.mean()))
	channel.write("FEMALE MIN\t%.2f\t%.2f\t%.2f\n" % (female_age.min(), female_heart.min(), female_temp.min()))
	channel.write("FEMALE MAX\t%.2f\t%.2f\t%.2f\n" % (female_age.max(), female_heart.max(), female_temp.max()))

	channel.close()

def get_data():
	return np.genfromtxt("BodyTemperature_nohead.txt")


import sys
file_name = sys.argv[1]
text = []

try:
    fh = open(file_name,'r')
except IOError:
    print(f'No such file or directory: "{file_name}"')
else:
    text = fh.readlines()
    fh.close()

if text:
    print(text[:100])


import tensorflow as tf
from tensorflow.keras import layers
from ml4ir.applications.ranking.config.keys import PositionalBiasHandler
from tensorflow.keras import regularizers

class FixedAdditivePositionalBias(layers.Layer):
    """
    This class implements a solution to handle positional bias in logged data.
    During training, a bias term is learned for each rank and is added to the relevance score of each query-document
    pair depending on its rank.
    The process of adding the positional bias is only applied during training because this is a way to de-bias data
    from logs (typically clicked/no clicked pairs). During inference we do not know the actual ranks, so the addition
    is turned off.
    This is an approach we have found useful for logged data as these are presented to the user with some order and
    there is a presentation bias (that this technique tries to model).
    When the data is labeled with actual graded relevance annotations then this technique is not recommended.

    To trigger this technique add this section to the model_config.yaml file:

    positional_bias_handler:
        key: fixed_additive_positional_bias
        max_ranks_count: x

    Where x is the maximum number of documents per query.
    """
    def __init__(self, max_ranks, kernel_initializer='Zeros', l1_coeff=0, l2_coeff=0):
        super(FixedAdditivePositionalBias, self).__init__()
        self.dense = layers.Dense(1,
                                  name=PositionalBiasHandler.FIXED_ADDITIVE_POSITIONAL_BIAS,
                                  kernel_initializer=kernel_initializer,
                                  kernel_regularizer=regularizers.l1_l2(l1=l1_coeff, l2=l2_coeff),
                                  activation=None,
                                  use_bias=False)
        self.max_ranks = max_ranks

    def call(self, inputs, training=False):
        """
        Invoke the positional bias handling

        Parameters
        ----------
        input : Tensor object
            rank index tensor
        training : bool
            If the layer should be run as training or not

        Returns
        -------
        Tensor object
            positional biases resulting from a feedforwrd of the converted one hot tensor through a dense layer.
        """
        features = tf.one_hot(tf.cast(tf.subtract(inputs, 1), dtype=tf.int64), depth=self.max_ranks,
                              dtype=tf.dtypes.float32)
        if not training:
            features = tf.multiply(features, 0.0)
        return self.dense(features)


##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: speedinghzl02
## updated by: RainbowSecret
## Microsoft Research
## yuyua@microsoft.com
## Copyright (c) 2018
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

import torch.nn as nn
from torch.nn import functional as F
import math
import torch.utils.model_zoo as model_zoo
import torch
import os
import sys
import numpy as np
from torch.autograd import Variable
import functools
import torchvision.models as mo
res18=mo.resnet18()
affine_par = True

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
sys.path.append(os.path.join(BASE_DIR, '../utils'))
# sys.path.append('/inplace_abn')
from utils.resnet_block import conv3x3, Bottleneck,BasicBlock
from utils.psp_block import PSPModule
from utils.modules import InPlaceABN, InPlaceABNSync
BatchNorm2d = functools.partial(InPlaceABNSync, activation='none')

class Net(nn.Module):
    def __init__(self,student, teacher, criterion_l,criterion_s,criterion_k,args):
        super(Net, self).__init__()
        self.student = student
        self.teacher = teacher
        self.criterion_l = criterion_l
        self.criterion_k = criterion_k
        self.criterion_s = criterion_s
        self.args = args

    def inference(self,image,upsample):
        self.student.eval()
        _, _, w, h = image.size()
        preds = self.student(image)
        if upsample:
            scale_pred = F.upsample(input=preds[0], size=(w, h), mode='bilinear', align_corners=True)
        else:
            scale_pred = preds[0]
        return scale_pred

    def cal_loss(self,s_image,t_image,label):

        preds = self.student(s_image)
        with torch.no_grad():
            soft = self.teacher(t_image)
        loss = 0
        loss_k = 0
        loss_l = 0
        loss_s = 0
        if 'label' in self.args.sd_mode:
            loss_l = self.args.weight_l * self.criterion_l(preds, label)
            loss = loss + loss_l

        if 'kd' in self.args.sd_mode:
            loss_k = self.args.weight_k * self.criterion_k(preds, soft)

            loss = loss + loss_k
        if 'sd' in self.args.sd_mode:
            loss_s = self.args.weight_s * self.criterion_s(preds, soft)
            loss = loss + loss_s
        return loss

    def forward(self,s_image,t_image,label,upsample,mode):
        if mode =='train':
            ret = self.cal_loss(s_image,t_image,label)
        elif mode == 'test':
            ret = self. inference(s_image,upsample)

        return ret


import tensorflow as tf
import keras
from keras import Sequential, Model
from tensorflow.python.keras.backend import set_session
from imageio import imread, imsave
from waitress import serve
from src.utils import *
from flask import Flask, send_from_directory, render_template, request, abort
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
app = Flask(__name__, static_url_path="/static")
tf.keras.backend.clear_session()
'''
to run flask app in development mode from terminal:
export FLASK_ENV=development
to init deploy:
env FLASK_APP=app.py flask run
'''

# letter labels from val_generator
key_dict = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4,
            'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9,
            'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14,
            'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19,
            'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24,
            'Z': 25}

model = load_saved_model('cnn_scratch_model.h5')
graph = tf.get_default_graph()
sess = keras.backend.get_session()
init = tf.global_variables_initializer()
sess.run(init)

@app.route("/")
def index():
    """Return the main page."""
    return send_from_directory("static", "index.html")

@app.route("/get_results", methods=["POST"])
def get_results():
    """ Predict the letter signed in input image """
    # access form submission
    data = request.form
    # load model
    # grab image and preprocess for model
    filename = data['image_name']
    true_label = data['image_true_label']
    global graph
    global sess
    with graph.as_default():
        set_session(sess)
        image = predict_custom_image(
            unet, imread(f'static/test_images/{filename}'))
        # classify image and attach letter label
        prediction_index = predict_on(model, image)
        letter_predict = list(key_dict.keys())[list(
            key_dict.values()).index(prediction_index)]
        # print to results.html
        return render_template("results.html", predicted_class=letter_predict, file_name=filename, true_label=true_label)

if __name__ == "__main__":
    serve(app, host='0.0.0.0', port=5000)


import tensorflow as tf
import csv
import os
import numpy as np

truth_data = []
train_data = []
test_data = []
mnist_train = []
mnist_test = []
batch = 100
epoch = 1000
batch_pointer = 0
train_read_pointer = 0

def weight_variable(shape):
	initial = tf.truncated_normal(shape=shape, stddev=0.1)
	return tf.Variable(initial)

def conv2d(x, W):
	return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = 'SAME')

def max_pool_2x2(x):
	return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

def bias_variable(shape):
	initial = tf.constant(0.1, shape = shape)
	return tf.Variable(initial, name = "bias")

def get_a_train_data(a_sample):
	a_sample_int = list(map(int, a_sample))
	return a_sample_int[1:]

def get_a_truth_data(a_sample):
	temp = [0 for i in range(0,10)]
	a_sample_int = list(map(int,a_sample))
	temp[a_sample_int[0]] = 1
	return temp

def get_mnist_data_set(mnist_train_name, mnist_test_name):
	with open(mnist_train_name, "r", newline='') as train_file:
		reader = csv.reader(train_file)
		_train_data = list(reader)

	with open(mnist_test_name, "r", newline='') as test_file:
		reader = csv.reader(test_file)
		_test_data = list(reader)

	return _train_data[1:], _test_data[1:]

def get_test_data(test_data, size):
	_batch_xs = []
	_batch_ys = []
	n_data = size
	read_pointer = 0
	print ("test data size %d" %n_data)
	for i in range(0, n_data):
		row = test_data[read_pointer]
		_batch_xs.append(get_a_train_data(row))
		_batch_ys.append(get_a_truth_data(row))
		read_pointer = (read_pointer + 1) % n_data

	return _batch_xs,_batch_ys

def get_next_train_batch(train_data, _batch):
	global train_read_pointer
	_batch_xs = []
	_batch_ys = []
	n_data = len(train_data)
	for i in range(0, _batch):
		row = train_data[train_read_pointer]
		_batch_xs.append(get_a_train_data(row))
		_batch_ys.append(get_a_truth_data(row))
		train_read_pointer = (train_read_pointer + 1) % n_data

	return _batch_xs,_batch_ys

def get_batch_next(__batch):
	global batch_pointer
	__batch_ys = []
	__batch_xs = [list(map(int, i)) for i in train_data[batch_pointer: batch_pointer + __batch]]
	answers = list(map(int,truth_data[batch_pointer: batch_pointer + __batch]))
	for x in answers:
		temp = [0,0,0,0,0,0,0,0,0,0]
		temp[x] = 1
		__batch_ys.append(temp)
	batch_pointer  += __batch
	assert batch_pointer < len(train_data), "get batch overflow"
	return __batch_xs, __batch_ys

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={input_data_ts: v_xs, truth_data_ts:v_ys, keep_prob:1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={input_data_ts: v_xs, truth_data_ts: v_ys})
    return result

def write_data2csv(file_name, x):
	if os.path.isfile(file_name):
		print("%s is exist" % file_name)
		csvfile = open(file_name, "a")
		first_write = False
	else:
		print("%s is not exist" % file_name)
		csvfile = open(file_name, "w")
		first_write = True

	batch = len(x)
	n_pixels = len(x[0])
	field_name = ["pixel%i" %i for i in range(0,n_pixels)]
	writer = csv.writer(csvfile)
	if first_write == True:
		writer.writerow(field_name)

	for s in range(0,batch):
		writer.writerow(x[s])
	csvfile.close()
	return

train_data, test_data = get_mnist_data_set("train.csv", "train.csv")

print("the number of truth data: %s" % str(len(truth_data)))
print("the number of trained samples: %s" % str(len(train_data)))
print("the number of pixels: %s" % str(len(train_data[0])))

input_data_ts = tf.placeholder(tf.float32, [None, 784], name="xs_input")/255.
truth_data_ts = tf.placeholder(tf.float32, [None, 10], name="ys_input")
keep_prob = tf.placeholder(tf.float32)
raw_data = tf.reshape(input_data_ts, [-1,28,28,1])

##conv1 layer##
with tf.name_scope("CONV1"):
	kernel1 = weight_variable([5,5,1,32])
	b_conv1 = bias_variable([32])
	f_conv1 = tf.nn.relu(conv2d(raw_data,kernel1) + b_conv1) #out: 28*28*32
	f_pool1 = max_pool_2x2(f_conv1) # out:14*14*32
	tf.summary.histogram(name = "conv1/k1", values =kernel1)

##conv2 layer
with tf.name_scope("CONV2"):
	kernel2 = weight_variable([5,5,32,64])
	b_conv2 = bias_variable([64])
	f_conv2 = tf.nn.relu(conv2d(f_pool1,kernel2) + b_conv2) #out: 14*14*64
	f_pool2 = max_pool_2x2(f_conv2) #7*7*64
	#tf.summary.histogram(name = "conv1/k2", values = kernel2)

with tf.name_scope("FC1"):
	## fc1 layer ##
	W_fc1 = weight_variable([7*7*64, 1024])
	b_fc1 = bias_variable([1024])
	h_pool2_flat = tf.reshape(f_pool2, [-1, 7*7*64])
	h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
	h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
	#tf.summary.histogram(name = "fc1/fc1", values = h_fc1)

with tf.name_scope("FC2"):
	## fc2 layer ##
	W_fc2 = weight_variable([1024, 10])
	b_fc2 = bias_variable([10])
	prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
	#tf.summary.histogram(name = "fc2/fc2", values = prediction)

#loss function
with tf.name_scope("cross_entropy"):
	cross_entropy = tf.reduce_mean(-tf.reduce_sum(truth_data_ts * tf.log(prediction),
                                              reduction_indices=[1]))       # loss
	train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

sess = tf.Session()
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
	init = tf.initialize_all_variables()
else:
	init = tf.global_variables_initializer()

tf.global_variables_initializer()
sess.run(init)

test_x,test_y = get_test_data(test_data, 100)

if os.path.isfile("batch_xs.csv")==True:
	os.remove("batch_xs.csv")
if os.path.isfile("batch_ys.csv")==True:
	os.remove("batch_ys.csv")
if os.path.isfile("test_pixel.csv")==True:
	os.remove("test_pixel.csv")
if os.path.isfile("test_label.csv")==True:
	os.remove("test_label.csv")

write_data2csv("test_pixel.csv",test_x)
write_data2csv("test_label.csv",test_y)
merged=tf.summary.merge_all()
writer = tf.summary.FileWriter("logs/train", graph=sess.graph)

for i in range (epoch):
	batch_xs, batch_ys = get_next_train_batch(train_data, batch)
#	write_data2csv("batch_xs.csv",batch_xs)
#	write_data2csv("batch_ys.csv",batch_ys)
	xs_np = np.array(batch_xs)
	ys_np = np.array(batch_ys)
	xs_np = np.multiply(xs_np, 1.0 / 255.0)
	sess.run(train_step, feed_dict= {input_data_ts: xs_np, truth_data_ts:ys_np, keep_prob:0.5})
	if(i % 50 == 0):
		result = sess.run(merged, feed_dict= {input_data_ts: xs_np, truth_data_ts:ys_np, keep_prob:0.5})
		print ("epch %d" % i)
		test_xs_np = np.array(test_x)
		test_ys_np = np.array(test_y)
		print(compute_accuracy(test_xs_np, test_ys_np))
		writer.add_summary(result, i)


import time
import sys
import os

start_time = time.time()

if len(sys.argv) < 4:
    print ("uso: python " + sys.argv[0] + " <arquivo_de_aceesos_ao_sistema> " + "<arquivo_de_usuarios_do_sistema> " + "<arquivo_de_relatorio>")
    sys.exit()

'''cria as listas e arquivos de trabalho'''
arquivo1 = sys.argv[1]
arquivo2 = sys.argv[2]
outfile = sys.argv[3]

try:
    os.remove(outfile)
except OSError:
    pass

f_arquivo1 = open(arquivo1)
f_arquivo2 = open(arquivo2)
f_out = open(outfile, 'w')

arquivo1_list = list()
arquivo2_list = list()
users = set()

'''le o arquivo de acessos ao icdl e coloca somente as chaves dos numa lista.'''
for line in f_arquivo1:
    if "_" in line:
        arquivo1_list.append(line.strip('\n').split(";")[1].split("_")[1])

'''le o arquivo de usuarios do icdl e coloca o conteudo numa lista.'''
for line in f_arquivo2:
    arquivo2_list.append(line.strip('\n').split("_")[1].split(";"))

'''cria um set onde cada entrada eh a chave do usuario do primeiro arquivo. usado para remover duplicidades.'''
users = set(arquivo1_list)

'''gera o arquivo csv de saida. o primeiro campo eh a chave do usuario e o segundo campo eh a empresa'''
for i in users:
    for j in arquivo2_list:
        if i in j:
            f_out.write(i + ";" + j[3] + "\n")

'''fecha os arquivos de trabalho'''
f_out.close()
f_arquivo1.close()
f_arquivo1.close()

'''exibe o tempo de execucao do script'''
print("--- %s seconds ---" % (time.time() - start_time))


import cflib.crtp
import time
import numpy as np
import cv2
import time
from matplotlib import pyplot as plt
from distance_to_camera import DistanceCalculator
from controle_cachorrinho import PositioningControl
import threading
import urllib.request as urllib

from cflib.crazyflie import Crazyflie
from cflib.crazyflie.syncCrazyflie import SyncCrazyflie
from cflib.positioning.motion_commander import MotionCommander
from cflib.crazyflie.swarm import CachedCfFactory
from cflib.crazyflie.swarm import Swarm
from cflib.crazyflie.log import LogConfig

cflib.crtp.init_drivers(enable_debug_driver=False)
factory = CachedCfFactory(rw_cache='./cache')
URI3 = 'radio://0/40/2M/E7E7E7E7E4'
cf = Crazyflie(rw_cache='./cache')
sync = SyncCrazyflie(URI3, cf=cf)
sync.open_link()
mc = MotionCommander(sync)
mc.take_off()
time.sleep(3)

calculator = DistanceCalculator()

controller = PositioningControl(320,20,27,2)
cap = cv2.VideoCapture(1)
CenterLimitH = [305, 335]
cont = 0

while(cap.isOpened()):
    ret, frame = cap.read()

    if(frame is None):
        break

    if(cont%15==0):
        thread = threading.Thread(target=calculator.processImage, args=(frame, ))
        thread.setDaemon(True)
        thread.start()
        thread.join()

    if(cont%30==0):
        calculator.mediaDistance()

    calculator.writeDistance(frame)
    cv2.imshow('frame',frame)
    markerCenter = calculator.center

    if(mc.isRunning):
        mc.stop()

    if(calculator.markerFound):
        #Se o marcador não está no centro, envia comando para virar o drone
        #na direção do marcador
        if(controller.offCenter(markerCenter)):
            if(markerCenter < controller.center):
                mc.turn_left(1)
            else:
                mc.turn_right(1)

        #Se o marcador não está na distância correta, envia commando
        #para aproximar ou afasta-se
        if(controller.offDistance(calculator.distance_x)):
            if(calculator.distance_x > controller.center):
                mc.start_linear_motion(0.1, 0.0, 0.0)
            else:
                mc.start_linear_motion(-0.1, 0.0, 0.0)
        mc.setIsRunning(True)

    # if(self.alpha != 0):
    #     if (self.alpha > 10):
    #         mc.left(0.1)
    #         mc.setIsRunning(True)
    #     elif(self.alpha < 10):
    #         mc.right(0.1)
    #         mc.setIsRunning(True)

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

cv2.waitKey()
cv2.destroyAllWindows()

mc.land()
sync.close_link()


#!/usr/local/bin python3
# -*- coding: utf-8 -*-
# @Time    : 2018/8/7 11:16
# @Author  : ray lei
# @File    : 生成sip账号.py
# @Software: PyCharm

def sip_account(sip_type,first_number,total,host=None):
    gw_sip = 'gw_sip = '
    for i in range(1,1+int(total)):
        # gw_sip += f'gw_sip_{i};'
        if i < int(total):
            gw_sip += f'gw_sip_{i};'
        else:
            gw_sip += f'gw_sip_{i}'
    """ 打印到终端 """
    print(gw_sip)
    for i in range(1, 1+total):
        num = int(first_number) + i
        if host != None:
            print(f'gw_sip_{str(i)} = {sip_type};{num};{num};123456;{host};')
        else:
            print(f'gw_sip_{str(i)} = {sip_type};{num};{num};123456;;')
    """ 打印到文件中 """
    with open('web_cases.conf','w') as f:
        print('[test_sip_endpoint]',file=f)
        print(gw_sip,file=f)
        for i in range(1, 1+total):
            num = int(first_number) + i
            if host != None:
                print(f'gw_sip_{str(i)} = {sip_type};{num};{num};123456;{host};',file=f)
            else:
                print(f'gw_sip_{str(i)} = {sip_type};{num};{num};123456;;',file=f)

sip_account('server',8000,32)  # 生成server账号

# sip_account('client',8000,16,'172.16.80.133')   # 生成client账号


"""raspPinball hardware plateform"""

import logging
import asyncio
import time

from mpf.platforms.rasppinball.keypad import Keypad

from mpf.devices.driver import ConfiguredHwDriver
from mpf.core.platform import MatrixLightsPlatform, LedPlatform, SwitchPlatform, DriverPlatform
from mpf.platforms.interfaces.switch_platform_interface import SwitchPlatformInterface
from mpf.platforms.interfaces.driver_platform_interface import DriverPlatformInterface
from mpf.platforms.interfaces.rgb_led_platform_interface import RGBLEDPlatformInterface
from mpf.platforms.base_serial_communicator import BaseSerialCommunicator

from neopixel import * # ok sur raspberry
#from neopixel import neopixel #don't find it on raspberry

#class HardwarePlatform(MatrixLightsPlatform, LedPlatform, SwitchPlatform, DriverPlatform):
class HardwarePlatform(SwitchPlatform, DriverPlatform, LedPlatform):
    """Platform class for the raspPinball hardware.

    Args:
        machine: The main ``MachineController`` instance.

    """

    okey = None
    osw = None
    fake_keys = [" ", "H", "AH", "H", " ", "M", " ", "I", "J", "I", " ", "J", "I", " ", "J", "K", " ",  "N", " ", "M", "H", "H"]
    fake_idx = 0
    fake_cnt = 0

    def __init__(self, machine):
        """Initialise raspPinball platform."""
        super(HardwarePlatform, self).__init__(machine)
        self.log = logging.getLogger('RASPPINBALL')
        self.log.info("Configuring raspPinball hardware.")
        self._poll_task = None
        self.strips = dict()
        self.switches = dict()
        self.drivers = dict()
        self.leds = dict()
        #self.serial_connections = dict()
        self.communicator = None

    def __repr__(self):
        """Return string representation."""
        return '<Platform.raspPinball>'

    def initialize(self):
        """Initialise connections to raspPinball hardware."""
        self.log.info("Initialize raspPinball hardware.")

        self.config = self.machine.config['rasppinball']
        self.machine.config_validator.validate_config("rasppinball", self.config)
        print("***************************")
        print(self.config)
        #self.machine_type = (
        #    self.machine.config['hardware']['driverboards'].lower())

        self._connect_to_hardware()

        #  keypad
        self._kp = Keypad()
        self.old_key = ""
        self.key = ""
        #  leds
        self.init_strips()

    def stop(self):
        # TODO: send a stop to arduino
        pass

    def init_strips(self):
        """read strips config and init objects"""
        #!!161126:VG:init_strips
        # read only one for now...
        #self.machine.config_validator.validate_config("rasp_strip_leds", rasp_strip_leds)
        #strip_config = self.config
        #self.strip = neopixel.Adafruit_NeoPixel(
        #    strip_config['count'], strip_config['pin'], strip_config['freq'], strip_config['dma'],
        #    strip_config['invert'], strip_config['brightness'])

        self.strip = Adafruit_NeoPixel(64, 18, 800000, 5, False, 255)
        # Intialize the library (must be called once before other functions).
        self.strip.begin()
        #self.strips[strip_name] = self.strip
        self.strip.updated = False

    def fake_keypad(self):
        c = self.fake_keys[self.fake_idx]

        if c == ' ':
            max = 800
        else:
            max = 10

        self.fake_cnt += 1
        if self.fake_cnt > max:
            self.fake_cnt = 0
            self.fake_idx += 1

        try:
            c = self.fake_keys[self.fake_idx]
        except:
            c = " "
            self.fake_idx = 0

        return c

    def update_kb(self):
        s = self._kp.getKeys()
        #self.key = ""
        #s = self.fake_keypad()
        #if len(s) > 0:
        #    self.log.info(s)
        #    print("KB:", s)
        if s != self.old_key:
            #print("Keys:%s" % s)

            #   disable sw
            for num, sw in self.switches.items():
                if (num in self.old_key) and (not num in s):
                    #print ("%s OFF" % num)
                    self.machine.switch_controller.process_switch_by_num(sw.number, state=0, platform=self, logical=False)

            for num, sw in self.switches.items():
                if (not num in self.old_key) and (num in s):
                    #print ("%s ON" % num)
                    self.machine.switch_controller.process_switch_by_num(sw.number, state=1, platform=self, logical=False)

            self.old_key = s

    def tick(self, dt):
        """check with tick..."""
        del dt
        self.update_kb()

        #if self.strip.updated:
        #    self.strip.updated = False
        self.strip.show()

        #  resent frame not acked by Arduino
        self.communicator.resent_frames()

    def get_hw_switch_states(self):
        """Get initial hardware switch states."""
        hw_states = dict()
        #k = self._kp.keypad()
        k = ""
        for number, sw in self.switches.items():
            if number == k:
                hw_states[number] = 1
            else:
                hw_states[number] = 0
        return hw_states

    def _get_pulse_ms_value(self, coil):
        if coil.config['pulse_ms']:
            return coil.config['pulse_ms']
        else:
            # use mpf default_pulse_ms
            return self.machine.config['mpf']['default_pulse_ms']

    def configure_switch(self, config: dict):
        """Configure a switch.

        Args:
            config: Config dict.
        """
        #print(config)
        number = config['number']
        self.log.debug("configure_switch(%s)" % (number))
        switch = RASPSwitch(config, number)
        self.switches[number] = switch
        return switch

    #def configure_driver(self, config):
    def configure_driver(self, config: dict):
        """Configure a driver.

        Args:
            config: Config dict.
        """
        #print(config)
        number = config['number']
        self.log.debug("configure_driver(%s)" % (number))
        driver = RASPDriver(config, number, self)
        self.drivers[number] = driver
        return driver

    def configure_led(self, config, channels):
        """Subclass this method in a platform module to configure an LED.

        This method should return a reference to the LED's platform interface
        object which will be called to access the hardware.

        Args:
            channels (int): Number of channels (typically 3 for RGB).
            config (dict): Config of LED.

        """
        number = config['number']
        self.log.debug("configure_led(%s)" % number)
        #strip = self.strips[0]
        strip = self.strip
        led = RASPLed(config, number, strip)
        self.leds[number] = led
        return led

    def clear_hw_rule(self, switch, coil):
        """Clear a hardware rule.

        This is used if you want to remove the linkage between a switch and
        some driver activity. For example, if you wanted to disable your
        flippers (so that a player pushing the flipper buttons wouldn't cause
        the flippers to flip), you'd call this method with your flipper button
        as the *sw_num*.

        """
        self.log.info("clear_hw_rule(coil=%s sw=%s)" %
                       (coil.hw_driver.number, switch.hw_switch.number))
        self.communicator.rule_clear(coil.hw_driver.number, switch.hw_switch.number)

    def set_pulse_on_hit_rule(self, enable_switch, coil):
        """Set pulse on hit rule on driver.

        Pulses a driver when a switch is hit. When the switch is released the pulse continues. Typically used for
        autofire coils such as pop bumpers.
        """
        self.log.info("set_pulse_on_hit_rule(coil=%s sw=%s)" %
                       (coil.hw_driver.number, enable_switch.hw_switch.number))
        self.communicator.rule_add(1, coil.hw_driver.number, enable_switch.hw_switch.number,
                                   duration=self._get_pulse_ms_value(coil))

    def set_pulse_on_hit_and_release_rule(self, enable_switch, coil):
        """Set pulse on hit and release rule to driver.

        Pulses a driver when a switch is hit. When the switch is released the pulse is canceled. Typically used on
        the main coil for dual coil flippers without eos switch.
        """
        self.log.info("set_pulse_on_hit_and_release_rule(coil=%s sw=%s)" %
                       (coil.hw_driver.number, enable_switch.hw_switch.number))
        self.communicator.rule_add(2, coil.hw_driver.number, enable_switch.hw_switch.number,
                                   duration=self._get_pulse_ms_value(coil))

    def set_pulse_on_hit_and_enable_and_release_rule(self, enable_switch, coil):
        """Set pulse on hit and enable and relase rule on driver.

        Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released
        the pulse is canceled and the driver gets disabled. Typically used for single coil flippers.
        """
        self.log.info("set_pulse_on_hit_and_enable_and_release_rule(coil=%s sw=%s)" %
                       (coil.hw_driver.number, enable_switch.hw_switch.number))
        self.communicator.rule_add(3, coil.hw_driver.number, enable_switch.hw_switch.number,
                                   duration=self._get_pulse_ms_value(coil))

    def set_pulse_on_hit_and_enable_and_release_and_disable_rule(self, enable_switch, disable_switch, coil):
        """Set pulse on hit and enable and release and disable rule on driver.

    Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released
        the pulse is canceled and the driver gets disabled. When the second disable_switch is hit the pulse is canceled
        and the driver gets disabled. Typically used on the main coil for dual coil flippers with eos switch.
        """
        self.log.info("set_pulse_on_hit_and_enable_and_release_and_disable_rule(coil=%s sw=%s dis_sw=%s)" %
                       (coil.hw_driver.number, enable_switch.hw_switch.number, disable_switch.hw_switch.number))
        self.communicator.rule_add(4, coil.hw_driver.number, enable_switch.hw_switch.number, disable_sw_id=disable_switch.hw_switch.number,
                                   duration=self._get_pulse_ms_value(coil))

    def _connect_to_hardware(self):
        """Connect to each port from the config.

        This process will cause the connection threads to figure out which processor they've connected to
        and to register themselves.
        """
        if False:  # !!!TEMP:need to validate config...
            if len(self.config['ports']) > 1:
                self.log.fatal("only one slave com port is supported")
            if len(self.config['ports']) == 0:
                self.log.warning("no communication port setted!")
                return
            port = self.config['ports'][0]
            self.communicator = RaspSerialCommunicator(
                platform=self, port=port,
                baud=self.config['baud'])
        self.communicator = RaspSerialCommunicator(
            platform=self, port='/dev/ttyAMA0',
            baud=115200)

    def process_received_message(self, msg: str):
        """Send an incoming message from the FAST controller to the proper method for servicing.

        Args:
            msg: messaged which was received
        """
        all = msg.split(":")
        if len(all) < 2:
          self.log.warning("Recv bad formated cmd", msg)
          return
        cmd, all_param = all[:2]
        params = all_param.split(";")

        self.strip.setPixelColorRGB(0, 0, 0, 0)
        if cmd == "":
            pass
        elif cmd == "SWU":      # switch update
            sw_id = params[0]
            sw_state = int(params[1])
            self.machine.switch_controller.process_switch_by_num(sw_id, state=sw_state, platform=self, logical=False)
            self.strip.setPixelColorRGB(0, 0, 0, 0xff)  # blue
        elif cmd == "DBG":      # debug message
            self.log.debug("RECV:%s" % msg)
        elif cmd == "INF":      # debug message
            self.log.info("RECV:%s" % msg)
        elif cmd == "WRN":  # warning message
            self.log.warning("RECV:%s" % msg)
            self.strip.setPixelColorRGB(0, 0xff, 0xff, 0)  # yellow
        elif cmd == "ERR":  # warning message
            self.log.error("RECV:%s" % msg)
            self.strip.setPixelColorRGB(0, 0xff, 0, 0)  # red
        elif cmd == "TCK": # arduino is alive !
            self.log.debug("TCK ok:%d" % int(params[0]))
        elif cmd == "ACK": # ack of frame
            self.communicator.ack_frame(int(params[0]), params[1] == "OK")
            self.strip.setPixelColorRGB(0, 0, 0xff, 0)  # green
        else:
            self.log.warning("RECV:UNKNOWN FRAME: [%s]" % msg)
        l = len(self.communicator.frames)
        #TODO: self.machine['frame_cnt'] = l
        self.strip.show()
        self.machine.events.post_async('raspberry_frame_count', frame_cnt=l, frames=self.communicator.frames)

class RASPDriver(DriverPlatformInterface):

    def __init__(self, config, number, platform):
        """Initialise driver."""
        super().__init__(config, number)
        self.platform = platform
        self.log = logging.getLogger('RASPDriver')
        self.log.info("Driver Settings for %s", self.number)

    def disable(self, coil):
        """Disable the driver."""
        self.log.info("RASPDriver.Disable(%s %s)" % (coil.config['label'], coil.hw_driver.number))
        self.platform.communicator.driver_disable(coil.hw_driver.number)
        pass

    def enable(self, coil):
        """Enable this driver, which means it's held "on" indefinitely until it's explicitly disabled."""
        self.log.info("RASPDriver.Enable(%s %s)" % (coil.config['label'], coil.hw_driver.number))
        self.platform.communicator.driver_enable(coil.hw_driver.number)
        pass

    def get_board_name(self):
        """Return the name of the board of this driver."""
        pass

    def pulse(self, coil, milliseconds):
        """Pulse a driver.

        Pulse this driver for a pre-determined amount of time, after which
        this driver is turned off automatically. Note that on most platforms,
        pulse times are a max of 255ms. (Beyond that MPF will send separate
        enable() and disable() commands.

        Args:
            milliseconds: The number of ms to pulse this driver for. You should
                raise a ValueError if the value is out of range for your
                platform.

        Returns:
            A integer of the actual time this driver is going to be pulsed for.
            MPF uses this for timing in certain situations to make sure too
            many drivers aren't activated at once.

        """
        self.log.info("RASPDriver.Pulse(%s %s, %d ms)" %
                       (coil.config['label'], coil.hw_driver.number, milliseconds))
        self.platform.communicator.driver_pulse(coil.hw_driver.number, milliseconds)
        return milliseconds

class RASPSwitch(SwitchPlatformInterface):

    def __init__(self, config, number):
        """Initialise switch."""
        super().__init__(config, number)
        self.log = logging.getLogger('RASPSwitch')
        #self.notify_on_nondebounce = notify_on_nondebounce
        #self.hw_rules = {"closed_debounced": [],
        #                 "closed_nondebounced": [],
        #                 "open_debounced": [],
        #                 "open_nondebounced": []}

class RASPLed(RGBLEDPlatformInterface):

    def __init__(self, config, number, strip):
        """Initialise led."""
        self.number = number
        self.current_color = '000000'
        self.log = logging.getLogger('RASPLed')
        self.strip = strip

    def color(self, color):
        """Set the LED to the specified color.

        Args:
            color: a list of int colors. one for each channel.

        Returns:
            None
        """
        #self._color = color
        new_color = "{0}{1}{2}".format(hex(int(color[0]))[2:].zfill(2),
                                       hex(int(color[1]))[2:].zfill(2),
                                       hex(int(color[2]))[2:].zfill(2))
        #self.log.info("RASPLes.color(%s : %s -> %s)" % (self.number, color, new_color))
        #print("color(%s -> %s)" % (self.number, new_color))
        try:
            self.current_color = new_color
            #self.strip.setPixelColor(int(self.number), self.current_color)
            self.strip.setPixelColorRGB(int(self.number), color[0], color[1], color[2])

            self.strip.updated = True
        except Exception as e:
            self.log.error("led update error" + str(e))

class RaspSerialCommunicator(BaseSerialCommunicator):
    """Protocol implementation to the Arduino"""

    def __init__(self, platform, port, baud):
        """Initialise communicator. """
        self.frame_nb = 0
        self.received_msg = ''
        self.frames = {}
        super().__init__(platform, port, baud)

    def _parse_msg(self, msg):
        """Parse a message.

        Msg may be partial.
        Args:
            msg: Bytes of the message (part) received.
        """
        try:
            self.received_msg += msg.decode()
        except:
            self.log.warning("invalid parse frame '%s'" % msg)

        while True:
            pos = self.received_msg.find('\r')
            if pos == -1: # no full msg
                break
            m = self.received_msg[:pos].strip()
            if not len(m):
                break
            self.platform.process_received_message(m)
            self.received_msg = self.received_msg[pos + 1:]

    @asyncio.coroutine
    def _identify_connection(self):
        """Initialise and identify connection."""
        pass #nothing to identify...
        #raise NotImplementedError("Implement!")

    def __send_frame(self, frame_nb, msg):
        """send a frame, store id and date it"""
        if frame_nb in self.frames:
            retry  = self.frames[frame_nb]['retry'] + 1
        else:
            retry = 0
        if retry > 5:
            self.log.error('SEND:too many retry (%d) for frame "%s"' % (retry, msg))
            self.frames.pop(frame_nb)
            return
        self.frames[frame_nb] = {'msg': msg, 'time': time.time(), 'retry': retry}
        s = "!%d:%s\n" % (self.frame_nb, msg)
        self.log.info('SEND:%s' % s)
        self.send(s.encode())

    def __send_msg(self, msg):
        """send a new frame"""
        self.frame_nb += 1
        self.__send_frame(self.frame_nb, msg)

    def ack_frame(self, frame_nb, result):
        """an ack has been received, delete the accodring frame in buffer"""
        #!!170514:VG:Remove the frame only if ACK OK
        if frame_nb in self.frames:
            if not result:
                self.log.error("ACK frame error '%s'" % self.frames[frame_nb])
            else:
                self.frames.pop(frame_nb)

    def resent_frames(self):
        """resent all frame not acked after a timeout of 250ms"""
        try:
            for k,f in self.frames.items():
                if time.time() - f['time'] > 0.500:
                    self.log.warning("resend frame %d:%s" % (k, f['msg']))
                    self.__send_frame(k, f['msg'])
        except RuntimeError:
            pass  # dictionary changed size during iteration

    def rule_clear(self, coil_pin, enable_sw_id):
        msg = "RC:%s:%s" % (coil_pin, enable_sw_id)
        self.__send_msg(msg)

    def rule_add(self, hwrule_type, coil_pin, enable_sw_id='0', disable_sw_id='0', duration=10):
        msg = "RA:%d:%s:%s:%s:%d" % (hwrule_type, coil_pin, enable_sw_id, disable_sw_id, duration)
        self.__send_msg(msg)

    def driver_pulse(self, coil_pin, duration):
        #!!170418:VG:Add duration
        msg = "DP:%s:%d" % (coil_pin, duration)
        self.__send_msg(msg)

    def driver_enable(self, coil_pin):
        msg = "DE:%s" % (coil_pin)
        self.__send_msg(msg)

    def driver_disable(self, coil_pin):
        msg = "DD:%s" % (coil_pin)
        self.__send_msg(msg)


try:
    import unittest2 as unittest
except ImportError:
    import unittest
import ast
from astmonkey import transformers

class ParentNodeTransformerTest(unittest.TestCase):

    def setUp(self):
        self.transformer = transformers.ParentNodeTransformer()

    def test_module_node_parent(self):
        node = ast.parse('')

        transformed_node = self.transformer.visit(node)

        self.assertIsNone(transformed_node.parent)

    def test_non_module_node_parent(self):
        node = ast.parse('x = 1')

        transformed_node = self.transformer.visit(node)

        assign_node = transformed_node.body[0]
        self.assertEqual(transformed_node, assign_node.parent)
        self.assertEqual(assign_node.parent_field, 'body')
        self.assertEqual(assign_node.parent_field_index, 0)

    def test_expr_context_nodes_parent(self):
        node = ast.parse('x = 1\nx = 2')

        transformed_node = self.transformer.visit(node)

        ctx_node = node.body[0].targets[0].ctx
        first_name_node = node.body[0].targets[0]
        second_name_node = node.body[1].targets[0]
        self.assertIn(first_name_node, ctx_node.parents)
        self.assertIn(second_name_node, ctx_node.parents)


"""

    Description: This file is where you set and change ports,
    set collection rates, etc

"""

import os, datetime

DEBUG = True

SITE_NAME = ""
BASE_DIR = os.getcwd()
DATA_DIR = os.path.join(BASE_DIR, '../../data')

#Uncomment the sensors that you are collecting from and add
#appropriate ports ALSO!!! add to the list of active sensors

SENSORS = {

           'TEMPERATURE': [
                           [ 'NAME'     , 'temperature'],
                           [ 'FREQ', '20'], #read every 120 sec
                           [ 'PERIOD', '30'], #for 30 seconds
                           [ 'WRITE_FILE', os.path.join(DATA_DIR,'temperature')],
                           ['INITIAL_COLLECTION_TIME',datetime.datetime.utcnow()],
                          ],

              'PRESSURE': [
                            [ 'NAME'     , 'pressure'],
                            [ 'FREQ', '20'], #read every 120 sec
                            [ 'PERIOD', '30'], #for 30 seconds
                            [ 'WRITE_FILE', os.path.join(DATA_DIR,'pressure')],
                            ['INITIAL_COLLECTION_TIME',datetime.datetime.utcnow()],
                           ],

          'SOLAR_RADIATION': [
                            ['NAME', 'solar_radiation'],
                            ['FREQ', '20'],
                            ['PERIOD','30'],
                            ['WRITE_FILE',os.path.join(DATA_DIR,'solar_radiation')],
                            ['INITIAL_COLLECTION_TIME',datetime.datetime.utcnow()],
                           ]

}


# 线程池
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED, as_completed
import time

def sleep_task(sleep_time):
    print('sleep {}s'.format(sleep_time))
    time.sleep(sleep_time)
    print('end')

# max_workers工作线程
excutor = ThreadPoolExecutor(max_workers=2)
# 直接传参，不需要使用元组类型
task_1 = excutor.submit(sleep_task, 2)
task_2 = excutor.submit(sleep_task, 3)
task_3 = excutor.submit(sleep_task, 4)
# # 判断线程是否完成
# time.sleep(2.1)
# print(task_1.done())
# 取消还为进行的线程

# cancel_status = task_1.cancel()
# print(cancel_status)
# print(task_2.cancel())
# print(task_3.cancel())

# # 使用wait()方法等待线程结束  ALL_COMPLETED所有线程结束
# wait([task_1, task_2, task_3], return_when=ALL_COMPLETED)
# print('main end')

# 使用as_completed()方法判断单个线程的执行情况     还可以拿到线程的返回值
all_task = [task_1, task_2, task_3]
for task in as_completed(all_task):
    print(task)


"""
Hash Tree : 5 rows
     #
    ###
   #####
  #######
 #########
     #
"""
tree_height = input('How tall is the tree: ')
tree_height = int(tree_height)
spaces = tree_height - 1
hashes = 1
stump_spaces = tree_height - 1

# To print number of rows
while tree_height != 0:

    # To print number of spaces
    for i in range(spaces):
        print(' ', end="")

    # To print number of hashes
    for i in range(hashes):
        print('#', end="")

    # New line command for each row finished
    print()

    # Space is decremented each time
    spaces -= 1

    # Increment hashes each time with 2 (odd number 1.. 3.. 5.. 7..)
    hashes +=2

    # Decrement tree height each time to jump out of the loop
    tree_height -= 1

# Print the spaces before stump and then the hash
for i in range(stump_spaces):
    print(' ', end="")

print("#")


#!/usr/bin/env python3

import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")

import keras
from keras.applications.nasnet import preprocess_input, NASNetLarge

#from keras_applications.resnet import ResNet50, ResNet101, ResNet152
from keras.applications.resnet50 import ResNet50

from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import ReduceLROnPlateau
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
from keras.models import Model
from keras.datasets import cifar100
import numpy as np
import os

# Training parameters
batch_size = 32
epochs = 200
num_classes = 10

class KerasModel():
    '''Create, train and predict with a Keras neural network.
    '''

    def __init__(self,
                 model_spec='ResNet20',
                 include_top=True,
                 weights='imagenet',
                 input_tensor=None,
                 pooling='max',
                 classes=1000):

        self.model_spec = model
        self.include_top=include_top
        self.weights = weights
        self.input_tensor = input_tensor
        self.pooling = pooling
        self.classes = classes

        if not self.include_top:
            self.input_shape = (224, 224, 3)
        else:
            self.input_shape = None

        self.model_options = {
            'ResNet50': ResNet50,
            'ResNet101': ResNet101,
            'ResNet152': ResNet152,
            'NASNetLarge': NASNetLarge,
        }

        self.model = self.model_options[self.model_spec]

    def build_model(self):

        self.model = self.model(include_top=self.include_top,
                                weights=self.weights,
                                input_tensor=self.input_tensor,
                                pooling=self.pooling)

    def train_model(self):

        pass

    def predict(self):

        pass

resnet50 = ResNet50(include_top=True,
                    weights='imagenet',
                    input_tensor=None,
                    input_shape=None,
                    pooling=None,
                    classes=1000)

(x_train, y_train), (x_test, y_test) = cifar100.load_data()


"""empty message

Revision ID: 4a80166a46ec
Revises: 7f234c96d8f4
Create Date: 2017-05-24 13:49:31.910594

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '4a80166a46ec'
down_revision = '7f234c96d8f4'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('subject', sa.Column('dataset_id', sa.Integer(), nullable=False))
    op.create_foreign_key(None, 'subject', 'dataset', ['dataset_id'], ['id'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'subject', type_='foreignkey')
    op.drop_column('subject', 'dataset_id')
    # ### end Alembic commands ###


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /usr/local/lib/python2.7/site-packages/canteen/logic/session.py
# Compiled at: 2014-09-26 04:50:19
"""

  session logic
  ~~~~~~~~~~~~~

  provides base logic for handling and enforcing user sessions.

  :author: Sam Gammon <sg@samgammon.com>
  :copyright: (c) Sam Gammon, 2014
  :license: This software makes use of the MIT Open Source License.
            A copy of this license is included as ``LICENSE.md`` in
            the root of the project.

"""
import time, hashlib, abc, random, string, operator
from ..core import hooks
from ..base import logic
from ..util import config
from ..util import decorators
from .. import model as models
_BUILTIN_SESSION_PROPERTIES = frozenset(('seen', 'data', 'csrf', 'established', 'seen',
                                         'agent', 'client', 'tombstoned'))

class ClientSession(models.Model):
    """ Canteen model for a user or HTTP client session. Tracks things like a
      session ID, last-seen-time, and when the session was established. """
    seen = int
    data = dict
    csrf = basestring
    agent = basestring
    client = basestring
    tombstoned = (bool, {'default': False})
    established = (int, {'required': True})

class Session(object):
    """ Thin object representing a user session. Used at runtime until it needs
      to be stored, which then spawns a model instance (usually a
      ``ClientSession``). """
    __slots__ = ('__id__', '__session__')

    def __init__(self, key=None, model=ClientSession, **kwargs):
        """ Initialize this ``Session`` object with an ID and session model.

        :param key: ``str`` key to attach to the session model and pass back-
          and-forth as the user's session ID.

        :param model: Model class to use for spawning the new session and
          persisting it.

        :param **kwargs: Extra keyword arguments to pass to ``model``'s
          constructor. """
        if isinstance(model, type):
            if 'established' not in kwargs:
                kwargs['established'] = kwargs['seen'] = int(time.time())
            if 'data' not in kwargs:
                kwargs['data'] = {}
            for k, v in kwargs.iteritems():
                if k not in _BUILTIN_SESSION_PROPERTIES:
                    kwargs['data'][k] = v

            key = Session.make_key(key, model)
            self.__id__, self.__session__ = key.id, model(key=key, **kwargs)
        elif not kwargs:
            self.__session__, self.__id__ = model, id
        else:
            raise RuntimeError('Cannot specify a session model instance and also additional kwargs.')

    @decorators.classproperty
    def config(cls):
        """  """
        return config.Config().get('Sessions', {'debug': True})

    id = property(lambda self: self.__id__)
    data = property(lambda self: self.__session__.data)
    csrf = property(lambda self: self.__session__.csrf or setattr(self.__session__, 'csrf', self.generate_token()) or self.__session__.csrf)

    def set(self, key, value, exception=Exception):
        """  """
        try:
            return setattr(self.data, key, value) or self
        except KeyError:
            if exception is not Exception:
                raise exception('Could not write to session item "%s".' % key)

    def get(self, key, default=None, exception=Exception):
        """  """
        if key in self.data:
            return self.data[key]
        if default:
            return default
        if exception is not Exception:
            raise exception('Could not resolve session data item "%s".' % key)

    __getitem__ = lambda self, key: self.get(key, exception=KeyError)
    __setitem__ = lambda self, key, value: self.set(key, value, exception=KeyError)

    def __contains__(self, key):
        """  """
        return key in self.__session__.data

    def reset(self, save=False, adapter=None):
        """  """
        self.__session__.csrf, self.__session__.tombstoned = None, True
        if save:
            self.save(adapter)
        return

    def reset_csrf(self, save=False, adapter=None):
        """  """
        self.__session__.csrf = None
        new_csrf = self.csrf
        if save:
            self.save(adapter)
        return new_csrf

    def save(self, environ, adapter=None):
        """  """
        if 'REMOTE_ADDR' in environ:
            self.__session__.client = environ.get('REMOTE_ADDR')
        if 'HTTP_USER_AGENT' in environ:
            self.__session__.agent = environ.get('HTTP_USER_AGENT')
        if self.config.get('storage', {}).get('enable'):
            return self.__session__.put(adapter=adapter)

    @classmethod
    def load(cls, id, model=ClientSession, strict=False, data=None):
        """  """
        _session = None
        if _session:
            return cls(id, _session)
        else:
            if strict:
                return False
            return cls(id, data=dict(data.iteritems()))

    @staticmethod
    def generate_token(salt=''):
        """  """
        return Session.config.get('hash', hashlib.sha256)(salt + reduce(operator.add, (random.choice(string.printable) for x in xrange(32)))).hexdigest()

    @staticmethod
    def make_key(id=None, model=ClientSession):
        """  """
        return models.Key(model, id or Session.generate_token(Session.config.get('salt', '')))

class SessionEngine(object):
    """  """
    __label__, __metaclass__ = None, abc.ABCMeta
    __api__, __path__, __config__ = None, None, {}

    def __init__(self, name, config, api):
        """  """
        self.__path__, self.__config__, self.__api__ = name, config, api

    api = property(lambda self: self.__api__)
    config = property(lambda self: self.__config__.get(self.__path__))
    session_config = property(lambda self: self.__config__)

    @staticmethod
    def configure(name, **config):
        """  """

        def add_engine(klass):
            """  """
            klass.__label__ = name
            Sessions.add_engine(name, klass, **config)
            return klass

        return add_engine

    @abc.abstractmethod
    def load(self, context):
        """  """
        raise NotImplementedError('Method `SessionEngine.load` is abstract.')

    @abc.abstractmethod
    def commit(self, context, session):
        """  """
        raise NotImplementedError('Method `SessionEngine.commit` is abstract.')

@decorators.bind('sessions')
class Sessions(logic.Logic):
    """  """
    __salt__ = None
    __secret__ = None
    __engines__ = {}
    __algorithm__ = None

    @decorators.classproperty
    def config(cls):
        """  """
        return config.Config().get('Sessions', {'debug': True})

    @decorators.classproperty
    def salt(cls):
        """  """
        if not cls.__salt__:
            cls.__salt__ = cls.config.get('salt')
            if not cls.__salt__:
                cls.__salt__ = Session.generate_token()
        return cls.__salt__

    @decorators.classproperty
    def secret(cls):
        """  """
        if not cls.__secret__:
            cls.__secret__ = cls.config.get('secret')
            if not cls.__secret__:
                cls.__secret__ = Session.generate_token() + Session.generate_token()
        return cls.__secret__

    @decorators.classproperty
    def engines(cls):
        """  """
        for engine in cls.__engines__.iteritems():
            yield engine

    @classmethod
    def add_engine(cls, name, engine, **config):
        """  """
        cls.__engines__[name] = (
         engine, config)
        return cls

    @classmethod
    def get_engine(cls, name=None, context=None):
        """  """
        if not context:
            _CONTEXT, _context_cfg = (False, {}) if 1 else (
             True, config.Config().get(context, {}).get('sessions', {}))
            name = name or _context_cfg.get('engine', 'cookies')
        if name in cls.__engines__:
            _engine, _engine_config = cls.__engines__[name]
            _config = {}
            if _CONTEXT:
                _config.update(config.Config().get('Sessions', {}))
                _config.update(_context_cfg)
            _config.update(_engine_config)
            return _engine(name, _config, cls)
        raise RuntimeError('No such session runtime: "%s".' % name)

    @decorators.bind('reset')
    def reset(self, redirect=None, save=True, engine=None):
        """  """
        pass

    @decorators.bind('establish', wrap=hooks.HookResponder('match', context=('environ',
                                                                             'endpoint',
                                                                             'arguments',
                                                                             'request',
                                                                             'http')))
    def establish(self, environ, endpoint, arguments, request, http):
        """  """
        if request.session:
            session, engine = request.session
            if not session and self.config.get('always_establish', True):
                return request.set_session(Session(), engine)

    @decorators.bind('load', wrap=hooks.HookResponder(context=('request', 'http'), *('request',
                                                                                'message')))
    def load(self, request, http):
        """  """
        if http:
            assert request, 'must have a request to load a session'
            session_cfg = http.config.get('sessions', {'enable': False})
            if session_cfg.get('enable', True):
                engine = self.get_engine(name=session_cfg.get('engine', 'cookies'), context='http')
                engine.load(request=request, http=http)

    @decorators.bind('commit', wrap=hooks.HookResponder('response', context=('status',
                                                                             'headers',
                                                                             'request',
                                                                             'http',
                                                                             'response')))
    def commit(self, status, headers, request, http, response):
        """  """
        if response:
            if request.session:
                session, engine = request.session
                engine.commit(request=request, response=response, session=session)

    @decorators.bind('save', wrap=hooks.HookResponder('complete', context=('response',
                                                                           'request',
                                                                           'http',
                                                                           'environ')))
    def save(self, response, request, http, environ):
        """  """
        if request.session and response:
            session, engine = request.session
            session.save(environ, adapter=None)
        return


class Solution(object):
    def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        ans = len(words)

        i1, i2 = -1, -1  # index of last appearance of word1 and word2
        for i in xrange(len(words)):
            curr = words[i]
            if curr == word1:
                i1 = i
                if i2 != -1:
                    ans = min(i1 - i2, ans)  # abs(i1 - i2) is not necessary
            elif curr == word2:
                i2 = i
                if i1 != -1:
                    ans = min(i2 - i1, ans)
        return ans

"""
Given a list of words and two words word1 and word2, return the
shortest distance between these two words in the list.

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
"""


from random import randint
#Created by Owen Schmierer 17/8/2020
#For my gorgeous kids
#To do - add a timer, and summary output to a list.

def multiply(num1, num2):
    global correct_count, total_count

    quiz1 = int(num1) * int(num2)
    #print(f"{num1} * {num2} = {quiz1}") #This prints the answer.

    while True:
        print(f"What is {num1} X {num2}")
        answer = input("> ")
        try:
            answer = int(answer)
        except:
            print('Please use numeric digits')
            continue
        break

    if int(answer) == int(quiz1):
        print("You got it correct!")
        correct_count += 1
    else:
        print(f"Try the next question.  The answer is {int(quiz1)}.")
    total_count += 1

def divide(num1, num2):
    global correct_count, total_count

    #Do a multiply
    quiz1 = int(num1) * int(num2)
    #Use the multiplication to get division question to avoid fractions
    quiz4 = int(quiz1) / int(num1) #quiz4 = num2

    #print(f"{num1} * {num2} = {quiz1}") #This prints the answer.
    while True:
        print(f"What is {quiz1} / {num1}")
        answer = input("> ")
        try:
            answer = int(answer)
        except:
            print('Please use numeric digits')
            continue
        break

    if int(answer) == int(quiz4):
        print("You got it correct!")
        correct_count += 1
    else:
        print(f"Try the next question.  The answer is {int(quiz4)}.")
    total_count += 1

def addition(num1, num2):
    global correct_count, total_count

    quiz2 = int(num1) + int(num2)
    while True:
        print(f"What is {num1} + {num2}")
        answer = input("> ")
        try:
            answer = int(answer)
        except:
            print('Please use numeric digits')
            continue

        break

    if int(answer) == int(quiz2):
        print("You got it correct!")
        correct_count += 1
    else:
        print(f"Try the next question.  The answer is {int(quiz2)}.")
    total_count += 1

def subtraction(num1, num2):
    global correct_count, total_count

    quiz3 = int(num1) - int(num2)

    while True:
        print(f"What is {num1} - {num2}")
        answer = input("> ")
        try:
            answer = int(answer)
        except:
            print('Please enter numeric digits.')
            continue
        break

    if int(answer) == int(quiz3):
        print("You got it correct!")
        correct_count += 1
    else:
        print(f"Try the next question.  The answer is {int(quiz3)}")
    total_count += 1

correct_count = int(0)
total_count = int(0)

print("Would you like 1) multiplication, 2) addition 3) subtraction 4) division")
type = input("> ")

######## MULTIPLICATION
if int(type) == 1:
    while True:
        while True:
            print("Would you like 1) random numbers, or 2) to suggest a number?")
            query1 = input("> ")
            try:
                query1 = int(query1)
            except:
                print('Please enter 1 or 2')
                continue
            break

        if int(query1) == 1:
            i = 1
            while i <= 20:
                randomnum1 = f"{randint(1,12)}"
                randomnum2 = f"{randint(1,12)}"
                multiply(randomnum1, randomnum2)
                i += 1
                print(f"You have {correct_count} correct out of {total_count} total.")
        elif int(query1) == 2:
            print("What number would you like?")
            choosenumber = input("> ")
            i = 1
            while i <= 20:
                randomnum2 = f"{randint(1,12)}"
                multiply(choosenumber, randomnum2)
                i += 1
                print(f"You have {correct_count} correct out of {total_count} total.")

#################################### ADDITION
elif int(type) == 2:
    i = 1
    while i <= 10:
        randomnum3 = f"{randint(10,100)}"
        randomnum4 = f"{randint(10,100)}"
        addition(randomnum3, randomnum4)
        i += 1
        print(f"You have {correct_count} correct out of {total_count} total.")

####################################################SUBTRACTION
elif int(type) == 3:
    i = 1
    while i <= 10:
        randomnum5 = f"{randint(10,100)}"
        randomnum6 = f"{randint(10,100)}"
        #Set variables to work out which number is the biggest, to subtract from.
        if int(randomnum5) >= int(randomnum6):
            sub_big = int(randomnum5)
            sub_little = int(randomnum6)
        else:
            sub_big = int(randomnum6)
            sub_little = int(randomnum5)
        subtraction(sub_big, sub_little)
        #print(f"sub_big={sub_big}")
        #print(f"sub_little={sub_little}")
        i += 1
        print(f"You have {correct_count} correct out of {total_count} total.")

####################DIVISION
elif int(type) == 4:
    while True:
        while True:

            print("Would you like 1) random numbers, or 2) to suggest a number?")
            query1 = input("> ")
            try:
                query1 = int(query1)
            except:
                print('Enter 1 or 2 please')
                continue
            break

        if int(query1) == 1:
            i = 1
            while i <= 20:
                randomnum7 = f"{randint(1,12)}"
                randomnum8 = f"{randint(1,12)}"
                divide(randomnum7, randomnum8)
                i += 1
                print(f"You have {correct_count} correct out of {total_count} total.")

        elif int(query1) == 2:
            print("What number would you like?")
            choosenumber = input("> ")
            i = 1
            while i <= 20:
                randomnum2 = f"{randint(1,12)}"
                divide(choosenumber, randomnum2)
                i += 1
                print(f"You have {correct_count} correct out of {total_count} total.")


import unittest
import os
import json
import time
import shutil

from os import environ
try:
    from ConfigParser import ConfigParser  # py2
except:
    from configparser import ConfigParser  # py3

from biokbase.workspace.client import Workspace as workspaceService
from GenomeFileUtil.GenomeFileUtilImpl import GenomeFileUtil
from GenomeFileUtil.GenomeFileUtilServer import MethodContext

from DataFileUtil.DataFileUtilClient import DataFileUtil

class GenomeFileUtilTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        token = environ.get('KB_AUTH_TOKEN', None)
        # WARNING: don't call any logging methods on the context object,
        # it'll result in a NoneType error
        cls.ctx = MethodContext(None)
        cls.ctx.update({'token': token,
                        'provenance': [
                            {'service': 'GenomeFileUtil',
                             'method': 'please_never_use_it_in_production',
                             'method_params': []
                             }],
                        'authenticated': 1})
        config_file = environ.get('KB_DEPLOYMENT_CONFIG', None)
        cls.cfg = {}
        config = ConfigParser()
        config.read(config_file)
        for nameval in config.items('GenomeFileUtil'):
            cls.cfg[nameval[0]] = nameval[1]
        cls.wsURL = cls.cfg['workspace-url']
        cls.ws = workspaceService(cls.wsURL, token=token)
        cls.serviceImpl = GenomeFileUtil(cls.cfg)

        # create one WS for all tests
        suffix = int(time.time() * 1000)
        wsName = "test_GenomeAnnotationAPI_" + str(suffix)
        ret = cls.ws.create_workspace({'workspace': wsName})
        cls.wsName = wsName

        with open ('data/e_coli_assembly.json', 'r') as file:
            data_str=file.read()
        data = json.loads(data_str)

        # save a fasta file to shock, preload an assembly pointing to it
        dfu = DataFileUtil(os.environ['SDK_CALLBACK_URL'])
        shutil.copy('data/e_coli_assembly.fasta', cls.cfg['scratch'])
        shock_file = dfu.file_to_shock({
                            'file_path': os.path.join(cls.cfg['scratch'], 'e_coli_assembly.fasta'),
                            'make_handle': 1
                        })
        data['fasta_handle_ref'] = shock_file['handle']['hid']

        # save to ws
        save_info = {
                'workspace':wsName,
                'objects': [{
                    'type':'KBaseGenomeAnnotations.Assembly',
                    'data':data,
                    'name':'e_coli_assembly'
                }]
            }
        result = cls.ws.save_objects(save_info)
        info = result[0]
        cls.e_coli_assembly_ref = str(info[6]) +'/' + str(info[0]) + '/' + str(info[4])

        # preload with reference data
        with open ('data/e_coli.json', 'r') as file:
            data_str=file.read()
        data = json.loads(data_str)
        data['assembly_ref'] = cls.e_coli_assembly_ref
        # save to ws
        save_info = {
                'workspace':wsName,
                'objects': [{
                    'type':'KBaseGenomes.Genome',
                    'data':data,
                    'name':'e_coli'
                }]
            }
        result = cls.ws.save_objects(save_info)
        info = result[0]
        cls.e_coli_ref = str(info[6]) +'/' + str(info[0]) + '/' + str(info[4])
        print('created e.coli test genome: ' + cls.e_coli_ref)

        # save a genbank file to shock, preload a genome pointing to it
        dfu = DataFileUtil(os.environ['SDK_CALLBACK_URL'])
        shutil.copy('data/GCF_000005845.2_ASM584v2_genomic.gbff', cls.cfg['scratch'])
        shock_file = dfu.file_to_shock({
                            'file_path': os.path.join(cls.cfg['scratch'], 'GCF_000005845.2_ASM584v2_genomic.gbff'),
                            'make_handle': 1
                        })
        data['genbank_handle_ref'] = shock_file['handle']['hid']

        # save to ws
        save_info['objects'][0]['name'] = 'e_coli_with_genbank'
        result = cls.ws.save_objects(save_info)
        info = result[0]
        cls.e_coli_ref_with_genbank = str(info[6]) +'/' + str(info[0]) + '/' + str(info[4])
        print('created e.coli test genome with handle: ' + cls.e_coli_ref_with_genbank)

    @classmethod
    def tearDownClass(cls):
        if hasattr(cls, 'wsName'):
            cls.ws.delete_workspace({'workspace': cls.wsName})
            print('Test workspace was deleted')

    def getWsClient(self):
        return self.__class__.ws

    def getWsName(self):
        if hasattr(self.__class__, 'wsName'):
            return self.__class__.wsName
        suffix = int(time.time() * 1000)
        wsName = "test_GenomeFileUtil_" + str(suffix)
        ret = self.getWsClient().create_workspace({'workspace': wsName})
        self.__class__.wsName = wsName
        return wsName

    def getImpl(self):
        return self.__class__.serviceImpl

    def getContext(self):
        return self.__class__.ctx

    def test_simple_genbank_download(self):
        genomeFileUtil = self.getImpl()
        print('testing Genbank download by building the file')
        res1 = genomeFileUtil.genome_to_genbank(self.getContext(),
            {'genome_ref': self.e_coli_ref})[0]
        self.assertEqual(res1['from_cache'], 0)

    def test_simple_genbank_download_from_cache(self):
        genomeFileUtil = self.getImpl()
        print('testing Genbank download from cached file')
        res2 = genomeFileUtil.genome_to_genbank(self.getContext(),
            {'genome_ref': self.e_coli_ref_with_genbank})[0]
        self.assertEqual(res2['from_cache'], 1)
        self.assertTrue('genbank_file' in res2)
        self.assertTrue('file_path' in res2['genbank_file'])
        self.assertTrue(bool(res2['genbank_file']['file_path']))

    def test_simple_genbank_export_from_cache(self):
        genomeFileUtil = self.getImpl()
        print('testing Genbank export from cached file')
        res = genomeFileUtil.export_genome_as_genbank(self.getContext(),
            {'input_ref': self.e_coli_ref_with_genbank})[0]
        self.assertTrue('shock_id' in res)
        self.assertTrue(bool(res['shock_id']))


import os, sys
import numpy as np
import cv2

class TFLiteModel:

    def __init__(self, tf, model_path, preprocess_func=None):
        self.interpreter = tf.lite.Interpreter(model_path=model_path)
        self.interpreter.allocate_tensors()
        self.input_details = self.interpreter.get_input_details()
        self.output_details = self.interpreter.get_output_details()
        self.input_shape = self.input_details[0]['shape']
        self.target_img_size = tuple(self.input_shape[1:3])
        self.preprocess_func = preprocess_func if preprocess_func is not None else self.preprocess

    def preprocess(self, input):
        return np.array(input).astype(np.float32) / 127.5 - 1

    def predict(self, image, color_mode='rgb'):
        assert color_mode in ['bgr', 'rgb']
        image = cv2.resize(image, self.target_img_size)
        if color_mode == 'bgr':
            image = image[:,:,::-1]

        image = self.preprocess_func(image)[np.newaxis,:,:,:]

        self.interpreter.set_tensor(self.input_details[0]['index'], image)
        self.interpreter.invoke()

        outputs = [self.interpreter.get_tensor(out['index']) for out in self.output_details]

        if len(outputs) == 1:
            return outputs[0]
        else:
            return outputs


from __future__ import print_function
import logging
import sys

import grpc

import hellonerd_pb2
import hellonerd_pb2_grpc

def run():
    try:
        uname = sys.argv[1]
        server = sys.argv[2]
        port = sys.argv[3]
        detonate = sys.argv [4]
    except:
        detonate = "no"
        print('usage: python client.py username ip  port  --normal/--detonate ')
        sys.exit(0)

    with grpc.insecure_channel(server+':'+port) as channel:
        stub = hellonerd_pb2_grpc.HelloNerdStub(channel)
        if (detonate == '--detonate'):
            while True:
                response = stub.SayHello(hellonerd_pb2.HelloRequest(name=uname))
                print ("Nerd Says : " + response.message)
        response = stub.SayHello(hellonerd_pb2.HelloRequest(name=uname))
        print("Nerd Says: " + response.message)

if __name__ == '__main__':
    logging.basicConfig()
    run()