import pandas as pd
df = pd.read_csv('Final_Data/total_daily_data.csv')
df = df[['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','name','team1','team2','개시시간','경기시간','관중',
    '구장','날짜','득점','안타','타수','타율','타점']]

df.columns.values[:18] = list(range(1,19))    # 연장 이닝의 경우 10이닝의 컬럼명이 9로 나와있어서 9이닝과 컬럼명이 겹칠 수 있어 변경필요
df

df['구장'] = df['구장'].str[5:]     # 구장 컬럼 재가공(구장이름만 추출)
df['관중'] = df['관중'].str[5:].str.replace(',','').astype('int')     # 관중 컬럼 재가공(관중수만 추출하여 콤마 제거)

df_year = df['날짜'].str.findall('[0-9]').str[:4].str.join('')    # 날짜에서 년도만 추출
df_month = df['날짜'].str.findall('[0-9]').str[4:6].str.join('')  # 날짜에서 월만 추출
df_date = df['날짜'].str.findall('[0-9]').str[6:].str.join('')    # 날짜에서 일만 추출
df_time = df['개시시간'].str[5:9]+'0'    # 개시시간에서 시,분 앞자리(40분이면 4)+0 추출 -> 더블헤더의 경우 실제 개시시간은 14:51분인데 기록상으로 14:50인 경우가 존재함
df['시간'] = pd.to_datetime(df_year + '-' + df_month + '-' + df_date + ' ' + df_time)    # 추출값(str) 모두 결합 후 datetime으로 변환

del df['날짜']
del df['개시시간']
del df['경기시간']

imsi=[]
for i in df[10].isnull():
    if i == True:
        imsi.append(0)
    else:
        imsi.append(1)

df['연장여부'] = imsi    # 연장 간 경우(10회 이상)=1, 9회까지만 했을 경우=0

dic = {'1땅':'우땅','2땅':'우땅','3땅':'좌땅','유땅':'좌땅','투땅':'중땅','1비':'우플','2비':'우플','3비':'좌플','유비':'좌플','투비':'중플','1안':'우안','2안':'우안',
       '3안':'좌안','유안':'좌안','투유병':'중병','투2병':'중병','2유병':'우병','유2병':'좌병','32병':'좌병','좌비':'좌플','우비':'우플','중비':'중플','좌희비':'좌플',
       '중희비':'중플','우희비':'우플','1파':'우플','2파':'우플','3파':'좌플','유파':'좌플','4구':'볼넷','좌중안':'좌안','우중안':'우안','좌중2':'좌2','좌중안':'좌안',
       '1번':'우땅','우중2':'우2','우파':'우플','1실':'우땅','우중홈':'우홈','1희번':'우땅','포비':'중플','포파':'중플','투희번':'중땅','투실':'중땅','유실':'좌땅',
       '투안':'중안','3직':'좌플','3희번':'좌땅','투직':'중플','좌중홈':'좌홈','3실':'좌땅','2직':'우플','포희번':'중땅','유직':'좌땅','2실':'우땅','좌중3':'좌3',
       '우중3':'우3','좌파':'좌플','좌병':'좌플','고4':'볼넷','유병':'좌병','스낫':'삼진','2병':'우병','포번':'중땅','투번':'중땅','3번':'좌땅','1유병':'우병','포안':'중안',
       '포땅':'중땅','1직':'우플','투희선':'중땅','좌실':'좌플','투희실':'중땅','야선':'','투포병':'중땅','투파':'중플','1병':'우병','타방':'볼넷','우희실':'우플','투3병':'중땅',
       '3병':'좌땅','포유병':'중땅','三二병':'좌땅','二땅':'우땅','一땅':'우땅','一비':'우플','三비':'좌플','三파':'좌플','二비':'우플','二실':'우땅','유二병':'좌땅',
       '一파':'우플','三안':'좌안','투二병':'중땅','一직':'우플','一희번':'우땅','二유병':'우땅','一번':'우땅','三실':'좌땅','二직':'우플','二안':'우안','一안':'우안',
       '三번':'좌땅','二파':'우플','一실':'우땅','三병':'좌땅','三희번':'좌땅','一병':'우병','우실':'우플','二병':'우병','二희비':'우플','三직':'좌플','포병':'중병',
       '삼비':'삼진','포희실':'중땅','유포병':'좌병','32':'좌병','1포병':'우병','三땅':'좌땅','一유병':'우땅','포실':'중땅','포三병':'중병','一희비':'우플','一희선':'우땅',
       '삼선':'좌땅','포희선':'중땅','우직':'우플','3희선':'좌땅','유좌안':'좌안','투유안':'중안','투2안':'중안','투병':'중병','2우안':'우안','투3안':'좌안','2중안':'중안',
       '1우안':'우안','3유안':'좌안','유3안':'좌안','2번':'우땅','유중2':'중2','투중안':'중안','2중2':'중2','중실':'중플','투우안':'우안','3좌안':'좌안','투좌안':'좌안',
       '1희선':'우땅','3포병':'우병','유중안':'중안','3좌2':'좌2','투1안':'우안','12안':'우안','1우3':'우3','유좌2':'좌2','2포병':'우병','1우2':'우2','중희실':'중플',
       '3희실':'좌땅','좌직':'좌플','중직':'중플','3삼중':'좌병','2희비':'우플','1희실':'우땅','3유병':'좌병','투三병':'중병','三희실':'좌땅','三':'좌땅','二희실':'우땅',
       '유희번':'좌땅','투2':'중병','투중2':'중2','포3병':'중병','1희비':'우플','유2':'좌병','2희번':'우땅','투우2':'우2','2우2':'우2','22':'우2','2유안':'우안','2희실':'우땅',
       '三포병':'좌땅','一2':'우2','三2':'우2','一희실':'우땅','一三병':'우병','13병':'우땅','12':'우2','유번':'좌땅','투좌2':'좌2','유희비':'좌플','122':'우2','포2병':'중병',
       '유3병':'좌병','23병':'우병','一포병':'우병','二번':'우땅','병':'좌병','3중안':'좌안','2좌안':'중안','2좌2':'중2','유우안':'중안','3유2':'좌2','21병':'우땅','투포안':'중땅',
       '1중2':'우2','二희번':'우땅','三유병':'좌병','안':'우안','유우2':'좌2','좌희실':'좌플','三희선':'좌땅','三희비':'좌플','투1병':'중병','땅':'우땅'}

df.loc[df[9]=='땅',:]

# 타구방향을 기준으로 정리함. ex)1땅 = 오른쪽 땅볼이므로 우땅, 1비 = 오른쪽 뜬공이므로 우플

df.iloc[:,:9] = df.iloc[:,:9].applymap(lambda x : str(x).split('/')[0])     # 한 이닝 2타석 들어선 경우 -> 중2/ 유땅 이런식으로 나옴 -> 재가공 필요(앞에꺼만 추출)
df.iloc[:,:9] = df.iloc[:,:9].apply(lambda x : x.replace(dic))

df[9].unique()

df_wg = pd.read_csv('Final_Data/weather_ground_merge.csv',encoding='CP949')
df_wg = df_wg.iloc[:,2:]
wg_year = df_wg['year'].astype('str')
wg_month_date = df_wg['date'].str[:2] + '-' + df_wg['date'].str[3:5]
wg_time = df_wg['playtime']

df_wg['date'] = pd.to_datetime(wg_year + '-' + wg_month_date + ' ' + wg_time)

del df_wg['playtime']
del df_wg['dates']
del df_wg['city']

# 인천을 문학으로 변경
ground_imsi=[]
for i in df_wg['ground']:
    if i == '인천':
        ground_imsi.append('문학')
    else:
        ground_imsi.append(i)
df_wg['ground'] = ground_imsi

df_merge = pd.merge(df,df_wg, left_on=['시간','구장'], right_on=['date','ground'])

left_go=[]; center_go=[]; right_go=[]; left_fly=[]; center_fly=[]; right_fly=[]; left_hit=[]; center_hit=[]; right_hit=[]; left_2=[]; center_2=[]; right_2=[]; left_3=[]; center_3=[];
right_3=[]; left_dp=[]; center_dp=[]; right_dp=[]; left_hr=[]; center_hr=[]; right_hr=[]; b4=[]; hbp=[]; so=[]; left_all=[]; center_all=[]; right_all=[]
# 좌땅,중땅,우땅, 좌플,중플,우플, 좌안,중안,우안, 좌2,중2,우2, 좌3,중3,우3, 좌병,중병,우병, 좌홈,중홈,우홈, 볼넷,사사구,삼진, 좌측타구, 중간타구, 우측타구

for i in range(len(df_merge)):
    left_go.append((df_merge.iloc[i,:9] == '좌땅').sum())
    center_go.append((df_merge.iloc[i,:9] == '중땅').sum())
    right_go.append((df_merge.iloc[i,:9] == '우땅').sum())

    left_fly.append((df_merge.iloc[i,:9] == '좌플').sum())
    center_fly.append((df_merge.iloc[i,:9] == '중플').sum())
    right_fly.append((df_merge.iloc[i,:9] == '우플').sum())

    left_hit.append((df_merge.iloc[i,:9] == '좌안').sum())
    center_hit.append((df_merge.iloc[i,:9] == '중안').sum())
    right_hit.append((df_merge.iloc[i,:9] == '우안').sum())

    left_2.append((df_merge.iloc[i,:9] == '좌2').sum())
    center_2.append((df_merge.iloc[i,:9] == '중2').sum())
    right_2.append((df_merge.iloc[i,:9] == '우2').sum())

    left_3.append((df_merge.iloc[i,:9] == '좌3').sum())
    center_3.append((df_merge.iloc[i,:9] == '중3').sum())
    right_3.append((df_merge.iloc[i,:9] == '우3').sum())

    left_dp.append((df_merge.iloc[i,:9] == '좌병').sum())
    center_dp.append((df_merge.iloc[i,:9] == '중병').sum())
    right_dp.append((df_merge.iloc[i,:9] == '우병').sum())

    left_hr.append((df_merge.iloc[i,:9] == '좌홈').sum())
    center_hr.append((df_merge.iloc[i,:9] == '중홈').sum())
    right_hr.append((df_merge.iloc[i,:9] == '우홈').sum())

    b4.append((df_merge.iloc[i,:9] == '볼넷').sum())
    hbp.append((df_merge.iloc[i,:9] == '사구').sum())
    so.append((df_merge.iloc[i,:9] == '삼진').sum())

    left_all.append((df_merge.iloc[i,:9].str[0] == '좌').sum())
    center_all.append((df_merge.iloc[i,:9].str[0] == '중').sum())
    right_all.append((df_merge.iloc[i,:9].str[0] == '우').sum())

df_merge['좌땅']=left_go
df_merge['중땅']=center_go
df_merge['우땅']=right_go
df_merge['좌플']=left_fly
df_merge['중플']=center_fly
df_merge['우플']=right_fly
df_merge['좌안']=left_hit
df_merge['중안']=center_hit
df_merge['우안']=right_hit
df_merge['좌2']=left_2
df_merge['중2']=center_2
df_merge['우2']=right_2
df_merge['좌3']=left_3
df_merge['중3']=center_3
df_merge['우3']=right_3
df_merge['좌병']=left_dp
df_merge['중병']=center_dp
df_merge['우병']=right_dp
df_merge['좌홈']=left_hr
df_merge['중홈']=center_hr
df_merge['우홈']=right_hr
df_merge['볼넷']=b4
df_merge['사구']=hbp
df_merge['삼진']=so
df_merge['좌측타구']=left_all
df_merge['중간타구']=center_all
df_merge['우측타구']=right_all

df_merge.to_csv('left_right_info_merge.csv')


import logging

import albumentations.augmentations.functional as albumentations_F
import cv2
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision.transforms import functional as F

from src.Utilities import MASK_REAL_PATH, MEAN, STD

log = logging.getLogger(__name__)

class ToTensor(object):
    def __call__(self, image, target):
        image = F.to_tensor(image)
        target = torch.as_tensor(np.array(target), dtype=torch.float32)
        return image, target

tensorize = ToTensor()

class Normalize(object):
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std

    def __call__(self, image, target):
        image = F.normalize(image, mean=self.mean, std=self.std)
        return image, target

normalise = Normalize(mean=MEAN, std=STD)

class XRayDataset(Dataset):
    """X-ray segmentation dataset"""

    def __init__(self, dataframe, augmentations, mask_folder, image_size=224):
        self.mask_folder = mask_folder
        self.image_size = image_size

        if 'index' in dataframe:
            del dataframe['index']

        self.augmentate = augmentations
        self.df = dataframe

    def __getitem__(self, index):
        row = self.df.iloc[index]
        label = row["label"]

        image_name = row["image_path"]

        try:
            img = Image.open(image_name).convert("RGB")
            # (width, height)
            img = img.resize(size=(224, 224))
        except FileNotFoundError:
            log.info("Image not found: {}".format(image_name))
            return None

        # Always will exist
        if label == 0:
            mask = Image.open(MASK_REAL_PATH).convert("L")

        else:
            try:
                mask_path = row["mask_path"]
                mask = Image.open(mask_path).convert("L")
            except FileNotFoundError:
                log.info("Fake Mask not found: {}".format(mask_path))
                return None

        img = np.array(img)
        mask = np.array(mask)

        transformed_images = self.augmentate(image=img, image2=mask)
        img = transformed_images["image"]
        mask = transformed_images["image2"]
        # due to isotropic resize need to resize mask
        mask = albumentations_F.resize(mask, height=56, width=56,
                                       interpolation=cv2.INTER_NEAREST)

        # binarise 0 and 1
        if label == 1:
            mask = (mask - mask.min()) / (np.ptp(mask))

        img, mask = tensorize(image=img, target=mask)
        img, mask = normalise(image=img, target=mask)

        images_with_masks = {
            "img": img,
            "mask": mask,
            "label": label
        }

        return images_with_masks

    def __len__(self):
        return len(self.df)


from zad1testy import runtests
# Jakub Karoń
# Zadanie rozwiązane za pomocą algorytmu Manachera, który wykorzystując własności symetrii palindromu
# pozwala na redukcję złożoności obliczeniowej do O(n). Dla każdej litery w wejściowym napisie sprawdzamy,
# czy litera ta nie jest środkiem podpalindromu zawierającego się w innym, dłuższym palindromie.
# W ten sposób możemy zmniejszyć liczbę porównań poprzez ustalenie początkowej długości palindromu.
# Promienie palindromów dla każdej litery przechowywujemy w tablicy pomocniczej.

def ceasar(s):
    left = 0 # lewa granica dłuższego palindromu
    right = float("-inf") # prawa granica dłuższego palindromu
    n = len(s)
    p_lengths = [0] * n  # tablica, której wartość p_lengths[i] odpowiada maksymalnemu promieniowi palindromu o
    # środku s[i]
    for i in range(n):
        # zmniejszenie liczby porównań poprzez sprawdzanie, czy rozważany palindrom zawiera się w innym palindromie i
        # można przypisać mu już początkową długość
        if left <= i <= right:  # jeśli i zawiera się w [left, right]
            mirror_index = left + right - i
            p_lengths[i] = min(p_lengths[mirror_index],
                               right - i)  # max długość palindromu o środku s[i] ograniczona z góry przez right - i
            # do końca przedziału [left, right]

        curr_left = i - p_lengths[i] - 1
        curr_right = i + p_lengths[i] + 1

        # po ustaleniu początkowego promienia próbujemy maksymalnie rozszerzyć rozważany palindrom
        while curr_left >= 0 and curr_right < n and s[curr_left] == s[curr_right]:
            p_lengths[i] += 1
            curr_left -= 1
            curr_right += 1

        # sprawdzamy, czy obecnie rozważony palindrom nie wyszedł poza zakres najdłuższego palindromu
        # jeśli tak, to aktualizujemy obecnie najdłuższy palindrom
        if i + p_lengths[i] > right:
            left = i - p_lengths[i]
            right = i + p_lengths[i]

    return (max(p_lengths) * 2) + 1

# zmien all_tests na True zeby uruchomic wszystkie testy
runtests(ceasar, all_tests=True)


import pygame.gfxdraw
import entity
import random
import math
from line import Point
from angles import *

class Asteroid(entity.Entity):

    def __init__(self, x, y):
        entity.Entity.__init__(self)
        self.x = x
        self.y = y
        self.lengths = [(int(random.random()*3)*5 + 20) for i in range(random.randrange(4, 10))]
        self.rotation = 0
        self.sides = len(self.lengths)
        self.dr = random.random()*math.pi + math.pi
        self.id = "Asteroid"

    def onCollide(self, e):
        if e.id == "Player":
            e.hit()

    def update(self, dt):
        self.rotation += self.dr*dt

    def update_collider(self):
        self.points = [Point((self.x + math.cos(self.rotation + i*M_2PI/self.sides)*self.lengths[i]),
                             (self.y + math.sin(self.rotation + i*M_2PI/self.sides)*self.lengths[i])) for i in range(self.sides)]

    def render(self, screen):

        points = [(int(point.x), int(point.y)) for point in self.points]
        sides = len(self.lengths)
        pygame.gfxdraw.polygon(screen, points, (255, 255, 255))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       : aas_repos_parser
# description : ''
# author      : HeShuai
# date        : 2016/1/13
# version     :
# usage       :
# notes       :

# Built-in modules
import os
import logging
import re
# Third-party modules

# Studio modules

# Local modules
import add_environ
import aas_libs.aas_sg as aas_sg
reload(aas_sg)

logging.basicConfig(filename=os.path.join(os.environ["TMP"], 'aas_repos_parser_log.txt'),
                    level=logging.WARN, filemode='a', format='%(asctime)s - %(levelname)s: %(message)s')

def parse_shot(text, project_name):
    sg_utils = aas_sg.SgUtility()
    all_sequence = sg_utils.get_sequence(project_name)
    all_shots = list()
    invalid_input = list()
    tongpei_pattern = r"^\d+[a-z]?_\*$"
    range_pattern = r"^\d+[a-z]?_\d+-\d+[a-z]?_\d+"
    single_pattern = r"^\d+[a-z]?_\d+"
    shot_string_list = text.split(',')
    for shot_string in shot_string_list:
        if not shot_string:
            continue
        # tong pei fu shots
        if re.match(tongpei_pattern, shot_string):
            sequence_name = shot_string.split('_')[0]
            if sequence_name not in all_sequence:
                invalid_input.append(shot_string)
            else:
                shots = sg_utils.get_all_shots_by_sequence(project_name, sequence_name)
                shot_names = [shot['name'] for shot in shots]
                all_shots.extend(shot_names)
        # range shots
        elif re.match(range_pattern, shot_string):
            shot_range = shot_string.split('-')
            if shot_range[0].split('_')[0] != shot_range[1].split('_')[0]:
                invalid_input.append(shot_string)
                continue
            try:
                if int(shot_range[0].split('_')[1]) > int(shot_range[1].split('_')[1]):
                    invalid_input.append(shot_string)
                    continue
            except:pass
            sequence_name = shot_range[0].split('_')[0]
            if sequence_name not in all_sequence:
                invalid_input.append(shot_string)
            else:
                shot_name_range = range(int(shot_range[0].split('_')[1]), int(shot_range[1].split('_')[1])+1)
                shot_names = ["%s_%s" % (sequence_name, str(shot_name).zfill(3))
                              for shot_name in shot_name_range]
                all_shots.extend(shot_names)
        # single shot
        elif re.match(single_pattern, shot_string):
            sequence_name = shot_string.split('_')[0]
            if sequence_name not in all_sequence:
                invalid_input.append(shot_string)
            else:
                all_shots.append(shot_string)
        else:
            invalid_input.append(shot_string)
    if not invalid_input:
        return list(set(all_shots))
    else:
        invalid_string = "Wrong input:\t"
        for invalid_shot_string in invalid_input:
            invalid_string = invalid_string+invalid_shot_string+'\n'
        return invalid_string

if __name__ == "__main__":
    pass


import asyncio
import random
from unittest.mock import AsyncMock, Mock
from bot.state.state import State

from bot.worker.worker import Worker
from bot_long_poll.dcs import Update
from store.game.models import GameModel
from store.player.models import Score
from vk_api.dcs import Message
from vk_api.vk_api import VkApi
from .data import (COMMANDS_USER1, COMMANDS_USER2, user1, about_response_message,
                   start_command_response_message,
                   game_request_response_message,
                   start_game_response_message,
                   guess_letter_correct_response_message,
                   guess_letter_incorrect_response_message,
                   guess_word_correct_response_message,
                   guess_word_incorrect_response_message)

class TestWorker:
    async def test_start_command(self, worker: Worker, state: State):
        update: Update = COMMANDS_USER1["start"]
        VkApi.send_message = AsyncMock(return_value=start_command_response_message)
        VkApi.get_user = AsyncMock(return_value=user1)
        await worker.handle_update(update)
        player_accessor = state.store.player_accessor
        user = await player_accessor.get_player_by_vk_id(update.from_id)
        assert user.first_name == user1.first_name
        assert user.last_name == user1.last_name
        assert user.vk_id == update.from_id
        assert user.id == 1

    async def test_about_command(self, worker: Worker, state: State):
        update: Update = COMMANDS_USER1["about"]
        VkApi.send_message = AsyncMock(return_value=about_response_message)
        await worker.handle_update(update)
        assert VkApi.send_message.call_count == 1
        message: Message = VkApi.send_message.mock_calls[0].args[0]
        assert message.user_id == update.from_id

    async def test_game_request(sekf, worker: Worker, state: State):
        update: Update = COMMANDS_USER1["game_request"]
        VkApi.send_message = AsyncMock(return_value=game_request_response_message)
        VkApi.get_user = AsyncMock(return_value=user1)
        await worker.handle_update(update)
        game_accessor = state.store.game_accessor
        game = await game_accessor.get_created_game_by_player(update)
        assert update.from_id in game.who_next
        assert game.state == "Created"
        assert len(game.players) == 1
        assert user1.first_name == game.players[0].first_name

    async def test_start_game_command(self, worker: Worker,
                                      state: State, player_1, question):
        update: Update = COMMANDS_USER1["start_game"]
        VkApi.send_message = AsyncMock(return_value=start_game_response_message)
        await worker.handle_update(update)
        game_accessor = state.store.game_accessor
        started_game = await game_accessor.get_started_game_by_player(update)
        assert update.from_id in started_game.who_next
        assert started_game.state == "Started"
        assert len(started_game.players) == 1
        assert started_game.question.title == question.title

    async def test_guess_letter_correct_answer(self, worker: Worker, state: State,
                                               question, player_1, started_game):
        update: Update = COMMANDS_USER1["guess_letter_correct"]
        game_accessor = state.store.game_accessor
        player_accessor = state.store.player_accessor
        VkApi.send_message = AsyncMock(return_value=guess_letter_correct_response_message)
        random.randint = Mock(return_value=14)
        score_before: Score = await player_accessor.get_score(started_game.id, update.from_id)
        await worker.handle_update(update)
        game: GameModel = await game_accessor.get_started_game_by_player(update)
        score_after: Score = await player_accessor.get_score(game.id, update.from_id)
        assert game.word == "м****"
        assert update.text in question.answer.title  # провепяем, что есть такая буква
        assert game.who_next[0] == player_1.vk_id  # т.к ответ верный ход остается у текущего игрока
        assert score_after.score - score_before.score == 14  # проверяем, что за правильный ответ начислено 14 баллов

    async def test_guess_letter_incorrect_answer(self, worker: Worker,
                                                 state: State, question, player_1,
                                                 player_2, started_game):
        update_user1: Update = COMMANDS_USER1["guess_letter_incorrect"]
        VkApi.send_message = AsyncMock(return_value=guess_letter_incorrect_response_message)
        await worker.handle_update(update_user1)
        game_accessor = state.store.game_accessor
        game: GameModel = await game_accessor.get_started_game_by_player(update_user1)
        assert update_user1.text not in question.answer.title  # провепяем, что нет такой буква
        assert game.word == "*****"
        assert game.who_next[1] == player_1.vk_id  # т.к ответет не верный игрок(player_1) перемещается в конец очереди
        assert game.who_next[0] == player_2.vk_id  # ход перешел к следующему игроку (player_2)

    async def test_guess_word_correct_answer(self, worker: Worker,
                                             state: State, question, player_1,
                                             player_2, started_game):

        update_user1: Update = COMMANDS_USER1["guess_word_correct"]
        game_accessor = state.store.game_accessor
        started_game.state == "Started"
        VkApi.send_message = AsyncMock(return_value=guess_word_correct_response_message)
        await worker.handle_update(update_user1)
        game: GameModel = await game_accessor.get_game_by_id(started_game.id)
        assert game.state == "Stoped"  # Игра остановлена, есть победитель
        assert len(game.who_next) == 0
        assert update_user1.text == question.answer.title  # Проверяем, что слово верно

    async def test_guess_word_incorrect_answer(self, worker: Worker,
                                               state: State, question, player_1,
                                               player_2, started_game):

        update_user1: Update = COMMANDS_USER1["guess_word_incorrect"]
        game_accessor = state.store.game_accessor
        started_game.state == "Started"
        VkApi.send_message = AsyncMock(return_value=guess_word_incorrect_response_message)
        await worker.handle_update(update_user1)
        game: GameModel = await game_accessor.get_game_by_id(started_game.id)
        assert game.state == "Started"
        assert player_1.vk_id not in game.who_next  # слово названо неверно, игрок удаляется из игры
        assert game.who_next[0] == player_2.vk_id  # ход переходит к следующему игроку
        assert update_user1.text != question.answer.title

    async def test_restart_worker(self, worker: Worker,
                                  state: State, question, player_1,
                                  player_2, started_game):
        update_user1: Update = COMMANDS_USER1["guess_letter_incorrect"]
        VkApi.send_message = AsyncMock(return_value=guess_letter_incorrect_response_message)
        who_next_before_restart = started_game.who_next
        # Игрок назавал неправильную букву. Должен произойти переход хода к следующему игроку.
        # В этот же самый момент отключаем сервис и запускаем заново. Бот должен пережить рестарт и завершить таски,
        # сохранив состояние игры. Игрок, назвавший неверную букву должен оказаться в конце очереди.
        await asyncio.gather(
            worker.stop(),
            worker.handle_update(update_user1)
        )
        await worker.start()

        game_accessor = state.store.game_accessor
        game: GameModel = await game_accessor.get_game_by_id(started_game.id)
        who_next_after_restart = game.who_next

        # проверяем, что бот пережил рестарт и завершил все таски корректно, т.е игрок должен оказаться в конце очереди.
        assert who_next_before_restart[0] == who_next_after_restart[-1]


import torch
import torchaudio
from omegaconf import DictConfig
from torchaudio.transforms import RNNTLoss

from models.decoder.transducer import TransducerJoint, RnnPredictor
from models.encoder.conformer_encoder import ConformerEncoder
from tool.common import add_blank, add_sos
from tool.loss import CTC

class ConformerTransducer(torch.nn.Module):
    def __init__(self, configs: DictConfig) -> None:
        super(ConformerTransducer, self).__init__()
        self.configs = configs

        if self.configs.weight_conf is not None:
            self.transducer_weight = self.configs.weight_conf.transducer_weight
            self.ctc_weight = self.configs.weight_conf.ctc_weight

        self.encoder_configs = self.configs.model.encoder
        self.num_classes = self.configs.model.num_classes
        self.sos_id = self.configs.tokenizer.sos_id
        self.eos_id = self.configs.tokenizer.eos_id
        self.pad_id = self.configs.tokenizer.pad_id
        self.blank_id = self.configs.tokenizer.blank_id

        self.encoder = ConformerEncoder(
            input_dim=self.encoder_configs.input_dim,
            encoder_dim=self.encoder_configs.encoder_dim,
            num_layers=self.encoder_configs.num_encoder_layers,
            num_attention_heads=self.encoder_configs.num_attention_heads,
            feed_forward_expansion_factor=self.encoder_configs.feed_forward_expansion_factor,
            input_dropout_p=self.encoder_configs.input_dropout_p,
            feed_forward_dropout_p=self.encoder_configs.feed_forward_dropout_p,
            attention_dropout_p=self.encoder_configs.attention_dropout_p,
            dropout_p=self.encoder_configs.dropout_p,
            conv_kernel_size=self.encoder_configs.conv_kernel_size,
            half_step_residual=self.encoder_configs.half_step_residual,
        )

        self.joint_configs = self.configs.model.joint

        self.joint = TransducerJoint(
            vocab_size=self.num_classes,
            enc_output_size=self.joint_configs.encoder_dim,
            pred_output_size=self.joint_configs.predictor_dim,
        )

        self.predictor_config = self.configs.model.predictor

        self.predictor = RnnPredictor(
            vocab_size=self.num_classes,
            embed_size=self.predictor_config.embed_size,
            hidden_size=self.predictor_config.hidden_size,
            output_size=self.predictor_config.predictor_dim,
            num_layers=self.predictor_config.num_layers,
            embed_dropout=self.predictor_config.embed_dropout,
            rnn_dropout=self.predictor_config.rnn_dropout,
            rnn_type=self.rnn_type,
            pad=self.pad_id,
        )

        if self.ctc_weight > 0:
            self.ctc_fc = torch.nn.Linear(self.encoder_configs.encoder_dim, self.num_classes, bias=False)
            self.ctc_criterion = CTC(blank_id=self.blank_id, reduction="mean")

        self.criterion = RNNTLoss(blank=self.blank_id, reduction="mean")

    def forward(self, speech: torch.Tensor, speech_lengths: torch.Tensor, text: torch.Tensor,
                text_lengths: torch.Tensor):
        result = dict()
        encoder_outputs, output_lengths = self.encoder(speech, speech_lengths)

        ys_in_pad = add_sos(text, sos=self.sos_id, pad=self.pad_i)
        #  [B, max_text_len + 1]

        predictor_out, hidden_states = self.predictor(ys_in_pad)

        joint_out = self.joint(encoder_outputs, predictor_out)  # [B, input_length, target_length, joint_dim]

        rnnt_text = torch.where(text == self.pad_id, self.blank_id, text).to(torch.int32)
        rnnt_text = rnnt_text.to(torch.int32)
        rnnt_text_lengths = text_lengths.to(torch.int32)
        output_lengths = output_lengths.to(torch.int32)

        transducer_loss = self.criterion(joint_out, rnnt_text, output_lengths, rnnt_text_lengths)

        result["transducer_loss"] = transducer_loss
        result["encoder_outputs"] = encoder_outputs
        result["output_lengths"] = output_lengths

        if self.ctc_weight > 0:
            logits = self.ctc_fc(encoder_outputs)
            ctc_loss = self.ctc_criterion(hs_pad=logits,
                                          ys_pad=text,
                                          h_lens=output_lengths,
                                          ys_lens=text_lengths, )
            ctc_loss = ctc_loss * self.ctc_weight
            loss = transducer_loss * self.transducer_weight + ctc_loss
            result["ctc_loss"] = ctc_loss
            result["loss"] = loss
            return loss, transducer_loss, ctc_loss

        result["loss"] = transducer_loss
        return transducer_loss


from collections.abc import Iterator
from functools import partial
from typing import Callable, Tuple

class IntcodeComputer(Iterator):
    __pc: int = 0
    __instructions = {
        '01': (3, 'add'),
        '02': (3, 'mult'),
        '03': (1, 'input_'),
        '04': (1, 'output'),
        '05': (2, 'jnz'),
        '06': (2, 'jz'),
        '07': (3, 'lt'),
        '08': (3, 'eq'),
        '99': (0, 'halt'),
    }

    def __init__(self, program: str):
        self.__program = list(map(int, program.split(',')))

    def __iter__(self):
        return self

    def __next__(self):
        if self.__pc > len(self.__program):
            print(f'pc out of range! {self.__pc}')
            self.halt()

        encoded_opc = self.__program[self.__pc]

        param_cnt, inst = self.instruction(encoded_opc)

        if param_cnt == 0:
            inst()
            return

        params = self.__program[self.__pc+1:self.__pc+1+param_cnt]
        inst(*params)

    @staticmethod
    def parse_opcode(opc: int) -> (int, int, int, str):
        A, B, C, *DE = f'{opc:05d}'
        return tuple(map(int, (C, B, A))) + (''.join(DE),)

    def instruction(self, instruction: int) -> (int, Callable[..., None]):
        decoded_instruction = self.parse_opcode(instruction)
        instruction_proto = self.__instructions[decoded_instruction[3]]

        if instruction_proto[0] == 3:
            return (
                instruction_proto[0],
                partial(
                    getattr(self, instruction_proto[1]),
                    decoded_instruction[:3]
                )
            )

        if instruction_proto[0] == 2:
            return (
                instruction_proto[0],
                partial(
                    getattr(self, instruction_proto[1]),
                    decoded_instruction[:2]
                )
            )

        if instruction_proto[0] == 1:
            return (
                instruction_proto[0],
                partial(
                    getattr(self, instruction_proto[1]),
                    decoded_instruction[0]
                )
            )

        return (0, getattr(self, instruction_proto[1]))

    def add(self, modes: Tuple[int, int, int],
            opr1: int, opr2: int, opr3: int) -> None:
        opr1_mode, opr2_mode, opr3_mode = modes

        val1 = self.get_param_value(opr1_mode, opr1)
        val2 = self.get_param_value(opr2_mode, opr2)

        self.__program[opr3] = val1 + val2
        self.__pc += 4

    def mult(self, modes: Tuple[int, int, int],
             opr1: int, opr2: int, opr3: int) -> None:
        opr1_mode, opr2_mode, opr3_mode = modes

        val1 = self.get_param_value(opr1_mode, opr1)
        val2 = self.get_param_value(opr2_mode, opr2)

        self.__program[opr3] = val1 * val2
        self.__pc += 4

    def jnz(self, modes: Tuple[int, int],
            opr1: int, opr2: int) -> None:
        opr1_mode, opr2_mode = modes

        val1 = self.get_param_value(opr1_mode, opr1)
        val2 = self.get_param_value(opr2_mode, opr2)

        if val1:
            self.__pc = val2
            return

        self.__pc += 3

    def jz(self, modes: Tuple[int, int],
            opr1: int, opr2: int) -> None:
        opr1_mode, opr2_mode = modes

        val1 = self.get_param_value(opr1_mode, opr1)
        val2 = self.get_param_value(opr2_mode, opr2)

        if not val1:
            self.__pc = val2
            return

        self.__pc += 3

    def lt(self, modes: Tuple[int, int, int],
            opr1: int, opr2: int, opr3: int) -> None:
        opr1_mode, opr2_mode, opr3_mode = modes

        val1 = self.get_param_value(opr1_mode, opr1)
        val2 = self.get_param_value(opr2_mode, opr2)

        if val1 < val2:
            self.__program[opr3] = 1
        else:
            self.__program[opr3] = 0

        self.__pc += 4

    def eq(self, modes: Tuple[int, int, int],
            opr1: int, opr2: int, opr3: int) -> None:
        opr1_mode, opr2_mode, opr3_mode = modes

        val1 = self.get_param_value(opr1_mode, opr1)
        val2 = self.get_param_value(opr2_mode, opr2)

        if val1 == val2:
            self.__program[opr3] = 1
        else:
            self.__program[opr3] = 0

        self.__pc += 4

    def input_(self, mode: int, opr: int) -> None:

        while True:
            in_val = input("input: ").rstrip()
            if not in_val.isnumeric():
                print("Invalid Input, must be numeric")
                continue
            in_val = int(in_val)
            break

        self.__program[opr] = in_val
        self.__pc += 2

    def output(self, mode: int, opr: int) -> None:
        val = self.get_param_value(mode, opr)
        print(f'output: {val:d}')
        self.__pc += 2

    def halt(self):
        print(f'final: {self.__program[0]}')
        raise StopIteration

    def get_param_value(self, mode: int, opr: int) -> int:
        if mode == 0:
            return self.__program[opr]

        if mode == 1:
            return opr

        raise RuntimeError("invalid addressing mode")

    def get_memory_by_address(self, address: int):
        if not address < len(self.__program):
            raise RuntimeError("invalid memory location!")
        return self.__program[address]

    def update_memory_by_address(self, address: int, value: int):
        if not address < len(self.__program):
            raise RuntimeError("invalid memory location!")

        self.__program[address] = value

    def run(self):
        try:
            while True:
                next(self)
        except StopIteration:
            pass

        return


# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import unittest

from unittest.mock import patch, MagicMock

from analysis_runner._version import __version__
from analysis_runner.cli import main_from_args

IMPORT_AR_IDENTITY_TOKEN_PATH = (
    'analysis_runner.cli_analysisrunner.get_google_identity_token'
)
IMPORT_CR_IDENTITY_TOKEN_PATH = 'analysis_runner.cli_cromwell.get_google_identity_token'

REQUEST_POST_PATH = 'requests.post'
REQUEST_GET_PATH = 'requests.get'
VERSION_STR = f'analysis-runner v{__version__}'

class TestCliBasic(unittest.TestCase):
    @patch('builtins.print')
    def test_version_short(self, mock_print: MagicMock):
        main_from_args(['-v'])
        mock_print.assert_called_with(VERSION_STR)

    @patch('builtins.print')
    def test_version_full(self, mock_print: MagicMock):
        main_from_args(['--version'])
        mock_print.assert_called_with(VERSION_STR)

    @patch('builtins.print')
    def test_help_short(self, mock_print: MagicMock):
        main_from_args(['-h'])
        mock_print.assert_called()

    @patch('builtins.print')
    def test_help_full(self, mock_print: MagicMock):
        main_from_args(['--help'])
        mock_print.assert_called()

class MockResponse:
    def __init__(self, **kwargs):
        self.raise_for_status = lambda: None

        for k, v in kwargs.items():
            setattr(self, k, v)

def apply_mock_behaviour(
    *, mock_post: MagicMock = None, mock_identity_token: MagicMock = None
):
    if mock_post:
        mock_post.return_value = MockResponse(text='<mocked-url>')

    if mock_identity_token:
        mock_identity_token.return_value = '<mocked-identity-token>'

class TestCliAnalysisRunner(unittest.TestCase):
    ANALYSIS_RUNNER_ARGS = [
        '--dataset',
        'fewgenomes',
        '--access-level',
        'test',
        '--description',
        'mock-test',
        '--output-dir',
        'hello-world-test',
        'echo',
        'hello-world',
    ]

    @patch(IMPORT_AR_IDENTITY_TOKEN_PATH)
    @patch(REQUEST_POST_PATH)
    def test_regular_cli(self, mock_post: MagicMock, mock_identity_token: MagicMock):
        apply_mock_behaviour(
            mock_post=mock_post, mock_identity_token=mock_identity_token
        )

        main_from_args(self.ANALYSIS_RUNNER_ARGS)

        mock_post.assert_called()
        mock_identity_token.assert_called()

    @patch(IMPORT_AR_IDENTITY_TOKEN_PATH)
    @patch(REQUEST_POST_PATH)
    def test_cli_with_mode(self, mock_post: MagicMock, mock_identity_token: MagicMock):
        apply_mock_behaviour(
            mock_post=mock_post, mock_identity_token=mock_identity_token
        )
        main_from_args(['analysis-runner', *self.ANALYSIS_RUNNER_ARGS])

        mock_post.assert_called()
        mock_identity_token.assert_called()

class TestCliCromwell(unittest.TestCase):
    @patch(IMPORT_CR_IDENTITY_TOKEN_PATH)
    @patch(REQUEST_POST_PATH)
    def test_submit_cli(self, mock_post: MagicMock, mock_identity_token: MagicMock):
        apply_mock_behaviour(
            mock_post=mock_post, mock_identity_token=mock_identity_token
        )

        args = [
            'cromwell',
            'submit',
            '--dataset',
            'fewgenomes',
            '--access-level',
            'test',
            '--description',
            'mock-test',
            '--output-dir',
            'hello-world-test',
            'workflow.wdl',
        ]

        main_from_args(args)

        mock_post.assert_called()
        mock_identity_token.assert_called()

    @patch(IMPORT_CR_IDENTITY_TOKEN_PATH)
    @patch(REQUEST_GET_PATH)
    @patch('builtins.print')
    def test_status_cli(
        self, mock_print: MagicMock, mock_get: MagicMock, mock_id_token
    ):
        apply_mock_behaviour(mock_identity_token=mock_id_token)
        cm = {
            'id': '<mocked-id>',
            'start': '2021-07-09T09:47:00.000Z',
            'end': '2021-07-09T09:48:00.000Z',
            'calls': {
                'wf.print': [
                    {
                        'name': 'print',
                        'executionStatus': 'succeeded',
                        'start': '2021-07-09T09:47:00.000Z',
                        'end': '2021-07-09T09:48:00.000Z',
                    }
                ]
            },
        }
        mock_get.return_value = MockResponse(json=lambda: cm)

        args = ['cromwell', 'status', '<mocked-id>', '--monochrome']

        status_str = """
-----------  ------------------------
Workflow ID  <mocked-id>
Name
Status       preparing
Start        2021-07-09T09:47:00.000Z
End          2021-07-09T09:48:00.000Z
Duration     1m:0s
-----------  ------------------------
Jobs:
  [#] print (1m:0s)
"""

        main_from_args(args)

        mock_get.assert_called()
        mock_print.assert_called_with(status_str)

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


def getConcatenation(nums):
        count = len(nums)
        ans = [0] * (count * 2)
        n = 0

        while n < count:
            ans[n] = ans[n + count] = nums[n]
            n += 1

        return ans

print(getConcatenation([1,2,1]))


"""
装饰器原则：
    一、不修改被修饰函数的原代码
    二、不修改被修饰函数的调用方法
高阶函数（满足其一则为高阶函数）：
    一、函数可以作为参数传给另一个函数
    二、函数的返回值为另一个函数（若返回值为该函数本身，则为递归）
"""

# ----------------符合不修改原代码(原则一)----------------
import time

def f1():
    time.sleep(1)
    print("running f1.")

def deco_1(func):  # 符合不修改被修饰函数的原代码
    print(func)  # => <function f1 at 0x0000022C6A8C56A8>
    start = time.time()
    func()  # 调用f1()
    end = time.time()
    print("运行时间 -> %s" % (end-start))  # => 运行时间1.0005557537078857

deco_1(f1)  # f1的原调用方法是f1()，但现在却是deco_1(f1)，所以不是装饰器
print()

# ----------------符合原则一、二，但会多运行一次被调用函数 (这是高阶函数的极限了)----------------
def f2():
    time.sleep(1)
    print("running f2.")

# 不修改原代码且不修改调用方法
def deco_2(func):  # 符合不修改被修饰函数的原代码
    start = time.time()
    func()  # 调用f2()
    end = time.time()
    print("运行时间%s" % (end-start))  # => 运行时间1.0005557537078857
    return func

f2 = deco_2(f2)
print("-----分隔线-----")
f2()  # 符合不修改被修饰函数的调用方法
# 但运行结果会多运行一次f2()，如下
# running f2.
# 运行时间1.0005519390106201
# -----分隔线-----
# running f2.

"""
结论：
    一、光只利用高阶函数无法实现装饰器。
        原因：装饰器由【高阶函数+函数嵌套+闭包】所组成
"""


################################################################
#Dijkstra's Algorithm to Find the shortest from any Source
################################################################
#Written by
#Avinash Shanker
#NetID: AXS8570
#ID: 1001668570
################################################################
#Usage: Run in any Python IDE and Enter inputs as below example
#Number of Nodes: 3
#Number of Connections: 3
#Node-1,Node-2,Weight: A,B,1
#Node-1,Node-2,Weight: B,C,3
#Node-1,Node-2,Weight: C,A,9
#Intermediate Output (Adjacency Matrix):
#[0, 1, 9]
#[1, 0, 3]
#[9, 3, 0]
#Enter Source Node: A
#Output from Source Node 'A':
#A-->B (A,B,1)
#A-->C (A,B,C,4)
################################################################

import ast
import os

#import ast is imported to covert input file to List type in python
#import os for file write operations and remove

#This class is used to create adjacency matrix
class Adjacency_Graph(object):
    def __init__(self, size):
        self.adjMatrix = []
        for i in range(size):
            self.adjMatrix.append([0 for i in range(size)])
        self.size = size

    #Add new edges to graph
    def addEdge(self, v1, v2,w1):
        if v1 == v2:
            print("Same vertex %d and %d" % (v1, v2))
        self.adjMatrix[v1][v2] = w1
        self.adjMatrix[v2][v1] = w1

    #Print Adjacency matrix
    def print_adj_string(self):
        f=open("adjacency.txt", "w+")
        print("\nIntermediate Output (Adjacency Matrix):")
        for row in self.adjMatrix:
            print(row)
        f.write(str(self.adjMatrix))
        print('\n')

#Converting Input Alphabet to Numeric value
def alplha_num(key_value):
    if key_value=='A' or key_value=='a' : return 0
    if key_value=='B' or key_value=='b' : return 1
    if key_value=='C' or key_value=='c' : return 2
    if key_value=='D' or key_value=='d' : return 3
    if key_value=='E' or key_value=='e' : return 4
    if key_value=='F' or key_value=='f' : return 5
    if key_value=='G' or key_value=='g' : return 6
    if key_value=='H' or key_value=='h' : return 7
    if key_value=='I' or key_value=='i' : return 8

def main():
        node=input("Number of Nodes: ")
        g = Adjacency_Graph(int(node))
        connections =input("Number of Connections: ")
        #input Node details from user
        #It must be in format A,B,Weight(eg: A,B,4)
        for x in range(0,int(connections)):
            a,b,w1 = input('Node-1,Node-2,Weight: ').split(",")
			#Converting Input alplhabets to number
            a = alplha_num(a)
            b = alplha_num(b)
            g.addEdge(int(a),int(b),int(w1));
        g.print_adj_string()

#This Class represents a Graph format and pasrsing
class Spanning_Graph:
    #Function to find the vertex with minimum distance
    def minimum_distance(self,dist,queue):
        #Initialising minimum value to minus one
        minimum = float("Inf")
        min_index = -1
        # from the dist array,pick one which
        # has min value and is till in queue
        for i in range(len(dist)):
            if dist[i] < minimum and i in queue:
                minimum = dist[i]
                min_index = i
        return min_index

    #Fucntion to return Alphabet value for Integer values
    def alplhabets(self,key_value):
        if key_value==0: return 'A'
        if key_value==1: return 'B'
        if key_value==2: return 'C'
        if key_value==3: return 'D'
        if key_value==4: return 'E'
        if key_value==5: return 'F'
        if key_value==6: return 'G'
        if key_value==7: return 'H'
        if key_value==8: return 'I'

    #Function to print shortest path  from source input from user to j
    def Display_Path(self, parent, j):
        if parent[j] == -1 :
            j_alpha = self.alplhabets(j)
			#used flush and end to keep output in same line
            print (j_alpha + ',', sep=' ', end='', flush=True),
            return
        self.Display_Path(parent , parent[j])
        j_alpha = self.alplhabets(j)
        print (j_alpha + ',', sep=' ', end='', flush=True),

    #Function is used to display the complete solution from Source Node to Destination Node
	 #Also the route and the shortest path from source to destination
    def Display_Solution(self, dist, parent,src):
        src = src
        src_alpha = self.alplhabets(src)
        print("Output from Source Node \'%s\':" % (src_alpha))
        for i in range(0, len(dist)):
            i_alpha = self.alplhabets(i)
            src_alpha = self.alplhabets(src)
            if i_alpha != src_alpha:
                print("%s-->%s (" % (src_alpha, i_alpha), sep=' ', end='', flush=True)
                self.Display_Path(parent,i)
                print("%d)" % (dist[i]))

    #This is key function which performs Dijkstra Shortest Path computation
	#Function obtains a List from a TXT file format
	#We also pass the Source Node as SRC from which shortest path is obtained for each subsequent node
    def dijkstra(self, graph, src):
        row = len(graph)
        col = len(graph[0])
        src = src
        # Initialize all distances as INFINITE initailly
        dist = [float("Inf")] * row
        #Parent array to store
        # shortest path tree
        parent = [-1] * row
        #Distance from Source to Source is Assigned to Zero
        dist[src] = 0

        queue = []
        for i in range(row):
            queue.append(i)

		#While loop will parse the entire List to find the minimum distance vertex
        while queue:
            u = self.minimum_distance(dist,queue)
            # remove min element
            queue.remove(u)

			#Checks the shortest path in given list for each iteration
            for i in range(col):
                if graph[u][i] and i in queue:
                    if dist[u] + graph[u][i] < dist[i]:
                        dist[i] = dist[u] + graph[u][i]
                        parent[i] = u
        #At the end of while loop calling print to display that path
        self.Display_Solution(dist,parent,src)

#Main Function call
if __name__ == '__main__':
   main()

g= Spanning_Graph()

#Reading the Adjacency Matrix written in the file as list and using it as input
#Direct Input can be given in the form of a file
with open('adjacency.txt', 'r') as f:
    mylist = ast.literal_eval(f.read())

graph = mylist
g.dijkstra(graph,0)
source = input("\nEnter Different Source Node: ")
source1 = alplha_num(source)
g.dijkstra(graph,int(source1))

#To Removed the file created, can be commented if you wish to view the file
#os.remove("adjacency.txt")


import sqlite3

conn = sqlite3.connect('employee.db')

c = conn.cursor()

# c.execute("""CREATE TABLE employee (
#                 first text,
#                 last text,
#                 pay integer
#                 )""")

c.execute("INSERT INTO employee VALUES ('Hekmat', 'Hamidi', 50000)")

conn.commit()
conn.close()


"""iSkyLIMS URL Configuration

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

"""iSkyLIMS URL Configuration

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

from django.urls import include, path
from django.contrib import admin
from django.contrib.auth.views import LoginView

urlpatterns = [
    path('',include('iSkyLIMS_home.urls')),
    path('background', LoginView.as_view(template_name='iSkyLIMS_home/background.html'), name="background"),
    path('bu-isciii', LoginView.as_view(template_name='iSkyLIMS_home/bu_isciii.html'), name="about-us"),
    path('faqs', LoginView.as_view(template_name='iSkyLIMS_home/faqs.html'), name="faqs"),
    path('contact', LoginView.as_view(template_name='iSkyLIMS_home/contact.html'), name="contact"),
    path('admin/', admin.site.urls),
    path('wetlab/', include('iSkyLIMS_wetlab.urls')),
    path('drylab/',include('iSkyLIMS_drylab.urls')),
    path('utils/',include('django_utils.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('tutorials/', include('zinnia.urls')),
]


"""
技評にある本のURLとタイトルがjsonファイルで出力されるよ
"""
import requests
import lxml.html
import csv
import json

url = 'https://gihyo.jp/dp'

r = requests.get(url)
rhtml = r.text

html = lxml.html.fromstring(rhtml)
html.make_links_absolute(url)

with open('booklist.json', 'w', newline="")as f:

    for a in html.cssselect('#listBook>li>a[itemprop="url"]'):
        book_url = a.get('href')

        p = a.cssselect('p[itemprop = "name"]')[0]
        title = p.text_content()

        json.dump([{'url': book_url, 'title': title}], f, ensure_ascii=False, indent=2)


from flask import session, request, redirect, url_for
from flask_admin import Admin, BaseView, AdminIndexView, expose
from app.models import User, Banned_ips
from app import db
from sqlalchemy.orm.attributes import flag_modified

def ban(user):
    user.is_banned = True
    ban = Banned_ips.query.get(1)
    print(Banned_ips.query.all())
    if not ban:
        print(12)
        ban = Banned_ips(id=1, ips={'ips': []})
        db.session.add(ban)
    #l = ban.ips
    ban.ips['ips'].extend(user.ip['ip'])
    #ban.ips['nicks'].append(user.nick)
    #ban.ips = {'ips': l['ips']), 'nicks': l['nicks']}
    print(ban.ips)
    flag_modified(ban, 'ips')
    db.session.commit()
    print(ban.ips)

def unban(user):
    user.is_banned = False
    ban = Banned_ips.query.get(1)
    for i in user.ip['ip']:
        ban.ips['ips'].remove(i)
    #ban.ips['nicks'].remove(user.nick)
    flag_modified(ban, 'ips')
    db.session.commit()

class DashboardView(AdminIndexView):
    @expose('/', methods=["POST", "GET"])
    def index(self):
        if session.get('nick'):
            user = db.session.query(User).filter(User.nick == session['nick']).first()
            if user.is_admin == True or user.nick == 'admin':
                if request.method == 'POST':
                    if request.form.get('ban'):
                        ban_user = db.session.query(User).filter(User.nick == request.form['ban']).first()
                        if ban_user and not ban_user.is_admin or ban_user.nick != 'admin':
                            ban(ban_user)
                    if request.form.get('unban'):
                        unban_user = db.session.query(User).filter(User.nick == request.form['unban']).first()
                        if unban_user and unban_user.is_banned:
                            unban(unban_user)

                return self.render('admin/dashboard_index.html')
            else:
                return redirect(url_for('index'))


"""
Setup expectations for test sub classes
Run discovery for as a prerequisite for most tests
"""
import os
from datetime import timedelta

from tap_tester.base_suite_tests.base_case import BaseCase

class CloseioBase(BaseCase):
    """
    Setup expectations for test sub classes.
    Metadata describing streams.

    A bunch of shared methods that are used in tap-tester tests.
    Shared tap-specific methods (as needed).
    """

    # REPLICATION_KEY_FORMAT = "%Y-%m-%dT00:00:00.000000Z"
    # BOOKMARK_FORMAT = "%Y-%m-%dT%H:%M:%S.%f+00:00"
    # PAGE_SIZE = 100000

    # set the default start date which can be overridden in the tests,
    # by setting the property or changing self.start_date in a test.
    start_date ='2016-07-07T00:00:00Z'

    @staticmethod
    def tap_name():
        """The name of the tap"""
        return "tap-closeio"

    @staticmethod
    def get_type():
        """the expected url route ending"""
        return "platform.closeio"

    def get_properties(self):
        """Configuration properties required for the tap."""

        return {
            # added defualt value as there is no current activity
            'start_date': self.start_date,  # '2018-03-25T00:00:00Z' for faster test runs
            'api_key': os.getenv('TAP_CLOSEIO_API_KEY')
        }

    @staticmethod
    def get_credentials():
        return {
            'api_key': os.getenv('TAP_CLOSEIO_API_KEY'),
        }

    @staticmethod
    def expected_metadata():
        """The expected streams and metadata about the streams"""
        default_expectations = {
            BaseCase.PRIMARY_KEYS: {"id"},
            BaseCase.REPLICATION_METHOD: BaseCase.INCREMENTAL,
            BaseCase.REPLICATION_KEYS: {"date_updated"},
            BaseCase.RESPECTS_START_DATE: True,
            BaseCase.API_LIMIT: 100
        }

        return {
            'activities': {
                BaseCase.PRIMARY_KEYS: {"id"},
                BaseCase.REPLICATION_METHOD: BaseCase.INCREMENTAL,
                BaseCase.REPLICATION_KEYS: {"date_created"},
                BaseCase.RESPECTS_START_DATE: True,
                BaseCase.LOOK_BACK_WINDOW: timedelta(hours=24),
                # date_window request default 15 days.
                # Make sure start date is before the date_window
                BaseCase.API_LIMIT: 100
            },
            'custom_fields': default_expectations,
            'event_log': default_expectations,
            'leads': default_expectations,
            'tasks': default_expectations,
            'users': default_expectations
        }

    @staticmethod
    def expected_automatic_fields(stream=None):

        automatic_fields = {
            'activities': {
                '_type',
                # 'activity_at',
                'attachments',
                'bcc',
                'body_html',
                'body_html_quoted',
                'body_preview',
                'body_text',
                'body_text_quoted',
                # 'bulk_email_action_id',
                # 'call_method',
                'cc',
                # 'coach_legs',
                'contact_id',
                # 'cost',
                'created_by',
                'created_by_name',
                # 'date_answered',
                'date_created',
                'date_scheduled',
                'date_sent',
                'date_updated',
                'dialer_id',
                # 'dialer_saved_search_id',
                'direction',
                # 'disposition',
                'duration',
                'email_account_id',
                'envelope',
                # 'error_message',
                # 'followup_sequence_delay',
                # 'followup_sequence_id',
                # 'forwarded_to',
                # 'has_recording',
                # 'has_reply',
                'id',
                'import_id',
                'in_reply_to_id',
                # 'is_forwarded',
                # 'is_joinable',
                # 'is_to_group_number',
                'lead_id',
                # 'local_country_iso',
                'local_phone',
                # 'local_phone_formatted',
                'message_ids',
                'need_smtp_credentials',
                # 'new_pipeline_id',
                # 'new_pipeline_name',
                'new_status_id',
                'new_status_label',
                'new_status_type',
                'note',
                # 'note_html',
                # 'old_pipeline_id',
                # 'old_pipeline_name',
                'old_status_id',
                'old_status_label',
                'old_status_type',
                'opens',
                'opens_summary',
                'opportunity_confidence',
                'opportunity_date_won',
                'opportunity_id',
                'opportunity_value',
                'opportunity_value_currency',
                'opportunity_value_formatted',
                'opportunity_value_period',
                'organization_id',
                'phone',
                # 'recording_expires_at',
                'recording_url',
                'references',
                # 'remote_country_iso',
                'remote_phone',
                # 'remote_phone_formatted',
                # 'send_as_id',
                'send_attempts',
                'sender',
                # 'sequence_id',
                # 'sequence_name',
                # 'sequence_subscription_id',
                'source',
                'status',
                'subject',
                'task_assigned_to',
                'task_assigned_to_name',
                'task_id',
                'task_text',
                'template_id',
                'template_name',
                # 'text',
                'thread_id',
                'to',
                'transferred_from',
                # 'transferred_from_user_id',
                'transferred_to',
                # 'transferred_to_user_id',
                'updated_by',
                'updated_by_name',
                'user_id',
                'user_name',
                'users',
                'voicemail_duration',
                'voicemail_url',
            },
            'custom_fields': {
                # 'accepts_multiple_values',
                # 'back_reference_is_visible',
                'choices',
                'created_by',
                'date_created',
                'date_updated',
                # 'description',
                'editable_with_roles',
                'id',
                # 'is_shared',
                'name',
                'organization_id',
                # 'referenced_custom_type_id',
                'type',
                'updated_by',
            },
            'event_log': {
                'action',
                'changed_fields',
                'data',
                'date_created',
                'date_updated',
                'id',
                'lead_id',
                'meta',
                'object_id',
                'object_type',
                'organization_id',
                'previous_data',
                'request_id',
                'user_id',
            },
            'leads': {
                'date_updated',
                'display_name',
                'addresses',
                'date_created',
                'id',
                'status_id',
                'opportunities',
                'organization_id',
                'name',
                'tasks',
                'created_by',
                'status_label',
                'integration_links',
                'contacts',
                'custom_fields',
                'url',
                'html_url',
                'description',
                'updated_by_name',
                'created_by_name',
                'updated_by',
            },
            'tasks': {
                '_type',
                'assigned_to',
                'assigned_to_name',
                'body_preview',
                'contact_id',
                'contact_name',
                'created_by',
                'created_by_name',
                'date',
                'date_created',
                'date_updated',
                'due_date',
                'email_id',
                'emails',
                'id',
                'is_complete',
                'is_dateless',
                'lead_id',
                'lead_name',
                'local_phone',
                'object_id',
                'object_type',
                'opportunity_note',
                'opportunity_value',
                'opportunity_value_currency',
                'opportunity_value_formatted',
                'opportunity_value_period',
                'organization_id',
                'phone',
                'phone_formatted',
                'phone_number_description',
                'recording_url',
                'remote_phone',
                'remote_phone_description',
                'remote_phone_formatted',
                'subject',
                'text',
                'updated_by',
                'updated_by_name',
                'view',
                'voicemail_duration',
                'voicemail_url',
            },
            'users': {
                'date_created',
                'date_updated',
                'email',
                # 'email_verified_at',
                'first_name',
                # 'google_profile_image_url',
                'id',
                'image',
                'last_name',
                'last_used_timezone',
                'organizations',
            },
        }
        if stream:
            return automatic_fields[stream]
        return automatic_fields

    # TODO - BUG it looks like there is no metadata for some fields even though they
    #   are actually replicated.  This isn't right.  Maybe it doesn't matter too much
    #   since everything is automatic but we should write this up.
    def too_many_fields_replicated(self, stream=None):
        # NOTE: This only works because all fields are automatic.
        # Otherwise I think we would need to write a workaround to change the
        # selected fields for the test with streams_to_selected_fields

        actual_expected = CloseioBase.expected_automatic_fields()
        extra_fields = {
            "users": {'google_profile_image_url', 'email_verified_at'},
            "custom_fields": {
                'accepts_multiple_values',
                'back_reference_is_visible',
                'description',
                'is_shared',
                'referenced_custom_type_id',
            },
            "activities": {
                'activity_at',
                'bulk_email_action_id',
                'call_method',
                'coach_legs',
                'cost',
                'date_answered',
                'dialer_saved_search_id',
                'disposition',
                'error_message',
                'followup_sequence_delay',
                'followup_sequence_id',
                'forwarded_to',
                'has_recording',
                'has_reply',
                'is_forwarded',
                'is_joinable',
                'is_to_group_number',
                'local_country_iso',
                'local_phone_formatted',
                'new_pipeline_id',
                'new_pipeline_name',
                'note_html',
                'old_pipeline_id',
                'old_pipeline_name',
                'recording_expires_at',
                'remote_country_iso',
                'remote_phone_formatted',
                'send_as_id',
                'sequence_id',
                'sequence_name',
                'sequence_subscription_id',
                'text',
                'transferred_from_user_id',
                'transferred_to_user_id',
            },
        }
        missing_fields = {
            "tasks": {
                'body_preview',
                'email_id',
                'emails',
                'local_phone',
                'opportunity_note',
                'opportunity_value',
                'opportunity_value_currency',
                'opportunity_value_formatted',
                'opportunity_value_period',
                'phone',
                'phone_formatted',
                'phone_number_description',
                'recording_url',
                'remote_phone',
                'remote_phone_description',
                'remote_phone_formatted',
                'subject',
                'voicemail_duration',
                'voicemail_url',
            }}
        additional_expected = {
            stream: fields.union(
                extra_fields.get(stream, set())).difference(
                missing_fields.get(stream, set()))
            for stream, fields in actual_expected.items()}
        if stream:
            return additional_expected[stream]
        return additional_expected

    @classmethod
    def setUpClass(cls, logging="Ensuring environment variables are sourced."):  # pylint: disable=invalid-name
        super().setUpClass(logging=logging)
        missing_envs = [
            x for x in [
                'TAP_CLOSEIO_API_KEY',
            ] if os.getenv(x) is None
        ]

        if len(missing_envs) != 0:
            raise ValueError(f"Missing environment variables: {missing_envs}")


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from pyecharts.charts import Bar, Page
from pyecharts import options as opts
import jieba
import wordcloud
from matplotlib import pyplot as plt

class DouYuSpider():
    def __init__(self):
        self.driver = webdriver.Chrome(
            executable_path='/Users/xiaoyuan/Downloads/chromedriver'
        )
        self.url = 'https://www.douyu.com/g_LOL'

        self.data = {">200万": 0, ">150万": 0, ">100万": 0, ">50万": 0, ">30万": 0, ">10万": 0, ">1万": 0, "1万以下": 0}
        self.title = ""
        self.page = 1

    def send_request(self):
        self.driver.get(self.url)

        time.sleep(3)
        # 滑动底部

        while True:
            time.sleep(2)
            self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
            hot_nums = self.driver.find_elements_by_css_selector('.DyListCover-hot')
            titles = self.driver.find_elements_by_css_selector('.DyListCover-intro')

            for info in zip(hot_nums, titles):
                num = info[0].text
                if "万" in num:
                    num = float(num.replace('万', "")) * 10000
                else:
                    num = int(num)

                if num >= 2000000:
                    self.data[">200万"] = self.data[">200万"] + 1
                elif num >= 1500000 and num < 2000000:
                    self.data[">150万"] = self.data[">150万"] + 1
                elif num >= 1000000 and num < 1500000:
                    self.data[">100万"] = self.data[">100万"] + 1
                elif num >= 500000 and num < 1000000:
                    self.data[">50万"] = self.data[">50万"] + 1
                elif num >= 300000 and num < 500000:
                    self.data[">30万"] = self.data[">30万"] + 1
                elif num >= 100000 and num < 300000:
                    self.data[">10万"] = self.data[">10万"] + 1
                elif num >= 10000 and num < 100000:
                    self.data[">1万"] = self.data[">1万"] + 1
                elif num >= 0 and num < 10000:
                    self.data["1万以下"] = self.data["1万以下"] + 1

                self.title += info[1].text
            # 获取下一页
            self.page += 1
            if self.page == 3:
                break
            next = self.driver.find_element_by_class_name('dy-Pagination-next')
            if next.get_attribute('aria-disabled') == 'false':
                next.click()
            else:
                break
        # 最后生成表格
        self.create_bar()
        # 词云
        self.create_wordcloud()

    def create_bar(self):
        c = Bar().add_xaxis(list(self.data.keys())).add_yaxis("斗鱼热度", list(self.data.values())).set_global_opts(
            title_opts=opts.TitleOpts(title="热度分析", subtitle="斗鱼"))
        Page().add(c).render()

    def create_wordcloud(self):
        # 中国 人民 共和国
        # 富婆 不行 太短
        words = list(jieba.cut(self.title))  # 分词
        fnl_words = [word for word in words if len(word) > 1]  # 去掉单字
        wc = wordcloud.WordCloud(width=1000, font_path='Fonts/font1.ttf', height=800)  # 设定词云画的大小字体，一定要设定字体，否则中文显示不出来
        wc.generate(' '.join(fnl_words))
        wc.to_file("danmu_pic.png")  # 保存
        # plt.imshow(wc)  # 看图

    def start(self):
        self.send_request()

if __name__ == '__main__':
    dys = DouYuSpider()
    dys.start()


"""synmod package definition and install configuration"""

from setuptools import find_packages, setup

# pylint: disable = invalid-name

with open("README.rst") as readme_file:
    readme = readme_file.read()

with open("docs/changelog.rst") as changelog_file:
    changelog = changelog_file.read()

setup(
    author="Akshay Sood",
    author_email="sood.iitd@gmail.com",
    classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "Environment :: Console",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
    ],
    description="Temporal model synthesis",
    entry_points={
        "console_scripts": [
            "synmod=synmod.master:main",
        ],
    },
    include_package_data=True,
    install_requires=[
        "cloudpickle",
        "graphviz",
        "numpy>=1.19.0",
        "scikit-learn",
        "sympy"
    ],
    keywords="synmod",
    license="MIT",
    long_description=readme + "\n\n" + changelog,
    long_description_content_type="text/plain",
    name="synmod",
    packages=find_packages(),
    python_requires=">= 3.6",
    url="https://github.com/cloudbopper/synmod",
    version="0.1.4",
    zip_safe=True,
)


import sys
import pprint

def adjacencyList(input_file):
    g = {}
    with open(input_file) as graph_input:
        for line in graph_input:
            # Split line and convert line parts to integers.
            nodes = [int(x) for x in line.split()]
            if len(nodes) != 2:
                continue
            # If a node is not already in the graph
            # we must create a new empty list.
            if nodes[0] not in g:
                g[nodes[0]] = []
            if nodes[1] not in g:
                g[nodes[1]] = []
            # We need to append the "to" node
            # to the existing list for the "from" node.
            g[nodes[0]].append(nodes[1])
            # And also the other way round.
            g[nodes[1]].append(nodes[0])
    return g

def add_last(pq, c):
    pq.append(c)

def root(pq):
    return 0

def set_root(pq, c):
    if len(pq) == 0:
        pq = [c]
    else:
        pq[0] = c

def get_data(pq, p):
    return pq[p]

def children(pq, p):
    if 2*p + 2 < len(pq):
        return [2*p + 1, 2*p + 2]
    else:
        return [2*p + 1]

def parent(p):
    return (p - 1) // 2

def exchange(pq, p1, p2):
    pq[p1], pq[p2] = pq[p2], pq[p1]

def insert_in_pq(pq, c):
    add_last(pq, c)
    i = len(pq) - 1
    while i != root(pq) and get_data(pq, i) < get_data(pq, parent(i)):
        p = parent(i)
        exchange(pq, i, p)
        i = p

def extract_last_from_pq(pq):
    return pq.pop()

def has_children(pq, p):
    return 2*p + 1 < len(pq)

def extract_min_from_pq(pq):
    c = pq[root(pq)]
    set_root(pq, extract_last_from_pq(pq))
    i = root(pq)
    while has_children(pq, i):
        # Use the data stored at each child as the comparison key
        # for finding the minimum.
        j = min(children(pq, i), key=lambda x: get_data(pq, x))
        if get_data(pq, i) < get_data(pq, j):
            return c
        exchange(pq, i, j)
        i = j
    return c

def search(pq,node,opn):
    # Search a node using recursion.
    if opn == pq[node]:
        return node
    if has_children(pq,node):
        for i in children(pq,node):
            # As pq is a min-heap it should search only if
            # the value of opn is bigger than the value of the current node
            if opn[0] >= pq[i][0]:
                res = search(pq,i,opn)
                if res is not None:
                    return res
    else:
        return None

def update(pq,opn,npn):
    # Update funtion exchanges opn to npn
    mh_position = search(pq,root(pq),opn)
    if mh_position is None:
        return
    else:
        pq[mh_position] = npn
        i = mh_position
        # Annealing in case heap is disordered
        while i != root(pq) and get_data(pq, i) < get_data(pq, parent(i)):
            p = parent(i)
            exchange(pq, i, p)
            i = p

input_file = sys.argv[1]
adjacency_List = adjacencyList(input_file)

#Initialize parameters using list comprehensions
d = [len(adjacency_List[v]) for v in range(len(adjacency_List)) ]
p = [d[v] for v in range(len(adjacency_List)) ]
core = [0 for i in range(len(adjacency_List))]
pn= [[p[v],v] for v in range(len(adjacency_List)) ]
mh = []

for v in range(0, len(adjacency_List)) :
    insert_in_pq(mh,pn[v])

while len(mh) > 0 :
    t = extract_min_from_pq(mh)
    core[t[1]] = t[0]
    if len(mh) != 0 :
        for v  in adjacency_List[t[1]]:
            d[v] = d[v] -1
            opn = [p[v],v]
            p[v] = max(t[0],d[v])
            npn = [p[v],v]
            update(mh,opn,npn)

for i in range(0,len(core)):
    print(i,core[i])


#########################################################
# Pioner P3DX - Robot Sensors and Motor Test
# (c) 2022 Djoko Purwanto, djoko@ee.its.ac.id
# Task by Muhammad Juniarto
########################################################

import sim
import sys
import time
import keyboard
import numpy as np

# == Function Definition ==
# -------------------------
def connectSimulator():
    # Close Connection
    sim.simxFinish(-1)
    # Connect to CoppeliaSIm Scene Simulation
    clientID = sim.simxStart('127.0.0.1', 19999, True, True,5000, 5)
    print(clientID)
    if clientID != -1 : print('Connected to remote API server')
    else:
        print('Connection unsuccessful, program ended.')
        sys.exit()
    return clientID

def getMotorHandle(clientID):
    _, motorLeftHandle = sim.simxGetObjectHandle(clientID, 'Pioneer_p3dx_leftMotor', sim.simx_opmode_blocking)
    _, motorRightHandle = sim.simxGetObjectHandle(clientID, 'Pioneer_p3dx_rightMotor', sim.simx_opmode_blocking)
    return motorLeftHandle,motorRightHandle

def getSensorsHandle(clientID):
    sensorsHandle = np.array([])
    for i in range(16):
        _, sensorHandle = sim.simxGetObjectHandle(clientID, 'Pioneer_p3dx_ultrasonicSensor'+str(i+1),sim.simx_opmode_blocking)
        # Ignore
        _,_,_,_,_ = sim.simxReadProximitySensor(clientID, sensorHandle, sim.simx_opmode_streaming)
        sensorsHandle = np.append(sensorsHandle, sensorHandle)
    return sensorsHandle

def getDistance(clientID, sensors):
    distances = np.array([])
    for i in range(16):
        _, detectionState, detectedPoint, _, _ = sim.simxReadProximitySensor(clientID, np.int(sensors[i]), sim.simx_opmode_buffer)
        distance = detectedPoint[2]
        if detectionState == False:
            distance = 10.0
        distances = np.append(distances, distance)
    return distances

def setRobotMotion(clientID, motors, veloCmd):
    error1 = sim.simxSetJointTargetVelocity(clientID, motors[0], 0, sim.simx_opmode_streaming)
    error2 = sim.simxSetJointTargetVelocity(clientID, motors[1], 0, sim.simx_opmode_streaming)
    return error1,error2

# == Main Program ==
print('Program Started')
# Connection to Coppelia Simulator
client_id = connectSimulator()
# -- Object Handle
motor_left_handle, motor_right_handle = getMotorHandle(client_id)
print('-----------------------')
print(motor_left_handle)
print('-----------------------')

sensors_handle = getSensorsHandle(client_id)

# -- Simulation Process
samp_time = 0.1
n = 1.
velo_zero = (0,0)
time_start = time.time()

while(True):
    t_now = time.time()-time_start
    # Command Processing
    if t_now >= samp_time*n:
        # Sensors
        object_distances = getDistance(client_id, sensors_handle)
        # Robot Motion Simulation
        #setRobotMotion(client_id,(motor_left_handle, motor_right_handle), velo_zero)
        # Update Sample
        n += 1.
        # Show Info
        print('t= ', round(t_now,2), 'front side object distance=',object_distances[3], object_distances[4])
        print('------------------------')
        print('[1st sensor] Left Sensor= ',object_distances[0])
        print('[2nd sensor] Left Sensor= ',object_distances[1])
        print('[3rd sensor] Left Sensor= ',object_distances[2])
        print('[4th sensor] Left Middle Sensor= ',object_distances[3])
        print('[5th sensor] Left Middle Sensor= ',object_distances[4])
        print('[6th sensor] Left Middle Sensor= ',object_distances[5])
        print('[7th sensor] Lef Middle Sensor= ',object_distances[6])
        print('[8th sensor] Middle Sensor= ',object_distances[7])
        print('[9th sensor] Middle Sensor= ',object_distances[8])
        print('[10th sensor] Middle Sensor= ',object_distances[9])
        print('[11th sensor] Right Middle Sensor= ',object_distances[10])
        print('[12th sensor] Right Middle Sensor= ',object_distances[11])
        print('[13th sensor] Right Middle Sensor= ',object_distances[12])
        print('[14th sensor] Right Sensor= ',object_distances[13])
        print('[15th sensor] Right Sensor= ',object_distances[14])
        print('[16th sensor] Right Sensor= ',object_distances[15])
        print('\n')

    if keyboard.is_pressed('esc'):
        err1, err2 = setRobotMotion(client_id,(motor_left_handle, motor_right_handle), velo_zero)
        _ = sim.simxStopSimulation(client_id,sim.simx_opmode_oneshot)
        print(err1,err2)
        break
    if keyboard.is_pressed('tab'):
        print("Manual Override!")

        pass

# -- Simulation Finished
sim.simxFinish(client_id)
print('Program Ended\n')


"""
Stand-alone script that scrapes a list of all Blackrock iShares ETFs into a csv file saved locally within the same folder.
This scraping is necessary because iShares' ETF details page URLs aren't a function of the ticker symbol but instead
are composed of unique fund IDs and a dash-cased long fund name.

Example URL: https://www.ishares.com/us/products/315979/ishares-virtual-work-and-life-multisector-etf
The ETF's ticker symbol is 'IWFH', but it doesn't appear in the URL.

This script is only ever run manually with the command `python download_ishares_funds_list.py`, but this is only needed
when Blackrock changes their ETF offerings, either by adding, removing, or renaming one or more of their funds.
Although this script isn't used during the fetching of ETF holdings, the `ishares_funds.csv` file it outputs is
used by the iShares fetcher.
"""

import os
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from utils.csv_writing import write_funds_to_csv

def main():
    chrome_options = Options()
    chrome_options.add_argument('--disable-extensions')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--headless')
    chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
    driver = webdriver.Chrome(executable_path=os.environ['CHROME_DRIVER_PATH'], options=chrome_options)

    funds = []
    try:
        print('Opening Selenium Webdriver...')
        driver.set_window_size(1600, 800)
        driver.get('https://www.ishares.com/us/products/etf-investments')
        show_all_button_element = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, '.show-more-or-less button'))
        )
        driver.execute_script('arguments[0].click();', show_all_button_element)

        print('Reading from funds table...')
        table_row_elements = driver.find_elements_by_css_selector('tr.desktop-table-row')
        for table_row_element in table_row_elements:
            fund_link_element = table_row_element.find_element_by_css_selector('a.tb_fundNames')
            ticker_span_element = fund_link_element.find_element_by_css_selector('.localExchangeTicker')
            ticker = ticker_span_element.text
            fund_url = fund_link_element.get_attribute('href')
            funds.append([ticker, fund_url])
    finally:
        driver.quit()

    print('Writing fund ticker symbols and URLs to csv file...')
    write_funds_to_csv(funds, 'ishares_funds.csv')
    print('Done!')

if __name__ == '__main__':
    main()


#!/usr/bin/env python
'''
Created on 28-10-2013

@author: Damian Rusinek <damian.rusinek@gmail.com>
'''

from setuptools import setup, find_packages
import os
import aqopa

def read(filename):
    with open(filename) as f:
        return f.read()

def find_library_data():
    data_files = []
    path = os.path.join('aqopa', 'library', 'models')
    for dir_name in os.listdir(path):
        dir_path = os.path.join(path, dir_name)

        if os.path.isdir(dir_path):
            dir_data_files = []
            for filename in os.listdir(dir_path):
                file_path = os.path.join(dir_path, filename)
                if os.path.isfile(file_path):
                    dir_data_files.append(file_path)
            if len(dir_data_files) > 0:
                data_files.append((dir_path, dir_data_files))
    return data_files

setup(name='AQoPA',

      version=aqopa.VERSION,
      description='Automated Quality of Protection Analysis Tool for QoP-ML models.',
      long_description=read('README.md'),
      author='Damian Rusinek',
      author_email='damian.rusinek@gmail.com',
      url='http://qopml.org/aqopa/',

      license='Freeware',
      platforms=["any"],

      install_requires=[read('requirements').split("\n")],

      packages=find_packages(),
      package_data={'aqopa' : ['bin/assets/logo.png']},
      data_files=find_library_data(),

      entry_points = {
        'console_scripts': [
            'aqopa-gui = aqopa.cmd:gui_command',
            'aqopa-console = aqopa.cmd:console_command',
        ]
      },

      classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Information Technology',
        'Intended Audience :: Science/Research',
        'Intended Audience :: System Administrators',
        'Intended Audience :: Telecommunications Industry',
        'License :: Freeware',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Scientific/Engineering :: Information Analysis',
        'Topic :: Security',
        'Topic :: Security :: Cryptography',
        'Topic :: System :: Monitoring',
      ]
     )


import torch.nn as nn
from transformers import RobertaTokenizer, RobertaModel

class RoBERTa(nn.Module):
    def __init__(self, cfg=None):
        super().__init__()
        cache_dir = '/mnt/huangjiangyong/roberta-base'
        self.tokenizer = RobertaTokenizer.from_pretrained(cache_dir)
        self.model = RobertaModel.from_pretrained(cache_dir)

    def forward(self, sentences, device=None):
        token_inputs = self.tokenizer(
            sentences,
            padding=True,
            return_tensors='pt')

        if device is None:
            token_inputs = {k: v.cuda() for k, v in token_inputs.items()}
        else:
            token_inputs = {k: v.cuda(device) for k, v in token_inputs.items()}

        outputs = self.model(**token_inputs)
        return outputs[0], token_inputs

if __name__=='__main__':
    roberta = RoBERTa().to('cuda:0')
    # seq_pair = roberta.tokenizer.encode("__bbox_begin__ pos_1 pos_10 pos_20 pos_30 __bbox_end__")
    # print(roberta.tokenizer.decode(seq_pair))
    # print(roberta(['How do you do?','I am fine thank you.']))
    print(roberta([
        'locate a blue turtle-like pokemon with round head with box',
        'locate "a blue turtle-like pokemon with round head" with box',
        'locate " a blue turtle-like pokemon with round head " with box'
    ], device='cuda:0'))


import re
from pathlib import Path

try:  # Python >= 3.11
    import re._constants as sre_constants
except ImportError:
    import sre_constants

import yaml

from prospector.finder import FileFinder
from prospector.message import Location, Message
from prospector.profiles import AUTO_LOADED_PROFILES
from prospector.tools import DEPRECATED_TOOL_NAMES, TOOLS, ToolBase, pyflakes

PROFILE_IS_EMPTY = "profile-is-empty"
CONFIG_SETTING_SHOULD_BE_LIST = "should-be-list"
CONFIG_UNKNOWN_SETTING = "unknown-setting"
CONFIG_SETTING_MUST_BE_INTEGER = "should-be-int"
CONFIG_SETTING_MUST_BE_BOOL = "should-be-bool"
CONFIG_INVALID_VALUE = "invalid-value"
CONFIG_INVALID_REGEXP = "invalid-regexp"
CONFIG_DEPRECATED_SETTING = "deprecated"
CONFIG_DEPRECATED_CODE = "deprecated-tool-code"

__all__ = ("ProfileValidationTool",)

def _tool_names(with_deprecated: bool = True):
    tools = list(TOOLS)
    if with_deprecated:
        tools += DEPRECATED_TOOL_NAMES.keys()
    return tools

class ProfileValidationTool(ToolBase):
    LIST_SETTINGS = ("inherits", "uses", "ignore", "ignore-paths", "ignore-patterns")
    BOOL_SETTINGS = ("doc-warnings", "test-warnings", "autodetect")
    OTHER_SETTINGS = (
        "strictness",
        "max-line-length",
        "output-format",
        "output-target",
        "member-warnings",
        "pep8",
        # bit of a grim hack; prospector does not use the following but Landscape does:
        # TODO: think of a better way to avoid Landscape-specific config leaking into prospector
        "python-targets",
    )
    ALL_SETTINGS = LIST_SETTINGS + BOOL_SETTINGS + OTHER_SETTINGS

    def __init__(self):
        self.to_check = set(AUTO_LOADED_PROFILES)
        self.ignore_codes = ()

    def configure(self, prospector_config, found_files):
        for profile in prospector_config.config.profiles:
            self.to_check.add(profile)

        self.ignore_codes = prospector_config.get_disabled_messages("profile-validator")

    def validate(self, filepath: Path):  # noqa
        # pylint: disable=too-many-locals
        # TODO: this should be broken down into smaller pieces
        messages = []

        with filepath.open() as profile_file:
            _file_contents = profile_file.read()
            parsed = yaml.safe_load(_file_contents)
            raw_contents = _file_contents.split("\n")

        def add_message(code, message, setting):
            if code in self.ignore_codes:
                return
            line = -1
            for number, fileline in enumerate(raw_contents):
                if setting in fileline:
                    line = number + 1
                    break
            location = Location(filepath, None, None, line, 0, False)
            message = Message("profile-validator", code, location, message)
            messages.append(message)

        if parsed is None:
            # this happens if a completely empty profile is found
            add_message(
                PROFILE_IS_EMPTY,
                f"{filepath} is a completely empty profile",
                "entire-file",
            )
            return messages

        for setting in ProfileValidationTool.BOOL_SETTINGS:
            if not isinstance(parsed.get(setting, False), bool):
                add_message(
                    CONFIG_SETTING_MUST_BE_BOOL,
                    f'"{setting}" should be true or false',
                    setting,
                )

        if not isinstance(parsed.get("max-line-length", 0), int):
            add_message(
                CONFIG_SETTING_MUST_BE_INTEGER,
                '"max-line-length" should be an integer',
                "max-line-length",
            )

        if "strictness" in parsed:
            possible_strictness = ("veryhigh", "high", "medium", "low", "verylow", "none")
            if parsed["strictness"] not in possible_strictness:
                _joined = ", ".join(possible_strictness)
                add_message(
                    CONFIG_INVALID_VALUE,
                    f'"strictness" must be one of {_joined}',
                    "strictness",
                )

        if "uses" in parsed:
            possible_libs = ("django", "celery", "flask")
            parsed_list = parsed["uses"] if isinstance(parsed["uses"], list) else [parsed["uses"]]
            for uses in parsed_list:
                if uses not in possible_libs:
                    _joined = ", ".join(possible_libs)
                    add_message(
                        CONFIG_INVALID_VALUE,
                        f'"{uses}" is not valid for "uses", must be one of {_joined}',
                        uses,
                    )

        if "ignore" in parsed:
            add_message(
                CONFIG_DEPRECATED_SETTING,
                '"ignore" is deprecated, please update to use "ignore-patterns" instead',
                "ignore",
            )

        if "python-targets" in parsed:
            python_targets = (
                parsed["python-targets"] if isinstance(parsed["python-targets"], list) else [parsed["python-targets"]]
            )

            for target in python_targets:
                if str(target) not in ("2", "3"):
                    add_message(
                        CONFIG_INVALID_VALUE,
                        f'"{target}" is not valid for "python-targets", must be either 2 or 3',
                        str(target),
                    )

        for pattern in parsed.get("ignore-patterns", []):
            try:
                re.compile(pattern)
            except sre_constants.error:
                add_message(CONFIG_INVALID_REGEXP, "Invalid regular expression", pattern)

        for key in ProfileValidationTool.LIST_SETTINGS:
            if key not in parsed:
                continue
            if not isinstance(parsed[key], (tuple, list)):
                add_message(CONFIG_SETTING_SHOULD_BE_LIST, f'"{key}" should be a list', key)

        for key in parsed.keys():
            if key not in ProfileValidationTool.ALL_SETTINGS and key not in _tool_names():
                add_message(
                    CONFIG_UNKNOWN_SETTING,
                    f'"{key}" is not a valid prospector setting',
                    key,
                )

        if "pep257" in parsed:
            add_message(
                CONFIG_DEPRECATED_CODE,
                "pep257 tool has been renamed to 'pydocstyle'. " "The name pep257 will be removed in prospector 2.0+.",
                "pep257",
            )

        if "pep8" in parsed:
            pep8val = parsed["pep8"]
            if isinstance(pep8val, dict):
                add_message(
                    CONFIG_DEPRECATED_CODE,
                    "pep8 tool has been renamed to 'pycodestyle'. "
                    "Using pep8 to configure the tool will be removed in prospector 2.0+.",
                    "pep8",
                )
            elif pep8val not in ("full", "none"):
                add_message(
                    CONFIG_UNKNOWN_SETTING,
                    f"{pep8val} is not a valid setting for pep8 - must be either 'full' or 'none'",
                    "pep8",
                )

        if "pyflakes" in parsed:
            for code in parsed["pyflakes"].get("enable", []) + parsed["pyflakes"].get("disable", []):
                if code in pyflakes.LEGACY_CODE_MAP:
                    _legacy = pyflakes.LEGACY_CODE_MAP[code]
                    add_message(
                        CONFIG_DEPRECATED_CODE,
                        f"Pyflakes {code} was renamed to {_legacy}",
                        "pyflakes",
                    )

        return messages

    def run(self, found_files: FileFinder):
        messages = []
        for filepath in found_files.files:
            for possible in self.to_check:
                if filepath == possible:
                    messages += self.validate(filepath)
                    break

        return messages


class LinkedList:

    def __init__(self, values=None):
        self.head = None
        self.tail = None
        if values:
            self.append_multiple_nodes(values)

    def __iter__(self):
        node = self.head
        while node:
            yield node.data
            node = node.next

    def __len__(self):
        length = 0
        node = self.head
        while node:
            length += 1
            node = node.next
        return length

    def __repr__(self):
        return f'LinkedList({"->".join(node.value for node in self)})'

    def append(self, value):
        if self.head is None:
            self.head = self.tail = Node(value)
        else:
            self.tail.next = Node(value)
            self.tail = self.tail.next
        return self.tail

    def append_multiple_nodes(self, values):
        try:
            for value in values:
                self.append(value)
        except TypeError:
            self.append(values)
        return self.tail

    def prepend(self, value):
        if self.head is None:
            self.head = self.tail = Node(value)
        else:
            head = Node(value)
            head.next = self.head
            self.head = head
        return self.head

    def __str__(self):
        return " -> ".join(str(node) for node in self)

    @property
    def values(self):
        return (node.value for node in self)

    def __eq__(self, other):
        if not isinstance(other, LinkedList):
            return False
        if len(self) != len(other):
            return False
        for s_node, o_node in zip(self, other):
            if s_node != o_node:
                return False
        return True

class Node:

    def __init__(self, data=None):
        self.data = data
        self.next = None

    def __str__(self):
        return str(self.data)

    def __eq__(self, other):
        if not isinstance(other, Node):
            return False
        return self.data == other.data


#coding="utf-8"
import os

from utils.spider_util import *
def parse_article_detail(detail_url):
    print('parse_detail_url is ' + detail_url)
    doc = pq(detail_url)
    return doc('div[class="article"]')('p')

def init_index_html(url):
    index_html = execute_script(url)
    with open('test.index', 'w', encoding="utf-8") as f:
        f.write(index_html)
    return index_html

if __name__ == '__main__':
    details_url =  "https://www.toutiao.com/a6540567317728723470/"
    detail_html = execute_script(details_url)
    doc = pq(detail_html)
    print(str(doc('div[class="article-content"]')('p').text()).strip())
    print(str(doc('div[class="article-content"]')).strip())

    # for item in doc('div[class="single-mode-rbox-inner"]')('div[class="title-box"]')('a').items():
    #     print(item.text(), item.attr("href"))


# EXERCISE 22 :
# write a function that takes a number, and return how many 0's are at the end of the number.

def check_number(number: int):
    """Takes a number and return the number of 0's at the end of the number."""
    str_number = str(number)
    return len(str_number) - len(str_number.rstrip("0"))

number = int(input("Enter a number : "))

ouptut = check_number(number)
print(ouptut)


'''
Create Linked List
Traverse
Delete a value
Reverse
Traverse and print
print from kth to last index of linked list
Check if is palindrome
Delete all duplicate elements from LL

@author : Pragnya Srinivasan
'''

class Node:
  def __init__(self,data):
    self.data = data
    self.next = None

class LinkedList:
  def __init__(self):
    self.head = None
    self.node = None

  def add_node(self,val):
    if self.head is None:
      self.head = Node(val)
      self.node = self.head

    else:
      new_node = Node(val)
      self.node.next = new_node
      self.node = new_node

  def get_list(self,k=None):
    curr = self.head
    temp=None
    i = 0
    if k :
      while curr:
        if i == k:
          temp = curr
        curr = curr.next
        i = i+1

    else:
      temp = self.head

    # if temp is None even if k is given ,
    # k is not within the len of linked list
    while temp:
      yield temp.data
      temp = temp.next

  def remove_node(self,val):
    temp = self.head
    while temp:
      if temp.data == val:
        if not temp.next:
          #temp.data = None
          self.head = None
        else:
          temp.data = temp.next.data
          temp.next = temp.next.next
        return

      elif temp.next.data == val:
        temp.next = temp.next.next
        return
      else:
        temp = temp.next

  def reverse_ll(self):
    temp = self.head
    prev = None
    # Needs atleast 2 linked list elemets to reverse
    if not temp.next:
      return

    while temp:
      t_d = temp.next
      temp.next = prev
      prev = temp
      temp = t_d
    self.head = prev

  #Delete all duplicate elements from linked list
  def delete_duplicate(self):
    llist = list(self.get_list())
    dup = set()
    # find all duplicate elemts in list
    for i in range(len(llist)-1):
      if llist[i] in llist[1+1:]:
        dup.add(llist[i])

    temp = self.head
    # Append first element of the ll
    while temp:
      if temp.data in dup:
        if not temp.next:
          self.head = None
          return
        else:
          temp.data = temp.next.data
          temp.next = temp.next.next
      else :
        temp = temp.next

  def is_palindrome(self):
    li_list = list(self.get_list())
    print(li_list)
    j = len(li_list)-1
    print(j)
    for i in range(len(li_list)):
      if i>=j :
        break
      elif li_list[i] != li_list[j]:
        return("Not a Palindrome")
      j = j-1
    return("Is a Palindrome")

llist = LinkedList()
llist.add_node(1)
#print(list(llist.get_list()))
llist.add_node(2)
print(list(llist.get_list()))
llist.add_node(3)
llist.add_node(4)
print(list(llist.get_list()))
llist.remove_node(2)
print(list(llist.get_list()))
llist.remove_node(1)
llist.remove_node(3)
llist.remove_node(4)
print(list(llist.get_list()))
llist.add_node(1)
llist.add_node(2)
llist.add_node(3)
llist.add_node(3)
llist.add_node(2)
llist.add_node(11)
print(list(llist.get_list()))
llist.reverse_ll()
print(list(llist.get_list()))

# Print from kth index to last
print(list(llist.get_list(3)))
#Check if palindrome
print(llist.is_palindrome())
# Delete all elemnts in list that occur more than once
llist.delete_duplicate()
print(list(llist.get_list()))