import socket
import time
import argparse

IP   = "172.21.72.133"
# IP   = "192.168.1.71"

PORT = 8080

# msg = 0
# cc = bytes([msg])
parser = argparse.ArgumentParser()
parser.add_argument("msg")
args = parser.parse_args()
msg = str(args.msg)
cc = msg.encode()

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as opened_socket:
    opened_socket.setblocking(0)
    opened_socket.sendto(cc, (IP, PORT))


n=int(input("Ile liczb chcesz wczytac ?\n"))
tab=[]
for x in range(0,n):
	tab.append(int(input()))
liczba=0
for x in tab:
	if liczba==0:
		lider=x
		liczba=1
	elif lider==x:
		liczba+=1
	else:
		liczba-=1
liczba=0
for x in tab:
	if x==lider:
		liczba+=1
if liczba>n/2:
	print("\nLider to ",lider)
else:
	print("Brak lidera")


import socket
#import json
import threading,queue
import logging
import sys, time
import select
import pickle
logger=logging.getLogger(__name__)
#logger.setLevel(logging.DEBUG)
logger.setLevel(logging.INFO)

class JSONBackAndForth2:

    def __init__(self,debug=False,maxsize=10):
        self.debug=debug
        self.sock=None
        self.server_sock=None
        self.should_quit = False
        self.input_queue=queue.Queue(maxsize=maxsize)
        self.output_queue=queue.Queue(maxsize=maxsize)
        self.sender_thread=None
        self.recver_thread=None

    def join(self):
        self.should_quit=True
        if self.sender_thread is not None:
            self.sender_thread.join()
        if self.recver_thread is not None:
            self.recver_thread.join()
        if self.sock is not None:
            self.sock.close()
        if self.server_sock is not None:
            self.server_sock.close()

    def start_client(self,host,port):
        self.host=host
        self.port=port
        #connect to server
        logger.info("creating client socket")
        self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.sock.settimeout(5)
        logger.info("connecting")
        conninfo= self.sock.connect((self.host,self.port))

        logger.info("starting thread")

        self.sender_thread = threading.Thread(target=self._sender_thread_loop)
        self.sender_thread.daemon = True
        self.sender_thread.start()

        self.recver_thread = threading.Thread(target=self._recver_thread_loop)
        self.recver_thread.daemon = True
        self.recver_thread.start()

    def start_server(self,port):
        logger.info("creating server socket")
        self.host = "10.0.0.4"
        self.port=port
        self.server_sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        self.server_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        #self.server_sock=socket.create_server( (self.host,self.port), reuse_port=True )
        self.server_sock.settimeout(5)
        logger.info("binding to {} {}".format(self.host,port))
        self.server_sock.bind((self.host, port))

        logger.info("listening")
        self.server_sock.listen(1) #accept only one connection at a time
        logger.info("thread starting")
        self.thread = threading.Thread(target=self._thread_loop_server)
        self.thread.daemon = True
        self.thread.start()

    def _sender_thread_loop(self):
        #Should I do this?  Clear the output queue at the beginning
        #of connection in case stuff built up in the interim
        while not self.output_queue.empty():
            self.output_queue.get(block=False)
        while not self.should_quit:
            to_send=[]
            try:
                to_send.append(self.output_queue.get(timeout=1))
                while not self.output_queue.empty():
                    to_send.append(self.output_queue.get_nowait())
                #tosend=(json.dumps(to_send)).encode()
                tosend=(pickle.dumps(to_send))

                length=len(tosend).to_bytes(4,byteorder='big')
                self.sock.sendall(length)
                self.sock.sendall(tosend)
            except queue.Empty:
                ...
            except socket.error as e:
                logger.error("sender socket error {}, closing".format(e))
                break

    def _thread_loop_server(self):
        while not self.should_quit:
            logger.debug("accepting")
            try:
                (self.sock, address) = self.server_sock.accept()

                self.sender_thread = threading.Thread(target=self._sender_thread_loop)
                self.sender_thread.daemon = True
                self.sender_thread.start()

                self.recver_thread = threading.Thread(target=self._recver_thread_loop)
                self.recver_thread.daemon = True
                self.recver_thread.start()

                self.sender_thread.join()
                self.recver_thread.join()
                self.sock.close()
                self.sock=None
            except socket.timeout:
                ... #this is fine, just retry
            except Exception as e:
                logger.warning("unhandled exception in accept, closing connection")
                logger.warning("{}".format(e))

                #self.should_quit=True
        self.server_sock.close()

    def _recver_thread_loop(self):
        while not self.should_quit:
            inputs=[self.sock]
            readable, writable, exceptional = select.select(inputs, [], inputs,5) #timeout 5 seconds
            if self.sock in exceptional:
                logger.error("Exception in socket")
            if self.sock in readable:
                try:
                    length=self.sock.recv(4)
                    if length==b'':
                        logger.info("Closing connection to ".format(self.host))
                        break
                    read_size=int.from_bytes(length,byteorder='big')
                    logger.debug("readed length {}".format(read_size))
                    data=b''
                    while(read_size>0):
                        newdata=self.sock.recv(read_size)
                        if newdata==b'':
                            logger.info("Closing connection to ".format(self.host))
                            break
                        data+=newdata
                        read_size=read_size-len(newdata)
                except Exception as error:
                    logger.error("Recvr error, closing")
                    break
                try:
                    #json_strings=data.decode().split('\n') #andle multiple messages all in one go
                    #json_string=data.decode() #andle multiple messages all in one go
                    #json_strings.pop(-1)
                    #for s in json_strings:
                        #logger.debug("message is {}".format(s))
                    #datastructure=json.loads(json_string+'\n')
                    datastructure=pickle.loads(data)
                    #if "tracks" not in datastructure:
                    for elem in datastructure:
                        self.input_queue.put(elem)
                    #else:
                    #    logger.info("tracks discarded")
                except Exception as error:
                    logger.error("Error parsing pickle")
                    logger.exception(error)

if __name__ == '__main__':
    #logger.basicConfig(level=logging.WARNING)
    test_port=23033
    if sys.argv[1]=='server':
        server=JSONBackAndForth2(debug=True)
        print("starting server")
        server.start_server(test_port)
        print("server started")
        last_send=0
        try:
            while True:
                time.sleep(0.01)
                if time.time()>last_send+1:
                    server.output_queue.put({"body": "from server"})
                    last_send=time.time()
                    #print("server sends")
                if not server.input_queue.empty():
                    print("message receieved: {} ".format(server.input_queue.get()))
        except KeyboardInterrupt:
            logger.error("Keyboard interrupt")
            server.join()

    elif sys.argv[1]=='client':
        try:
            client=JSONBackAndForth2()
            #client.start_client('localhost',test_port)
            client.start_client("10.0.0.4",test_port)
            print("client started")
            last_send=0
            while True:
                time.sleep(0.01)
                if time.time()>last_send+1.15:
                    client.output_queue.put({"body": "from client"})
                    last_send=time.time()
                    #print("client sends")
                if not client.input_queue.empty():
                    print("message receieved: {}".format(client.input_queue.get()))
        except KeyboardInterrupt:
            logger.error("Keyboard interrupt")
            client.join()
    else:
        print("don't know how to {}".format(sys.argv[1]))


from __future__ import print_function
from pytraj import io as mdio

@profile
def test_0():
    traj = mdio.iterload("./data/md1_prod.Tc5b.x", "./data/Tc5b.top")
    fa = traj[:]
    fa._fast_strip_atoms("@CA")

    # must raise ValueError if strip the same atom mask again
    # (there is no @CA anymore)
    #fa._fast_strip_atoms("@CA"))

if __name__ == "__main__":
    test_0()


#!/usr/local/bin/python

#coding :utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""对应于save x
"""
from QUANTTOOLS.QAStockETL import (QA_SU_save_index_technical_index_day,
                                   QA_SU_save_index_technical_week_day,
                                   QA_SU_save_index_info)
from QUANTAXIS.QASU.main import (QA_SU_save_index_day,QA_SU_save_index_list)
from QUANTTOOLS.QAStockETL.Check import (check_index_day)
from QUANTTOOLS.QAStockETL.Check import (check_index_techindex, check_index_techweek)
from QUANTTOOLS.QAStockETL import (QA_etl_index_technical_day,
                                   QA_etl_index_technical_week)
from QUANTAXIS.QAUtil import QA_util_today_str,QA_util_if_trade
from QUANTTOOLS.QAStockETL.QAUtil.QADate_trade import QA_util_get_real_date
from datetime import datetime

if __name__ == '__main__':
    mark_day = QA_util_today_str()

    if QA_util_if_trade(mark_day):

        QA_SU_save_index_list('tdx')
        QA_SU_save_index_info()

        res = check_index_day(mark_day)
        while res is None or (len(res[0]) + len(res[1])) > 100:
            QA_SU_save_index_day('tdx')
            res = check_index_day(mark_day)

        res = check_index_techindex(mark_day)
        while res is None or (len(res[0]) + len(res[1])) > 100:
            QA_SU_save_index_technical_index_day(start_date = mark_day, end_date = mark_day)
            res = check_index_techindex(mark_day)

        QA_etl_index_technical_day(mark_day, mark_day)

    if datetime.strptime(mark_day,'%Y-%m-%d').weekday() + 1 == 5:
        if QA_util_if_trade(mark_day):
            mark_day = mark_day
        else:
            mark_day = QA_util_get_real_date(mark_day)
        QA_SU_save_index_technical_week_day(start_date = mark_day, end_date = mark_day)

        QA_etl_index_technical_week(mark_day,  mark_day)


import re
from random import randrange

from diversificator.Generator import Generator
from diversificator.SimpleObfuscator import SimpleObfuscator

class StructureObfuscator(SimpleObfuscator):
    # Критичность взлома
    __Q = 0.02
    __operators = ['+', '*', '/', '-']

    def set_Q(self, Q):
        self.__Q = Q

    def __get_spaces(self, start):
        matches = [m.start() for m in re.finditer('\n\n\n', self._SimpleObfuscator__code)]
        new_matches = []
        for match in matches:
            if match > start:
                new_matches.append(match)

        return new_matches

    @staticmethod
    def get_involution(convolution):
        involution = convolution[1]
        i = 0
        while involution.find('{space}') != -1:
            involution = involution.replace('{space}', convolution[0][i], 1)
            i += 1
        return involution

    @staticmethod
    def get_convolution(function_call):
        # Получение строки аргументов
        arguments_string = function_call[function_call.find('(') + 1:-1]
        count = 0
        start = 0
        end = 0
        temp = []
        # Свертка скобок
        while arguments_string.find('(') != -1:
            for i in range(len(arguments_string)):
                if arguments_string[i] == '(':
                    if count == 0:
                        start = i
                    count += 1
                elif arguments_string[i] == ')':
                    count -= 1
                    if count == 0:
                        end = i
                        temp.append(arguments_string[start:end + 1])
                        arguments_string = arguments_string[0:start] + '{space}' + arguments_string[
                                                                                end + 1:len(arguments_string)]
                        break
        return temp, arguments_string

    def obfuscate(self):
        defenitions = self._SimpleObfuscator__get_function_defenitions()
        print(defenitions)
        function_texts = []
        for defenition in defenitions:
            print(defenition + '------------------------------------------')
            # Определим количество переменных
            variable_names = self._SimpleObfuscator__get_variable_defenitions_inside(defenition)
            if variable_names == ['']:
                variable_count = 0
            else:
                variable_count = len(variable_names)

            entries = self._SimpleObfuscator__get_function_entries(defenition)
            print(entries)
            coordinates = entries[1]
            entries = entries[0]
            space = 0
            if len(entries) != 0:
                # Определяем минимальное и максимальное количество функций-посредников
                min_function_count = int(self.__Q * 100) - int(self.__Q * 100 / 2)
                max_function_count = int(self.__Q * 100) + int(self.__Q * 100 / 2)
                # Генерируем цепочку функций-посредников
                next_function_name = Generator.generate_random_name(10, 15)
                function_count = randrange(min_function_count, max_function_count + 1)
                inverse_transmutation = [''] * variable_count
                first_function_name = ''
                temp_function_text = []
                for i in range(function_count):
                    arguments = ''
                    transmutated_arguments = ''
                    for j in range(variable_count):
                        argument_name = Generator.generate_random_name(10, 15)
                        operator = self.__operators[randrange(0, 4)]
                        number = randrange(1, 100)
                        transmutation_string = operator + ' ' + str(number)
                        # Заносим обратное преобразование в массив
                        if operator == '+':
                            inverse_operator = '-'
                        elif operator == '-':
                            inverse_operator = '+'
                        elif operator == '*':
                            inverse_operator = '/'
                        else:
                            inverse_operator = '*'

                        inverse_transmutation[j] = ' ' + inverse_operator + ' ' + str(number) + ')' + \
                                                   inverse_transmutation[j]

                        if i == function_count - 1:
                            transmutated_argument = 'ctypes.cast(int(round(' + argument_name + ' ' + transmutation_string + \
                                                    ')), ctypes.py_object).value'
                        else:
                            transmutated_argument = argument_name + ' ' + transmutation_string
                        if j != variable_count - 1:
                            arguments += argument_name + ', '
                            transmutated_arguments += transmutated_argument + ', '
                        else:
                            arguments += argument_name
                            transmutated_arguments += transmutated_argument

                    function_name = next_function_name
                    next_function_name = Generator.generate_random_name(10, 15)
                    if i == 0:
                        first_function_name = function_name
                    new_function_text = 'def ' + function_name + '(' + arguments + '):\n'
                    if i == function_count - 1:
                        new_function_text += '    return ' + defenition + '(' + transmutated_arguments + ')'
                    else:
                        new_function_text += '    return ' + next_function_name + '(' + transmutated_arguments + ')'
                    new_function_text += '\n\n\n'
                    temp_function_text.append(new_function_text)

                function_texts.append(temp_function_text)
                print(inverse_transmutation)
                # Поиск вызовов функции и замена имени функции и параметров
                print(entries)
                s = 0
                for entry in entries:
                    convolution = self.get_convolution(entry)
                    arguments = convolution[1].split(',')
                    for i in range(len(arguments)):
                        arguments[i] = arguments[i].strip()
                    arguments_string = ''

                    for i in range(len(arguments)):
                        # Получаем количество закрывающихся скобок, чтобы записать открывающиеся
                        if len(inverse_transmutation):
                            open_brackets = inverse_transmutation[i].count(')')
                        else:
                            open_brackets = 0
                        if arguments != ['']:
                            for j in range(open_brackets):
                                arguments_string += '('
                            if i < len(arguments) - 1:
                                arguments_string += 'id(' + arguments[i] + ')' + inverse_transmutation[i] + ', '
                            else:
                                arguments_string += 'id(' + arguments[i] + ')' + inverse_transmutation[i]
                    print(first_function_name)
                    print('involution=', self.get_involution((convolution[0], arguments_string)))
                    new_call = first_function_name + '(' + self.get_involution((convolution[0], arguments_string)) + ')'
                    print(new_call)
                    # Замена вхождения вызова функции в код на новый вызов
                    function_name = entry[:entry.find('(')]
                    print('function name =', function_name)
                    function_entries = self._SimpleObfuscator__get_function_entries(function_name)
                    print('function_entries =', function_entries)
                    function_coordinates = function_entries[1]
                    self._SimpleObfuscator__code = self._SimpleObfuscator__code[:function_coordinates[0][
                        0]] + new_call + self._SimpleObfuscator__code[function_coordinates[0][1]:]
                    s += 1
        print(function_texts)
        for i in range(len(function_texts)):
            for j in range(len(function_texts[i])):
                # Вставка функции в код
                spaces = self.__get_spaces(0)
                index = randrange(0, len(spaces))
                space = spaces[index] + 3
                self._SimpleObfuscator__code = self._SimpleObfuscator__code[
                                               :space] + function_texts[i][j] + self._SimpleObfuscator__code[space:]
        return 'import ctypes\n\n\n' + self._SimpleObfuscator__code


#Autor: Diego Castillejo
#Udacity - Programming for Data Science with Python

import time
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }
#print(CITY_DATA)

MONTH_LIST = ['All months', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
#print(MONTH_LIST[0])

DAY_LIST = ['All days', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
#print(DAY_LIST[0])

#-------------

def get_city():

    city       = 0
    city_name  = ""

    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    while not (city >= 1 and city <=3) : #{     -- Note in Spanish: Estoy acostumbrado a los corchetes T.T
        print("Please choose your city: \n")

        print("Press 1 to Chicago.")
        print("Press 2 to New York.")
        print("Press 3 to Washington.")

        print("     (only press one number)     \n")

        city = int(input())

        if not(city >= 1 and city <=3) :
            print("\n Only 1, 2 or 3... Try again!")
            #End if

    #} End while
    if city == 1:
        print("Chicago, Great! \n")
        city_name = "chicago"
    elif  city == 2:
        print("NY, Perfect! \n")
        city_name = "new york city"
    else :
        print("Washington, OK! \n")
        city_name = "washington"

    return city_name
#End get_city

def get_month():

    month       = -1
    #month_name  = ""

    # TO DO: get user input for month (all, january, february, ... , june)
    print("Now, choose your month: \n")

    while not(month >= 0 and month <=12) :
        print("Press: 1 to Jan., 2 to Feb., 3 to Mar., ..., 12 to Dec Or you can press 0 to All months.")
        print("     (only press one number)     \n")

        month = int(input())

        if not(month >= 0 and month <=12) :
            print("\n Only numbers into 0, to 12, Try again!")
            #End if
    #End while
    print("You select: " + MONTH_LIST[month] + ", Good \n ")

    return MONTH_LIST[month]
#End get_month

def get_day():

    day         = -1
    #day_name  = ""

    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    print("Finaly, select the day of the week: \n")

    while not(day >= 0 and day <=7) :
        print("Press: 1 to Mon., 2 to Tue., 3 to Wed., 4 to Thu., 5 to Fri., 6 to Sat, 7 to Sun Or you can press 0 to All days.")
        print("     (only press one number)     \n")

        day = int(input())

        if not(day >= 0 and day <=7) :
            print("\n Only numbers into 0, to 7, Try again!")
            #End if
    #End while
    print("You select: " + DAY_LIST[day] + " \n ")

    return DAY_LIST[day]
#End get_day

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """

    # Inicialización de Variables:

    city  = ""
    month = ""
    day   = ""

    print('Hello! Let\'s explore some US bikeshare data! \n')

    city = get_city() # TO DO: get user input for city (chicago, new york city, washington).
    month = get_month() # TO DO: get user input for month (all, january, february, ... , june)
    day = get_day() # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)

    print('-'*40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """

    return df

def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # TO DO: display the most common month

    # TO DO: display the most common day of week

    # TO DO: display the most common start hour

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # TO DO: display most commonly used start station

    # TO DO: display most commonly used end station

    # TO DO: display most frequent combination of start station and end station trip

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # TO DO: display total travel time

    # TO DO: display mean travel time

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def user_stats(df):
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # TO DO: Display counts of user types

    # TO DO: Display counts of gender

    # TO DO: Display earliest, most recent, and most common year of birth

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)

        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break

if __name__ == "__main__":
	main()


try:
    import sys, string, os, arcpy, traceback, math

    def AddAndSubtractRadians(theta):
        return (theta + 1.57079632679, theta - 1.57079632679)
    def Distance(x1, y1, x2, y2):
        '''Cartesian distance formula'''
        return float(math.pow(((math.pow((x2-x1),2)) + (math.pow((y2 - y1),2))),.5))
    def CartesianToPolar(xy1, xy2):
        '''Given coordinate pairs as two lists or tuples, return the polar
        coordinates with theta in radians. Values are in true radians along the
        unit-circle, for example, 3.14 and not -0 like a regular python
        return.'''
        try:
            x1, y1, x2, y2 = float(xy1[0]), float(xy1[1]), float(xy2[0]), float(xy2[1])
            xdistance, ydistance = x2 - x1, y2 - y1
            distance = math.pow(((math.pow((x2 - x1),2)) + (math.pow((y2 - y1),2))),.5)
            if xdistance == 0:
                if y2 > y1:
                    theta = math.pi/2
                else:
                    theta = (3*math.pi)/2
            elif ydistance == 0:
                if x2 > x1:
                    theta = 0
                else:
                    theta = math.pi
            else:
                theta = math.atan(ydistance/xdistance)
                if xdistance > 0 and ydistance < 0:
                    theta = 2*math.pi + theta
                if xdistance < 0 and ydistance > 0:
                    theta = math.pi + theta
                if xdistance < 0 and ydistance < 0:
                    theta = math.pi + theta
            return [distance, theta]
        except:
            gPrint("Error in CartesianToPolar()")
    def PolarToCartesian(polarcoords):
        '''A tuple, or list, of polar values(distance, theta in radians) are
        converted to cartesian coords'''
        r = polarcoords[0]
        theta = polarcoords[1]
        x = r * math.cos(theta)
        y = r * math.sin(theta)
        return [x, y]
    def gPrint(string):
        #print string
        arcpy.AddMessage(string)

    def stringToBoolean(x):
        if x == 'true':
             x = True
        else:
             x = False
        return x

    gPrint("\n      Runing...Create Perpendicular Lines At The End Point of Line Features")
    gPrint("      A Two-Bit Algorithms product.\n      Copyright 2011 Gerry Gabrisch (gerry@gabrisch.us)\n")
    infc = arcpy.GetParameterAsText(0)
    distance = arcpy.GetParameterAsText(1)
    fcname = arcpy.GetParameterAsText(2)
    leftside = arcpy.GetParameterAsText(3)
    rightside = arcpy.GetParameterAsText(4)
    bothsides = arcpy.GetParameterAsText(5)
    makeperptoend = arcpy.GetParameterAsText(6)

    leftside = stringToBoolean(leftside)
    rightside = stringToBoolean(rightside)
    bothsides = stringToBoolean(bothsides)
    makeperptoend = stringToBoolean(makeperptoend)

    gPrint("      Cracking Features...")

    #Get the input line files geometry as a python list.
    desc = arcpy.Describe(infc)
    shapefieldname = desc.ShapeFieldName
    rows = arcpy.SearchCursor(infc)

    listofpointgeometry = []
    gPrint("      Finding points...")
    for row in rows:
        feat = row.getValue(shapefieldname)
        midpointDistance = (feat.length/2)
        partnum = 0
        partcount = feat.partCount
        thisrecordsgeometry = []

        while partnum < partcount:
            part = feat.getPart(partnum)
            pnt = part.next()
            pntcount = 0
            while pnt:
                thetuple = [pnt.X, pnt.Y]
                thisrecordsgeometry.append(thetuple)
                pnt = part.next()
                pntcount += 1
            partnum += 1

        if makeperptoend:
            startnode = [thisrecordsgeometry[-2][0], thisrecordsgeometry[-2][1]]
        else:
            startnode = [thisrecordsgeometry[0][0], thisrecordsgeometry[0][1]]

        endnode = [thisrecordsgeometry[-1][0], thisrecordsgeometry[-1][1]]

        listofpointgeometry.append([startnode,endnode])

    #Create the data models to store the new geometery....
    featureList = []
    array = arcpy.Array()
    pnt = arcpy.Point()
    gPrint("      Defining Perpendicular Lines...")
    for pt in listofpointgeometry:
        startx = pt[0][0]
        starty = pt[0][1]
        endx = pt[1][0]
        endy = pt[1][1]

        #use the start point and end point to get a theta
        polarcoor = CartesianToPolar((startx,starty), (endx,endy))

        #Add and subtract the 90 degrees in radians from the line...
        ends = AddAndSubtractRadians(polarcoor[1])

        firstend = PolarToCartesian((float(distance),float(ends[0])))
        secondend = PolarToCartesian((float(distance),float(ends[1])))

        firstx2 = endx + firstend[0]
        firsty2 = endy + firstend[1]

        secondx2 = endx + secondend[0]
        secondy2 = endy + secondend[1]

        if bothsides:
            pnt.X, pnt.Y = firstx2 , firsty2
            array.add(pnt)
            pnt.X, pnt.Y = secondx2 , secondy2
            array.add(pnt)
            polyline = arcpy.Polyline(array)
            array.removeAll()
            featureList.append(polyline)

        if leftside:
            pnt.X, pnt.Y = endx , endy
            array.add(pnt)
            pnt.X, pnt.Y = firstx2 , firsty2
            array.add(pnt)
            polyline = arcpy.Polyline(array)
            array.removeAll()
            featureList.append(polyline)

        if rightside:
            pnt.X, pnt.Y = pnt.X, pnt.Y = endx , endy
            array.add(pnt)
            pnt.X, pnt.Y = secondx2 , secondy2
            array.add(pnt)
            polyline = arcpy.Polyline(array)
            array.removeAll()
            featureList.append(polyline)
    gPrint("      Creating New Feature Class...")
    arcpy.CopyFeatures_management(featureList, fcname)
    spatialRef = arcpy.Describe(infc).spatialReference
    arcpy.DefineProjection_management(fcname, spatialRef)

    gPrint ("      Done")

except arcpy.ExecuteError:
    msgs = arcpy.GetMessages(2)
    arcpy.AddError(msgs)
    gPrint(msgs)
except:
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
    msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
    arcpy.AddError(pymsg)
    arcpy.AddError(msgs)
    gPrint(pymsg + "\n")
    gPrint (msgs)


# coding: utf-8

# In[1]:

from sklearn.externals import joblib
import numpy
from collections import Counter
from sklearn.metrics import confusion_matrix

# In[6]:

X_test_st = numpy.load('../data/X_test_st.npy')
X_test_we = numpy.load('../data/X_test_we.npy')
y_test_pos = numpy.load('../data/y_test_pos.npy')
y_test_dep = numpy.load('../data/y_test_dep.npy')
X_test_words = numpy.load('../data/X_test_words.npy')

# In[3]:

dep_baseline = joblib.load('../models/dep_logisticregression_b.estimator')
dep_classifier = joblib.load('../models/dep_logisticregression.estimator')
pos_baseline = joblib.load('../models/pos_logisticregression_b.estimator')
pos_classifier = joblib.load('../models/pos_linearsvc.estimator')

# In[4]:

y_pred_pos = pos_classifier.predict(X_test_st)
y_pred_pos_baseline = pos_baseline.predict(X_test_we)

# In[16]:

for i, y in enumerate(y_test_pos):
    if y == "VERB" and y_pred_pos[i] == y and y_pred_pos_baseline[i] != y:
        print(X_test_words[i], " ".join(X_test_words[i-10:i+10]))

# In[14]:

for i, y in enumerate(y_test_pos):
    if y == "PART" and y_pred_pos[i] == y and y_pred_pos_baseline[i] != y:
        print(X_test_words[i], y_pred_pos[i], y_pred_pos_baseline[i], " ".join(X_test_words[i-10:i+10]))

# In[18]:

for i, y in enumerate(y_test_pos):
    if y == "NOUN" and y_pred_pos[i] == y and y_pred_pos_baseline[i] == "VERB":
        print(X_test_words[i],
              y_pred_pos[i],
              y_pred_pos_baseline[i],
              " ".join(X_test_words[i-10:i+10]))


import unittest
from random import randint
from mcapi import api
from mcapi import set_remote_config_url, get_remote_config_url
from mcapi import create_project
from mcapi import Template

url = 'http://mctest.localhost/api'

def fake_name(prefix):
    number = "%05d" % randint(0, 99999)
    return prefix+number

class TestProcess(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        set_remote_config_url(url)
        cls.base_project_name = fake_name("TestProject-")
        description = "Test project generated by automated test"
        cls.base_project = create_project(cls.base_project_name, description)
        cls.base_project_id = cls.base_project.id
        name = fake_name("TestExperiment-")
        description = "Test experiment generated by automated test"
        cls.base_experiment = cls.base_project.create_experiment(name, description)
        cls.base_experiment_id = cls.base_experiment.id

    def test_is_setup_correctly(self):
        self.assertIsNotNone(self.base_project)
        self.assertIsNotNone(self.base_project.name)
        self.assertEqual(self.base_project_name, self.base_project.name)
        self.assertIsNotNone(self.base_project.id)
        self.assertEqual(self.base_project_id, self.base_project.id)
        self.assertIsNotNone(self.base_experiment)
        self.assertIsNotNone(self.base_experiment.id)
        self.assertEqual(self.base_experiment_id, self.base_experiment.id)

    def test_process_from_template_for_create_sample(self):
        process = self.base_experiment.create_process_from_template(Template.create)
        self.assertIsNotNone(process)
        self.assertIsNotNone(process.id)
        self.assertIsNotNone(process.process_type)
        self.assertEqual(process.process_type, 'create')
        self.assertTrue(process.does_transform)

    def test_process_from_template_for_computation(self):
        process = self.base_experiment.create_process_from_template(Template.compute)
        self.assertIsNotNone(process)
        self.assertIsNotNone(process.id)
        self.assertIsNotNone(process.process_type)
        self.assertEqual(process.process_type, 'analysis')
        self.assertFalse(process.does_transform)


import json

import random
import os
import h5py
import numpy as np

import torch
from torch.utils.data import Dataset

class VideoDataset(Dataset):

    def get_vocab_size(self):
        return len(self.get_vocab())

    def get_vocab(self):
        return self.ix_to_word

    def get_seq_length(self):
        return self.seq_length

    def __init__(self, opt, mode):
        self.mode = mode  # to load train/val/test data

        # load the json file which contains information about the dataset
        print('DataLoader loading json file: ', opt.input_json)
        info = json.load(open(opt.info_json))
        self.ix_to_word = info['ix_to_word']
        print('vocab size is ', len(self.ix_to_word))
        self.splits = info['videos']
        print('number of train videos: ', len(self.splits['train']))
        print('number of val videos: ', len(self.splits['val']))
        print('number of test videos: ', len(self.splits['test']))
        # open the hdf5 file
        print('DataLoader loading video features: ', opt.feats_dir)
        print('DataLoader loading h5 file: ', opt.input_label_h5)
        self.h5_label_file = h5py.File(
            opt.input_label_h5, 'r', driver='core')

        self.feats_dir = opt.feats_dir

        # load in the sequence data
        self.seq_length = self.h5_label_file['labels'].shape[1]
        print('max sequence length in data is', self.seq_length)
        # load the pointers in full to RAM (should be small enough)
        self.label_start_ix = self.h5_label_file['label_start_ix'][:]
        self.label_end_ix = self.h5_label_file['label_end_ix'][:]

    def __getitem__(self, ix):
        """This function returns a tuple that is further passed to collate_fn
        """
        # which part of data to load
        if self.mode == 'val':
            ix += len(self.splits['train'])
        elif self.mode == 'test':
            ix = ix + len(self.splits['train']) + len(self.splits['val'])

        fc_feat = np.load(os.path.join(self.feats_dir,
                                       'video' + str(ix) + '.npy'))

        label = np.zeros([self.seq_length], dtype='int')
        mask = np.zeros([self.seq_length], dtype='float32')

        # fetch the sequence labels
        ix1 = self.label_start_ix[ix]
        ix2 = self.label_end_ix[ix]
        # random select a caption for this video
        ixl = random.randint(ix1, ix2)
        label = self.h5_label_file['labels'][ixl]

        nonzero_ixs = np.nonzero(label)[0]
        mask[:nonzero_ixs.max() + 2] = 1

        # Used for reward evaluation
        gts = self.h5_label_file['labels'][self.label_start_ix[ix]: self.label_end_ix[ix] + 1]

        # generate mask

        data = {}
        data['fc_feats'] = torch.from_numpy(fc_feat)
        data['labels'] = torch.from_numpy(label)
        data['gts'] = torch.from_numpy(gts)
        data['masks'] = torch.from_numpy(mask)
        data['ix'] = ix
        return data

    def __len__(self):
        return len(self.splits[self.mode])


import datetime

from test.BaseCase import BaseCase
from utils.serializer import Serializer

class TestSerializer(BaseCase):

    def test_ok_serialize_object(self):
        self.db.insert({
            "name": "My company",
            "creation_date": "2020-06-06",
            "is_startup": True,
        }, self.db.tables["Company"])

        company = self.db.get(self.db.tables["Company"])[0]

        res = Serializer.serialize_object(company, self.db.tables["Company"])

        self.assertEqual(res["name"], "My company")
        self.assertEqual(res["creation_date"], "2020-06-06")
        self.assertEqual(res["is_startup"], True)

    def test_ok_serialize_with_object(self):
        self.db.insert({
            "name": "My company",
            "creation_date": "2020-06-06",
            "is_startup": True,
        }, self.db.tables["Company"])

        company = self.db.get(self.db.tables["Company"])[0]

        res = Serializer.serialize(company, self.db.tables["Company"])

        self.assertEqual(res["name"], "My company")
        self.assertEqual(res["creation_date"], "2020-06-06")
        self.assertEqual(res["is_startup"], True)

    def test_ok_serialize_with_list(self):
        self.db.insert({
            "name": "My company",
            "creation_date": "2020-06-06",
            "is_startup": True,
        }, self.db.tables["Company"])
        self.db.insert({
            "name": "My company 2",
            "creation_date": "2020-06-06",
            "is_startup": True,
        }, self.db.tables["Company"])

        companies = self.db.get(self.db.tables["Company"])

        res = Serializer.serialize(companies, self.db.tables["Company"])

        self.assertEqual(len(res), 2)
        self.assertEqual(res[0]["name"], "My company")
        self.assertEqual(res[0]["creation_date"], "2020-06-06")
        self.assertEqual(res[0]["is_startup"], True)
        self.assertEqual(res[1]["name"], "My company 2")
        self.assertEqual(res[1]["creation_date"], "2020-06-06")
        self.assertEqual(res[1]["is_startup"], True)

    def test_ok_serialize_with_bytes(self):
        self.db.insert({
            "id": 51,
            "thumbnail": bytes("", encoding='utf8'),
            "width": 10,
            "height": 10,
            "creation_date": datetime.datetime.today()
        }, self.db.tables["Image"])

        image = self.db.get(self.db.tables["Image"])[0]

        Serializer.serialize(image, self.db.tables["Image"])


# 페어 트레이딩 대상 종목들의 실제 데이터로 학습한다.
# 가상 주가로 초기 학습된 신경망을 실제 데이터를 사용하여
# 추가로 학습 시킨다.
# -----------------------------------------------------------------
from keras.models import Sequential
from keras.layers import Dense, LSTM
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# plot에서 한글 처리를 위해 아래 폰트를 사용한다
from matplotlib import font_manager, rc
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)

pair = pd.read_csv("P.Pair종목(200).csv", engine='python')

def npiSpread(codeA, codeB):
    # 해당 종목의 주가 데이터를 가져온다
    p1 = pd.read_pickle('StockData/' + codeA)
    p2 = pd.read_pickle('StockData/' + codeB)

    # 해당 종목의 NPI 주가, NPI 스프레드를 계산한다
    s = pd.DataFrame(columns=['npiA', 'npiB', 'spread'])
    s['npiA'] = (p1['Close'] - p1['Close'].mean()) / p1['Close'].std()
    s['npiB'] = (p2['Close'] - p2['Close'].mean()) / p2['Close'].std()
    s['spread'] = s['npiA'] - s['npiB']

    return s

# LSTM 모델을 빌드한다
def buildModel(nInput):
    model = Sequential()
    model.add(LSTM(10, input_shape=(1,nInput)))
    model.add(Dense(1))
    model.compile(loss='mse', optimizer='adam')
    return model

def simLearning(data):
    for x in data.itertuples():
        nPrior = 10     # 과거 10-기간 데이터로 미래 예측

        # LSTM 모델을 빌드한다
        model = buildModel(nPrior)

        # LSTM weight의 초깃값을 결정한다. 저장된 weight가 있으면 이를 적용한다
        weightFile = x.codeA[0:6] + '-' + x.codeB[0:6] + '.h5'
        try:
            model.load_weights("data/" + weightFile)
            print("기존 학습 결과 Weight를 적용하였습니다.")
        except:
            print("model Weight을 Random 초기화 하였습니다.")

        # 실제 주가의 NPI 스프레드를 생성하고 마지막 nPrior개 데이터를
        # 신경망에 입력하여 nFuture 기간의 스프레드를 예측한다
        nFuture = 10
        df = npiSpread(x.codeA, x.codeB)
        df = df.dropna()
        df = df['spread'].values

        dx = np.copy(df)
        estimate = [dx[-1]]
        for i in range(nFuture):
            # 마지막 nPrior 만큼 입력데이로 다음 값을 예측한다
            xInput = dx[-nPrior:]
            xInput = np.reshape(xInput, (1, 1, nPrior))

            # 다음 값을 예측한다.
            y = model.predict(xInput)[0][0]
            print(xInput, y)
            # 예측값을 저장해 둔다
            estimate.append(y)

            # 이전 예측값을 포함하여 또 다음 값을 예측하기위해 예측한 값을 저장해 둔다
            dx = np.insert(dx, len(dx), y)

        # 원 시계열의 마지막 부분 100개와 예측된 시계열을 그린다
        dtail = df[-100:]
        ax1 = np.arange(1, len(dtail) + 1)
        ax2 = np.arange(len(dtail), len(dtail) + len(estimate))
        plt.figure(figsize=(8, 7))
        plt.plot(ax1, dtail, color='blue', label='Spread', linewidth=1)
        plt.plot(ax2, estimate, color='red', label='Estimate')
        plt.axvline(x=ax1[-1],  linestyle='dashed', linewidth=1)
        plt.title(x.stockA + '-' + x.stockB)
        plt.legend()
        plt.show()
        #print("추정치 : ", estimate)

# weight 값을 출력해 본다
def checkWeight(codeA, codeB):
    # LSTM 모델을 빌드한다
    model = buildModel(10)

    # LSTM weight의 초깃값을 결정한다. 저장된 weight가 있으면 이를 적용한다
    weightFile = codeA + '-' + codeB + '.h5'
    try:
        model.load_weights("data/" + weightFile)
        print("기존 학습 결과 Weight를 적용하였습니다.")
    except:
        print("model Weight을 Random 초기화 하였습니다.")

    np.set_printoptions(precision=3)
    for layer in model.layers:
        weights = layer.get_weights()
        print(weights)
        print()


import logging
import random
import sys
from time import sleep

from PyQt5.QtCore import QMutex, QObject, QThread, pyqtSignal
from PyQt5.QtWidgets import (
    QApplication,
    QLabel,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

logging.basicConfig(format="%(message)s", level=logging.INFO)

balance = 100.00
mutex = QMutex()

class AccountManager(QObject):
    finished = pyqtSignal()
    updatedBalance = pyqtSignal()

    def withdraw(self, person, amount):
        logging.info("%s wants to withdraw $%.2f...", person, amount)
        global balance
        mutex.lock()
        if balance - amount >= 0:
            sleep(1)
            balance -= amount
            logging.info("-$%.2f accepted", amount)
        else:
            logging.info("-$%.2f rejected", amount)
        logging.info("===Balance===: $%.2f", balance)
        self.updatedBalance.emit()
        mutex.unlock()
        self.finished.emit()

class Window(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
        self.threads = []

    def setupUi(self):
        self.setWindowTitle("Account Manager")
        self.resize(200, 150)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        button = QPushButton("Withdraw Money!")
        button.clicked.connect(self.startThreads)
        self.balanceLabel = QLabel(f"Current Balance: ${balance:,.2f}")
        layout = QVBoxLayout()
        layout.addWidget(self.balanceLabel)
        layout.addWidget(button)
        self.centralWidget.setLayout(layout)

    def createThread(self, person, amount):
        thread = QThread()
        worker = AccountManager()
        worker.moveToThread(thread)
        thread.started.connect(lambda: worker.withdraw(person, amount))
        worker.updatedBalance.connect(self.updateBalance)
        worker.finished.connect(thread.quit)
        worker.finished.connect(worker.deleteLater)
        thread.finished.connect(thread.deleteLater)
        return thread

    def updateBalance(self):
        self.balanceLabel.setText(f"Current Balance: ${balance:,.2f}")

    def startThreads(self):
        self.threads.clear()
        people = {
            "Alice": random.randint(100, 10000) / 100,
            "Bob": random.randint(100, 10000) / 100,
        }
        self.threads = [
            self.createThread(person, amount)
            for person, amount in people.items()
        ]
        for thread in self.threads:
            thread.start()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())


import matplotlib.pyplot as plt
class AnalyzeData():
    def __init__(self, parent, fname):
        self.phi = []
        self.dB = []
        self.parent = parent
        self.fname = fname

    def show(self, status, name):
        if status:
            plt.axes(projection='polar')
        plt.plot(self.phi, self.dB, '.')

        plt.savefig(name)

    def analyze(self, phi):
        self.phi = []
        self.dB = []
        k = (phi - 90) / -5
        with open(self.fname) as t:
            for i, line in enumerate(t):
                if i > 72 * k + 2 and i < 75 + 72 * k:
                    nums = []
                    num = ""
                    for sym in line:
                        if sym != ' ':
                            num += sym
                        elif len(num) > 0 and sym == ' ':
                            nums.append(float(num))
                            num = ""
                    self.phi.append(nums[0])
                    self.dB.append(nums[2])
        t.close()


from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import requests
import telegram
import random
import os
from app.utils import *

def fun_handler(bot, update, msg_list):
    if msg_list[1] in ["joke", "roast", "mock"]:
        if len(msg_list) > 2:
            fname = msg_list[2]
            lname = msg_list[3] if len(msg_list) > 3 else ""
        else:
            fname, lname = update.message.from_user.first_name, update.message.from_user.last_name
        if fname == None: fname = ""
        if lname == None: lname = ""

        contents = requests.get(
            'http://api.icndb.com/jokes/random?firstName='+fname+'&lastName='+lname).json()
        url = contents['value']['joke']
        update.message.reply_text(url)

    elif msg_list[1] in ["google"]:
        link = "http://lmgtfy.com/?q=" + "+".join(msg_list[2:])
        update.message.reply_text(link)

    elif msg_list[1] in ["meme"]:
        contents = requests.get('https://some-random-api.ml/meme').json()
        url = contents['image']
        bot.send_photo(chat_id=update.message.chat_id, photo=url)

    elif msg_list[1] in ["quote"]:
        import re
        contents = requests.get(
            'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1').json()
        text = re.sub('<[^<]+?>', '', contents[0]
                      ["content"] + "\n -- " + contents[0]["title"])
        bot.send_message(chat_id=update.message.chat_id,
                         text="`"+text+"`",
                         parse_mode=telegram.ParseMode.MARKDOWN)

    elif msg_list[1] in ["xkcd"]:
        num = str(random.randint(1, 2120))
        contents = requests.get('https://xkcd.com/'+num+'/info.0.json').json()
        url = contents["img"]
        bot.send_photo(chat_id=update.message.chat_id, photo=url)

    elif msg_list[1] in ["geek", "geekjoke"]:
        contents = requests.get(
            "https://geek-jokes.sameerkumar.website/api").text
        update.message.reply_text(contents)

    elif msg_list[1] in ["dice"]:
        num = random.randint(1, 6)
        update.message.reply_text("Dice : " + str(num))

    elif msg_list[1] in ["coin", "flip"]:
        num = random.randint(1, 2)
        txt = "Heads!"
        if num == 2:
            txt = "Tails!"
        update.message.reply_text(txt)

    elif msg_list[1] in ["choose", "select"]:
        item_list = msg_list[2:]
        num = random.randint(0, len(item_list)-1)
        update.message.reply_text(item_list[num])

    elif msg_list[1] in ["avatar"]:
        if len(msg_list) > 2:
            username = msg_list[2].replace("@", "")
        else:
            username = update.message.from_user.username
        bot.send_photo(chat_id=update.message.chat_id,
                       photo="https://api.adorable.io/avatars/285/" + username + "@adorable.io.png")

    elif msg_list[1] in ["unsplash", "wall", "wallpaper"]:
        num = str(random.randint(1, 100000000))
        bot.send_photo(chat_id=update.message.chat_id,
                       photo="https://source.unsplash.com/random?" + msg_list[2] + "&sig="+num)

    elif msg_list[1] in ["wink"]:
        contents = requests.get("https://some-random-api.ml/animu/wink").json()
        bot.send_animation(chat_id=update.message.chat_id,
                           animation=contents["link"])

    elif msg_list[1] in ["gif"]:
        if len(msg_list) < 3:
            update.message.reply_text("please provide a search term.")
        else:
            terms = " ".join(msg_list[2:])
            contents = requests.get("https://api.giphy.com/v1/gifs/random?api_key="+ os.environ["GIPHY"] + "&tag=" + terms + "&limit=1").json()
            bot.send_animation(chat_id=update.message.chat_id,
                           animation=contents["data"]["images"]["original"]["url"])

    elif msg_list[1] in ["yesno"]:
        contents = requests.get("https://yesno.wtf/api/").json()
        bot.send_animation(chat_id=update.message.chat_id,
                           animation=contents["image"])

    elif msg_list[1] in ["advice"]:
        contents = requests.get("https://api.adviceslip.com/advice").json()
        update.message.reply_text(contents["slip"]["advice"])

    elif msg_list[1] in ["belikebill"]:
        if len(msg_list) == 2:
            uname = update.message.from_user.username
        else:
            uname = msg_list[2].replace("@", "")
        bot.send_photo(chat_id=update.message.chat_id,
                       photo="https://belikebill.ga/billgen-API.php?random_number=" + \
                           get_random_number() + "&default=1&name=" + uname)

    elif msg_list[1] in ["die", "kill"]:
        ways_to_die = load_replies("ways_to_die")
        way_to_die = choose_random(ways_to_die)
        if len(msg_list) == 2:
            uname = update.message.from_user.username
        else:
            uname = msg_list[2].replace("@", "")
        update.message.reply_text(uname + " " + way_to_die)

    elif msg_list[1] in ["asktrump"]:
        replies = load_replies("ask_trump_replies")
        reply = choose_random(replies)
        update.message.reply_text("Trump : \n " + reply)

    elif msg_list[1] in ["yomama"]:
        replies = load_replies("yo_mama")
        reply = choose_random(replies)
        update.message.reply_text(reply)

    elif msg_list[1] in ["insult"]:
        if len(msg_list) == 2:
            uname = update.message.from_user.username
        else:
            uname = msg_list[2].replace("@", "")
        replies = load_replies("insults")
        reply = "Hey @" + uname + ", " + choose_random(replies)
        update.message.reply_text(reply)

    elif msg_list[1] in ["dadjoke"]:
        joke = requests.get("https://icanhazdadjoke.com/",
                            headers={"Accept": "text/plain"}).text
        update.message.reply_text(joke)

    elif msg_list[1] in ["compliment", "praise"]:
        response = requests.get('https://complimentr.com/api')
        compliment = response.json()['compliment']
        update.message.reply_text(compliment)


from create_db_sqlalchemy import (dal, Word, En_Rus, Source, Tag,
                                  WordStat, DataAccessLayer, sources_tags,
                                  TempWordStat)
from sqlalchemy import and_

class SourceExistsException(Exception):
    """
    Source already exists in the database
    """

    def __init__(self, description=None):
        if description:
            self._description = description
        else:
            self._description = 'Source already exists in the database'

    def __str__(self):
        return self._description

def source_exists(name, author=None, year=None):
    q = dal.session.query(Source).filter_by(source_name=name,
                                            source_author=author,
                                            source_year=year)
    return q.count() > 0

def get_tag(tag):
    q = dal.session.query(Tag).filter_by(tag_name=tag)
    return q.first()

def get_tag_list(tags):
    result = []
    if type(tags) == str:
        tags = [tags]
    for tag_name in tags:
        tag = get_tag(tag_name)
        if not tag:
            tag = Tag(tag_name=tag_name)
            dal.session.add(tag)
        result.append(tag)
    return result

def create_source(name, author, year, tags):
    if source_exists(name, author, year):
        raise SourceExistsException()
    source = Source(source_name=name,
                    source_author=author,
                    source_year=year)
    dal.session.add(source)
    tags = get_tag_list(tags)
    for tag in tags:
        ins = sources_tags.insert().values(tag_id=tag.tag_id,
                                           source_id=source.source_id)
        dal.session.connection().execute(ins)
    dal.session.commit()
    return source

def create_missing():  # UGLY! Should better redo
    dal.session.commit()
    dal.engine.execute("""
        INSERT INTO Words (word, word_pos)
        SELECT t.word, t.word_pos
        FROM temp_wordstat t
        LEFT JOIN Words w
        ON w.word = t.word
        AND w.word_pos = t.word_pos
        WHERE w.word_id IS NULL
        """)

def insert_wordstat(source_id, freq_dist):
    print('Creating missing words...')
    dal.session.query(TempWordStat).delete()
    dal.session.bulk_insert_mappings(TempWordStat, freq_dist)
    create_missing()
    dal.session.commit()
    print('Inserting wordstat...')
    q = dal.session.query(TempWordStat.word_freq, Word.word_id).\
        outerjoin(Word, and_(Word.word == TempWordStat.word,
                             Word.word_pos == TempWordStat.word_pos))
    print(q)
    result = [dict(source_id=source_id,
                   word_id=word_id,
                   freq=freq) for freq, word_id in q]
    print(result[0])
    dal.session.bulk_insert_mappings(WordStat, result)
    dal.session.query(TempWordStat).delete()
    dal.session.commit()


from celery import Celery
import time

app = Celery('task', backend= 'redis://localhost', broker= 'redis://localhost')

@app.task()
def task():
    '''
    this is async
    '''
    print('work started')
    time.sleep(5)
    f = open('file.text', 'w', encoding= 'utf-8')
    for i in range(5000):
        for j in range(i):
            f.write(str(i))
        f.write('\n')
    f.close()
    print('work completed')
    return "Task result"


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from asyncio import gather

import pytest
from syncer import sync

from pyppeteer.errors import BrowserError
from tests.utils import waitEvent, attachFrame, detachFrame, dumpFrames, navigateFrame

@sync
async def test_executionContext(isolated_page, server):
    p = isolated_page
    await p.goto(server.empty_page)
    await attachFrame(p, server.empty_page, 'frame1')
    assert len(p.frames) == 2

    frame1, frame2 = p.frames
    context1 = await frame1.executionContext
    context2 = await frame2.executionContext
    assert context1.frame is frame1
    assert context2.frame is frame2

    await gather(
        context1.evaluate('window.a = 1'),
        context2.evaluate('window.a = 2'),
    )
    a1, a2 = await gather(
        context1.evaluate('window.a'),
        context2.evaluate('window.a'),
    )
    assert a1 == 1
    assert a2 == 2

@sync
async def test_evaluate(isolated_page, server):
    p = isolated_page
    # should throw for detached frames
    frame1 = await attachFrame(p, server.empty_page, 'frame1')
    await detachFrame(p, 'frame1')
    with pytest.raises(BrowserError) as e:
        await frame1.evaluate('7 * 8')
    assert e.match('Execution Context is not available in detached frame')

@sync
async def test_management(isolated_page, server):
    p = isolated_page
    await p.goto(server / 'frames/nested-frames.html')
    assert dumpFrames(p.mainFrame) == [
        server / 'frames/nested-frames.html',
        '    ' + server / 'frames/two-frames.html (2frames)',
        '        ' + server / 'frames/frame.html (uno)',
        '        ' + server / 'frames/frame.html (dos)',
        '    ' + server / 'frames/frame.html (aframe)',
    ]

    # should send events when frames are manipulated dynamically
    await p.goto(server.empty_page)
    # validate frameattached events
    attachedFrames = []
    p.on('frameattached', lambda frame: attachedFrames.append(frame))
    await attachFrame(p, 'assets/frame.html', 'frame1')
    assert attachedFrames
    assert 'assets/frame.html' in attachedFrames[0].url
    # validated framenavigated events
    navigatedFrames = []
    p.on('framenavigated', lambda frame: navigatedFrames.append(frame))
    await navigateFrame(p, 'frame1', 'empty.html')
    assert navigatedFrames
    assert 'empty.html' in navigatedFrames[0].url
    # validate framedetached events
    detachedFrames = []
    p.on('framedetached', lambda frame: detachedFrames.append(frame))
    await detachFrame(p, 'frame1')
    assert len(detachedFrames) == 1
    assert detachedFrames[0].isDetached is True
    # should send framenavigated when navigating on anchor urls
    await p.goto(server.empty_page)
    await gather(
        p.goto(server.empty_page + '#foo'),
        waitEvent(p, 'framenavigated')
    )
    assert p.url == server.empty_page + '#foo'
    # should persist mainFrame on cross-process navigation
    await p.goto(server.empty_page)
    mainFrame = p.mainFrame
    await p.goto(server.cross_process_server / 'empty.html')
    assert p.mainFrame is mainFrame

@sync
async def test_attaching(isolated_page, server):
    p = isolated_page
    # should detach child frames on navigation
    attachedFrames = []
    detachedFrames = []
    navigatedFrames = []
    p.on('frameattached', lambda frame: attachedFrames.append(frame))
    p.on('framedetached', lambda frame: detachedFrames.append(frame))
    p.on('framenavigated', lambda frame: navigatedFrames.append(frame))
    await p.goto(server / 'frames/nested-frames.html')
    assert len(attachedFrames) == 4
    assert len(detachedFrames) == 0
    assert len(navigatedFrames) == 5

    # should detach child frames on navigation
    attachedFrames = []
    detachedFrames = []
    navigatedFrames = []
    await p.goto(server.empty_page)
    assert len(attachedFrames) == 0
    # TODO here detachedframes has more than 4 because it's filled with dupes
    assert len(detachedFrames) == 4
    assert len(navigatedFrames) == 1

@sync
async def test_report_frame(isolated_page, server):
    p = isolated_page
    # should report frame from-inside shadow DOM
    await p.goto(server / 'shadow.html')
    await p.evaluate(
        """
        async url => {
            const frame = document.createElement('iframe');
            frame.src = url;
            document.body.shadowRoot.appendChild(frame);
            await new Promise(x => frame.onload = x);
        }
        """,
        server.empty_page
    )
    assert len(p.frames) == 2
    assert p.frames[1].url == server.empty_page

@sync
async def test_report_frame_name(isolated_page, server):
    p = isolated_page
    await attachFrame(p, server.empty_page, 'theFrameId')
    await p.evaluate(
        """
        url => {
            const frame = document.createElement('iframe');
            frame.name = 'theFrameName';
            frame.src = url;
            document.body.appendChild(frame);
            return new Promise(x => frame.onload = x);
        }
        """,
        server.empty_page
    )
    assert p.frames[0].name == ''
    assert p.frames[1].name == 'theFrameId'
    assert p.frames[2].name == 'theFrameName'

@sync
async def test_report_frame_parents(isolated_page, server):
    p = isolated_page
    await attachFrame(p, server.empty_page, 'frame1')
    await attachFrame(p, server.empty_page, 'frame2')
    assert p.frames[0].parentFrame is None
    assert p.frames[1].parentFrame is p.mainFrame
    assert p.frames[2].parentFrame is p.mainFrame

@sync
async def test_frame_reattach(isolated_page, server):
    p = isolated_page
    frame1 = await attachFrame(p, server.empty_page, 'frame1')
    await p.evaluate(
        """
        () => {
            window.frame = document.querySelector('#frame1');
            window.frame.remove();
        }
        """
    )
    assert frame1.isDetached is True
    frame2 = (await gather(
        waitEvent(p, 'frameattached'),
        p.evaluate('document.body.appendChild(window.frame)')
    ))[0]
    assert frame2.isDetached is False
    assert frame1 is not frame2


import numpy as np
def Nodeneighbor(triangles,N):
    T=[0]*N
    for node in range(N):
        neigh_t=[]
        for elem in triangles:
            if node in elem:
                neigh_t.extend(elem)
        T[node]=neigh_t
        T[node]=list(dict.fromkeys(T[node]))
    T1=np.zeros((N,10))
    for i in range(N):
        for j in range(len(T[i])):
            T1[i,j]=T[i][j]+0
    return T1


import pygame
import os
import sys

class pause_play(object):

    def __init__(self, x, y, width, height, WIDTH, HEIGHT):
        self.PLAY_B = pygame.image.load(os.path.join("Assets", "play_b.png"))
        self.PLAY_BCLICKED = pygame.image.load(os.path.join("Assets", "play_bclicked.png"))
        self.PAUSE_B = pygame.image.load(os.path.join("Assets", "pause_b.png"))
        self.PAUSE_BCLICKED = pygame.image.load(os.path.join("Assets", "pause_bclicked.png"))
        self.SETTINGS_PLAY_B = pygame.image.load(os.path.join("Assets", "settings_play_b.png"))
        self.SETTINGS_PLAY_BCLICKED = pygame.image.load(os.path.join("Assets", "settings_play_bclicked.png"))
        self.SETTINGS_WIDTH, self.SETTINGS_HEIGHT = 202, 163
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.SETTINGS_X = WIDTH//2 - self.SETTINGS_WIDTH//2
        self.SETTINGS_Y = HEIGHT//2 - self.SETTINGS_HEIGHT//2

    def draw_pause(self, WIN, mouse):
        if 10 <= mouse[0] <= self.width + 10 and 10 <= mouse[1] <= self.height + 10:
            WIN.blit(self.PAUSE_BCLICKED, (self.x, self.y))
        else:
            WIN.blit(self.PAUSE_B, (self.x, self.y))

    def settings_window(self, WIN):
        settings_run = True
        while settings_run:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.SETTINGS_X + 82 <= mouse[0] < self.SETTINGS_X + 82 + self.width and self.SETTINGS_Y + 60 <= mouse[1] < self.SETTINGS_X + 60 + self.height:
                        settings_run = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        settings_run = False

            mouse = pygame.mouse.get_pos()
            if 10 <= mouse[0] <= self.width + 10 and 10 <= mouse[1] <= self.height + 10:
                WIN.blit(self.PAUSE_BCLICKED, (self.x, self.y))
            else:
                WIN.blit(self.PAUSE_B, (self.x, self.y))
            if (self.SETTINGS_X + 82) <= mouse[0] <= (self.SETTINGS_X + 82 + self.width) and (self.SETTINGS_Y + 60) <= mouse[1] <= (self.SETTINGS_Y + 60 + self.height):
                WIN.blit(self.SETTINGS_PLAY_BCLICKED, (self.SETTINGS_X, self.SETTINGS_Y))
            else:
                WIN.blit(self.SETTINGS_PLAY_B, (self.SETTINGS_X, self.SETTINGS_Y))

            pygame.display.update()


#calss header
class _RESPECTABLE():
	def __init__(self,):
		self.name = "RESPECTABLE"
		self.definitions = [u'considered to be socially acceptable because of your good character, appearance, or behaviour: ', u'A respectable amount or quality is large enough or of a good enough standard to be acceptable: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'adjectives'

	def run(self, obj1, obj2):
		self.jsondata[obj2] = {}
		self.jsondata[obj2]['properties'] = self.name.lower()
		return self.jsondata


import os, csv
import cv2
import pandas as pd
import numpy as np
import time
path = '/Users/jason/Desktop/springboard/capstone-datasets/VIRAT/virat-annotations-v2/ground-truth-in-yolo-format'
video_path = '/Users/jason/Desktop/springboard/capstone-datasets/VIRAT/virat-ground'
save_path = '/Users/jason/Desktop/springboard/capstone-datasets/VIRAT/transfer-learning/data/images'

files = os.listdir(path)
video_files = os.listdir(video_path)

for f in files:

    if not f.startswith('VIRAT'):
        continue

    filename = path + '/' + f

    frames_df = pd.read_csv(filename, sep=' ', header=0, names=['class','x_center','y_center','box_width','box_height',
                                                                'frame'])

    video_filename = video_path + '/' + f.split('.')[0] + '.mp4'

    if os.path.getsize(video_filename) > 100000000:
        continue

    frame_list = frames_df['frame'].tolist()
    frame_list = frame_list[::9]

    cap = cv2.VideoCapture(video_filename)

    frame_no = 0

    while cap.isOpened():

        start = time.time()
        saved_filename = save_path + '/' + f.split('.')[0] + '/' + f.split('.')[0] + '-' + str(frame_no) + '.jpg'
        cap.set(1,frame_no)
        ret, frame = cap.read()
        if ret == False:
            break
        cv2.imwrite(saved_filename, frame)
        elapsed = str(time.time() - start)
        print(saved_filename + " " + elapsed + " seconds")
        frame_no += 1

    cap.release()
    cv2.destroyAllWindows()


from itertools import repeat

from torch.utils.data import Dataset
from torch_geometric.data import Data, InMemoryDataset
import codecs
import torch
from utils import subject_to_data
from data.data_utils import read_mm_data, normalize_node_feature_node_wise, zt_edge_attr
import os.path as osp
from os.path import join
from tqdm import tqdm

from data.data_utils import concat_extra_node_feature, \
    set_missing_node_feature, \
    normalize_node_feature_subject_wise, \
    normalize_node_feature_sample_wise_transform, \
    phrase_subject_list, \
    set_edge_attr

class MmDataset(InMemoryDataset):
    def __init__(self, root, name, transform=None, pre_transform=None, pre_set_edge_attr=set_edge_attr,
                 pre_concat=None, pre_set_missing=None, pre_th=None, th=0.0,
                 scale='60', r=3, force=False, batch_size=1):
        self.name = name
        self.pre_concat = pre_concat
        self.pre_transform = pre_transform
        self.pre_set_edge_attr = pre_set_edge_attr
        self.pre_set_missing = pre_set_missing
        self.pre_th = pre_th
        self.th = th
        self.scale = scale
        if scale == '60':
            self.num_nodes = 129
        self.r = r
        self.force = force
        self.batch_size = batch_size
        super(MmDataset, self).__init__(root, transform, pre_transform)
        self.data, self.slices = torch.load(self.processed_paths[0])

        # collate in dataloader is slooooow
        if self.batch_size > 1:
            self._collate()

    @property
    def raw_file_names(self):
        # mc_filtered_subjects test_subject train_subjects
        return ['train_subjects', 'FEAT.linear/', 'Fs.subjects/', 'LABELS.xlsx', 'Lausanne/']

    @property
    def processed_file_names(self):
        return 'data.pt'

    def download(self):
        return

    def process(self):
        """
        process raw data, and save
        :return:
        """
        subject_list = [line.strip() for line in
                        codecs.open(osp.join(self.raw_dir, self.raw_file_names[0]), 'r').readlines()]
        # subject_list = phrase_subject_list(subject_list)

        print("Reading MM data...")
        data_list = read_mm_data(subject_list=subject_list,
                                 fsl_subjects_dir_path=join(self.raw_dir, self.raw_file_names[1]),
                                 fs_subjects_dir_path=join(self.raw_dir, self.raw_file_names[2]),
                                 atlas_sheet_path=join(self.raw_dir, self.raw_file_names[3]),
                                 atlas_dir_path=join(self.raw_dir, self.raw_file_names[4]),
                                 tmp_dir_path=join(self.raw_dir, 'tmp'),
                                 scale=self.scale,
                                 r=self.r,
                                 force=self.force)
        print("Setting edge_attr")
        data_list = self.pre_set_edge_attr(data_list)

        self.data, self.slices = self.collate(data_list)

        # set missing node feature for subcortical regions
        print("set missing data...")
        self.data.x = self.pre_set_missing(self.data.x) if self.pre_set_missing is not None else self.data.x

        # concat adj to node feature
        if self.pre_concat is not None:
            print("concatenating adj to node feature")
            # this will take a long time...
            # python for-loop is incredibly slow, even with multi-processing
            data_list = self.pre_concat([self._get(i) for i in range(self.__len__())])

        # normalization
        print("Normalizing node attributes")
        self.data, self.slices = self.collate(data_list)
        self.data.x = self.pre_transform(self.data.x, N=len(data_list)) \
            if self.pre_transform is not None else self.data.x

        torch.save((self.data, self.slices), self.processed_paths[0])

    def get(self, idx):
        data = Data()
        for key in self.data.keys:
            item, slices = self.data[key], self.slices[key]
            s = list(repeat(slice(None), item.dim()))
            s[self.data.cat_dim(key, item)] = slice(slices[idx],
                                                    slices[idx + 1])
            data[key] = item[s]
        return data.x, data.edge_index, data.edge_attr, data.y, data.adj

    def _get(self, idx):
        data = Data()
        for key in self.data.keys:
            item, slices = self.data[key], self.slices[key]
            s = list(repeat(slice(None), item.dim()))
            s[self.data.cat_dim(key, item)] = slice(slices[idx],
                                                    slices[idx + 1])
            data[key] = item[s]
        return data

    def add_flag_to_edge_index(self):
        """
        recursively add flag(integer) to edge_index to concatenate graphs to a bigger graph (batch)
        refer: https://rusty1s.github.io/pytorch_scatter/build/html/index.html
        :return:
        """
        dim = self.data.cat_dim('edge_index', self.data.edge_index)
        i = 0
        for idx in range(self.__len__()):
            slices = self.slices['edge_index']
            s = list(repeat(slice(None), self.data.edge_index.dim()))
            s[dim] = slice(slices[idx], slices[idx + 1])
            flag = i * self.num_nodes
            self.data.edge_index[s] += flag
            i += 1
            if i == self.batch_size:
                i = 0

    def _collate(self):
        """
        Collate the graphs in the dataset before passing it to dataloader,
        to make it faster to build a _DataLoaderIter
        :return:
        """
        self.add_flag_to_edge_index()
        keys = self.slices.keys()
        for key in keys:
            self.slices[key] = self.slices[key][::self.batch_size]

    def collate_fn(self, data_list):
        """
        for Pytorch DataLoader
        Duang a batch of graph in to a BIG graph
        :param data_list:
        :return:
        """
        data, slices = self.collate(data_list)
        return data

    def collate_fn_multi_gpu(self, device_count, data_list):
        """
        TODO: Deprecated
        for Pytorch DataLoader
        Usage: partial(collate_fn_multi_gpu, device_count)(data_list)
        :param data_list:
        :param device_count: gpu count used
        :return: list of data
        """
        data_chunks = [data_list[i::device_count] for i in range(device_count)]
        collated_data_list = []
        for data_chunk in data_chunks:
            data, slices = self.collate(data_chunk)
            collated_data_list.append(data)

        return collated_data_list

    def set_active_data(self, index):
        """
        copy the dataset by index
        :param index:
        :return:
        """
        copy = self.__class__.__new__(self.__class__)
        copy.__dict__ = self.__dict__.copy()
        copy.data, copy.slices = self.collate([self._get(i) for i in index])
        return copy

    def __repr__(self):
        return '{}()'.format(self.name)

if __name__ == '__main__':
    mmm = MmDataset('data/', 'MM',
                    pre_transform=normalize_node_feature_sample_wise_transform,
                    pre_set_missing=set_missing_node_feature,
                    pre_set_edge_attr=set_edge_attr,
                    pre_concat=concat_extra_node_feature,
                    batch_size=1,
                    r=5,
                    force=True
                    )
    mmm.__getitem__(0)
    print()

class Normalize(object):
    """
    Normalize a tensor image with mean and standard deviation.

    Args:
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channel.
    """

    def __init__(self, mean, std):
        self.mean = [torch.tensor(x) for x in mean]
        self.std = [torch.tensor(x) for x in std]

    def __call__(self, tensor):
        return self.z_score_norm(tensor, self.mean, self.std)

    @staticmethod
    def z_score_norm(tensor, mean, std):
        """
        Normalize a tensor with mean and standard deviation.
        Args:
            tensor (Tensor): Tensor image of size [num_nodes, num_node_features] to be normalized.
            mean (sequence): Sequence of means for each num_node_feature.
            std (sequence): Sequence of standard deviations for each num_node_feature.

        Returns:
            Tensor: Normalized tensor.
        """
        for i, _ in enumerate(mean):
            tensor[:, i] = (tensor[:, i] - mean[i]) / std[i]
        return tensor

    @staticmethod
    def min_max_norm(tensor):
        """
        Normalize a tensor to [0,1]
        """
        for i in range(0, tensor.shape[-1]):
            max_v = torch.max(tensor[:, i])
            min_v = torch.min(tensor[:, i])
            tensor[:, i] = (tensor[:, i] - min_v) / (max_v - min_v)
        return tensor

class MmmDataset(Dataset):
    def __init__(self,
                 subject_id_path=str,
                 G_path=str,
                 transform=None,
                 scale="60",
                 ):
        """
        Args:
            subject_id_path: path to subject_id file
            transform: pytorch transforms
            scale: ['60', '125', '250'], Lausanne atlas scale
        """
        self.transform = transform
        self.G_path = G_path
        self.scale = scale
        self.subject_ids = [line.strip() for line in codecs.open(subject_id_path, 'r').readlines()]
        print("Loading dataset from disk into memory...")
        self.datas = [subject_to_data(self.G_path, subject, self.scale) for subject in self.subject_ids]
        self.active_datas = self.datas

        for data in self.datas:
            data.x = data.x if self.transform is None else self.transform(data.x)

    @property
    def num_features(self):
        return self[0].num_features

    def __getitem__(self, index):
        data = self.active_datas[index]
        return data.x, data.edge_index, data.edge_attr, data.y, data.adj

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

    def set_active_data(self, index):
        """
        Set active data for K-Folds cross-validation
        Args:
            index: indices for the split
        """
        self.active_datas = [self.datas[i] for i in index]

    @staticmethod
    def collate_fn(batch):  # Deprecated
        """
        Note: real support of minibatch.
        :param batch: list of Data object
        :return:
        """
        batch_data = Data()

        for k, _ in batch[0]:
            batch_data[k] = torch.stack([data[k] for data in batch], dim=0)

        return batch_data


import hashlib
import logging
import time
from json import JSONDecodeError

import scrapy

from kingfisher_scrapy.base_spider import LinksSpider

class Colombia(LinksSpider):
    name = 'colombia'
    sleep = 120 * 60

    def start_requests(self):
        base_url = 'https://apiocds.colombiacompra.gov.co:8443/apiCCE2.0/rest/releases'
        if hasattr(self, 'year'):
            base_url += '/page/{}'.format(int(self.year))
        base_url += '?page=%d'

        start_page = 1
        if hasattr(self, 'page'):
            start_page = int(self.page)
        yield scrapy.Request(
            url=base_url % start_page,
            meta={'kf_filename': 'page{}.json'.format(start_page)}
        )

    def parse(self, response):
        # In Colombia, every day at certain hour they run a process in their system that drops the database and make
        # the services unavailable for about 120 minutes, as Colombia has a lot of data,
        # the spider takes more than one day to scrape all the data,
        # so eventually the spider will always face the service problems. For that, when the problem occurs, (503
        # status or invalid json) we wait 120 minutes and then continue
        try:
            if response.status == 503 or response.status == 404:
                url = response.request.url
                logging.info('Sleeping due error {} in url {}'.format(response.status, url))
                time.sleep(self.sleep)
                yield scrapy.Request(url,
                                     dont_filter=True,
                                     meta={'kf_filename': hashlib.md5(
                                         url.encode('utf-8')).hexdigest() + '.json'})

            elif response.status == 200:

                yield self.save_response_to_disk(response, response.request.meta['kf_filename'],
                                                 data_type='release_package')

                if not self.sample:
                    yield self.next_link(response)
            else:

                yield {
                    'success': False,
                    'file_name': response.request.meta['kf_filename'],
                    'url': response.request.url,
                    'errors': {'http_code': response.status}
                }

        except JSONDecodeError:
            url = response.request.url
            logging.info('Sleeping due json decode error in url {}'.format(url))
            time.sleep(self.sleep)
            yield scrapy.Request(url, dont_filter=True,
                                 meta={'kf_filename': hashlib.md5(url.encode('utf-8')).hexdigest() + '.json'})


from django.core import mail
from selenium.webdriver.common.keys import Keys
import re
from .base import FunctionalTest
import time

TEST_EMAIL = 'liliancai@404@gmail.com'
SUBJECT="Your log in link from todolist"

class LoginTest(FunctionalTest):

	def test_can_get_email_link_to_log_in(self):
		#send email
		self.browser.get(self.live_server_url)
		#time.sleep(30)
		self.browser.find_element_by_name('email').send_keys(TEST_EMAIL)
		self.browser.find_element_by_name('email').send_keys(Keys.ENTER)

		#check if the email sent or not by 'Check your email'
		self.wait_for(lambda:self.assertIn(
			'Check your email',
			self.browser.find_element_by_tag_name('body').text
		))

		#get the mailbox and check it's email
		email=mail.outbox[0]
		self.assertIn(TEST_EMAIL,email.to)
		self.assertEqual(email.subject,SUBJECT)

		#check the url sent or not
		self.assertIn('Use this link to log in',email.body)
		url_search=re.search(r'http://.+/.+$',email.body)

		if not url_search:
			self.fail(f'Could not find url in email body:\n{email.body}')
		url=url_search.group(0)
		self.assertIn(self.live_server_url,url)
		print('url is \n',url)
		#act as click in
		self.browser.get(url)

		#check if logged in,wait untill log out button shows up
		self.wait_to_be_logged_in(email=TEST_EMAIL)
		#test log out works by click()
		self.browser.find_element_by_link_text('Log out').click()
		#test if 'enter enamil to login' show up again by find 'email'
		#and also make sure the test_email address didn't show up on homeapge
		self.wait_to_be_logged_out(email=TEST_EMAIL)


import sys

def fatorizacao(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors

def main():
    val = sys.stdin.readline()
    lista = fatorizacao(int(val))
    for i in lista:
        print(i)

main()


# A Ball is Prey; it updates by moving in a straight
#   line and displays as blue circle with a radius
#   of 5 (width/height 10).

from prey import Prey

class Ball(Prey):
    radius = 5
    speed = 5
    color = 'blue'

    def __init__(self, x, y, width, height, speed, angle, color):

        Prey.__init__(self, x, y, width, height, angle, speed)

        self._x = x
        self._y = y
        self._width = width * 2
        self._height = height * 2
        self._speed = speed
        self._angle = angle
        self._color = color

        Prey.randomize_angle(self)

    def update(self, model):
        Prey.move(self)

    def display(self,canvas):
        canvas.create_oval(self._x-Ball.radius      , self._y-Ball.radius,
                                self._x+Ball.radius, self._y+Ball.radius,
                                fill=self._color)