# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import random
import base64
# 加密工具
class prpcrypt():

    def __init__(self):

        self.mode = AES.MODE_CBC

    # 加密文本
    def encrypt(self,text,key):
        #
        cryptor=AES.new(key,self.mode,key)
        # 密钥key 长度必须为16（AES-128）、24（AES-192）、或32（AES-256）Bytes 长度.目前AES-128足够用
        length = 16
        count=len(text)
        pad=length-(count%length)
        text=text+('\0'*pad)

        self.ciphertext=cryptor.encrypt(text)
        # Aes加密得到的字符串不一定是ascii字符集 输出到终端或者保存时会出问题
        # 这里统一把加密后的字符串转换位16进制字符串
        encryptstr=b2a_hex(self.ciphertext)
        encryptstr=str(encryptstr,'utf-8')
        # base64加密
        base64str=base64.b64encode(encryptstr.encode('utf-8'))

        return base64str
    # 解密
    def decrypt(self,text,key):
        # base64解密
        base64_decrypt = base64.b64decode(text.encode('utf-8'))
        decrypttext=str(base64_decrypt, 'utf-8')

        cryptor=AES.new(key,self.mode,key)
        target_text=cryptor.decrypt(a2b_hex(decrypttext))
        decryptstr=str(target_text,'utf-8')
        targetstr=decryptstr.rstrip('\0')

        return targetstr

    # 获取16位随机密码
    def get_random_secret(self):
        samplestr="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"
        randomstr="".join(random.sample(samplestr,16))
        return randomstr

if __name__ == '__main__':
    print("")
    # send_encryptkey="JA@eDmi&osEx#q2BYzgxOWQ1NjAzMzZmYzVkYzZmNzQ2ZTU4ODhmZGY0MzVlMjE3ZjA5Nzk5Y2Y2ZDRiMGRmM2MzYWVmZWUwMDM4YmY2MTNmYmZjMjVkOTk2NDRkNmY1OWEwMDI3Y2NhM2NiYWFlZjNkYWNlNzJjNTg5YTIyODA5MWJjNDY2NDJkNzA5YWZkYmI4NzhkMDJiZjc3MWFmODFkZDVmYmRhZmY4ZTg2MzE1MmE0YWMwZGIxNjAyM2UxZDIzOGVjZGQzMWRlNjkxMmEwMTUyMzM1ZGJlMmQ5MDg1NDNkNWMwMmY1YWFmNGQzMThiNzU5NWYyY2E0ZDdmZjM0OWRhZjQyNzMyYzUzYjZiYTBmMjMwZWUxMTQ0ZTgzMmRjNGRhZWQxZjM5"
    # sendkey=send_encryptkey[0:16]
    # ms=send_encryptkey[16:len(send_encryptkey)]
    # # 解密
    # prpcrypttool = prpcrypt()
    # un_encrypt = prpcrypttool.decrypt(ms, sendkey)
    # jsondata = eval(un_encrypt)
    # key_e = jsondata['KEY_ENCRY']
    # st=str(prpcrypttool.encrypt(un_encrypt,key_e),"utf-8")
    # _create_file(st)
    # print("自己："+st)
    #
    # xmlencrykey = _get_element_by_tag("encryptstr")
    # print("系统："+xmlencrykey)
    # if st==xmlencrykey:
    #     print("------------------------ok")
    #
    # #
    # # un_ss = prpcrypttool.decrypt(xmlencrykey, key_e)
    # # print(un_ss)

#
# if __name__ == '__main__':
#
#
#
#     mac=_get_machine_message()
#     timenumber=_get_time_stamp13()
#     phonenumber=15659813871
#     registdate=_get_date_formate()
#     daynumber=2
#     key_encry=str(_get_time_stamp16())
#
#
#     # AES加密
#     encrypt_str='{"MAC":'+mac+' ,"PHONE": '+str(phonenumber)+',"TIMENUMBER": '+str(timenumber)+',"REGISTDATE":'+registdate+',"DAYS":'+str(daynumber)+'}'
#     prpcrypttool=prpcrypt(key_encry)
#
#     prpcrypttool.get_random_secret()
#
#
#     AES_txt=prpcrypttool.encrypt(encrypt_str)
#     print("AES加密后："+str(AES_txt,'utf-8'))
#     # AES解密
#     txt=prpcrypttool.decrypt(str(AES_txt,'utf-8'))
#     print("解密后"+txt)
#     _write_yaml('AES_Encrypt_Key','11111')
#
#
#     # base64加密解密
#
#     keystr = base64.b64encode(encrypt_str.encode('utf-8'))
#     str_decrypt = str(keystr, 'utf-8')
#     print("64密钥：" + str_decrypt)
#     # base64解密
#     base64_decrypt=base64.b64decode(str_decrypt.encode('utf-8'))
#     print("BASE64解密串（UTF-8）:\n", str(base64_decrypt, 'utf-8'))


# https://www.acmicpc.net/problem/2018

# 첫 줄에 정수 N을 입력합니다.
# 1 <= N <= 10,000,000
N = int(input())

method = 0

for start in range(1, N + 1):
    case = 0
    i = 0

    while True:
        case += start + i

        if case >= N:
            if case == N:
                method += 1
            else:
                break

        i += 1

print(method)


from PIL import ImageGrab
import os
import sys
import time
from config import *
from pathlib import Path

def main(input_file, namespace = 'db'):
	Path("thumbs/low/").mkdir(parents=True, exist_ok=True)

	os.system("principia principia://principia-web.se/play/lvl/%s/%s &" % (namespace, input_file))
	time.sleep(2)
	image = ImageGrab.grab(bbox=(
		(MONITOR_WIDTH - PRINCIPIA_WIDTH) / 2,
		((MONITOR_HEIGHT - PRINCIPIA_HEIGHT) / 2)+29,
		(MONITOR_WIDTH - PRINCIPIA_WIDTH) / 2 + PRINCIPIA_WIDTH,
		((MONITOR_HEIGHT - PRINCIPIA_HEIGHT) / 2 + PRINCIPIA_HEIGHT)+29
	))
	image.save("thumbs/%s.%s" % (input_file, IMAGEFORMAT))

	os.system("convert thumbs/%s.%s -resize 240 -unsharp 0x0.55+0.55+0.008 -quality 90 thumbs/low/%s.%s" % (input_file, IMAGEFORMAT, input_file, IMAGEFORMAT))

if __name__ == "__main__":
	if len(sys.argv) < 2:
		print("gimmie a level id uwu")
	else:
		if len(sys.argv) < 3:
			main(sys.argv[1], sys.argv[2])
		else:
			main(sys.argv[1])


a = 4546

b = 67.990

c = '''ramesh'''

print('this isn\'t called a "variable"')
print(''' this
wyw
wru3hr''')

d = True

c = None

'''
int
float
String
boolean
None

'''

print(type(d))

print(d)


"""
Crie duas variáveis, atribua valor a cada uma e troque os seus valores, usando somente variáveis
"""

from doctest import OutputChecker

A = 10
B = 20

# cria uma variável temporária para armazenar valor de B
temp = B
B = A
A = temp

# ou A, B = B, A

print('O valor de A é:', A)
print('O valor de B é:', B)


import argparse
import logging
import os
import sys
import pyqtgraph as pg
from PyQt5 import QtGui
from PyQt5.QtOpenGL import *
from PyQt5 import QtCore, Qt
from PyQt5.Qt import *
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from pyqtgraph.Qt import QtGui, QtCore
from PyQt5.QtGui import QFont
from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds
from brainflow.data_filter import DataFilter, FilterTypes, DetrendOperations
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from random import randint

class graph_win(QMainWindow):
    def __init__(self, board_shim):
        super(graph_win, self).__init__()
        self.board_id = board_shim.get_board_id()
        self.board_shim = board_shim
        self.eeg_channels = BoardShim.get_eeg_channels(self.board_id)
        self.sampling_rate = BoardShim.get_sampling_rate(self.board_id)
        self.update_speed_ms = 50
        self.window_size = 4
        self.num_points = self.window_size * self.sampling_rate

        #region Initial layout
        styles = {'color': 'black', 'font-size': '16px'}
        self.setWindowTitle('Main Window')
        self.setGeometry(0, 0, 1500, 900)

        self.vLayout = QVBoxLayout()
        self.hLayout = QHBoxLayout()
        self.gridLayout = QGridLayout()
        self.vLayout.addLayout(self.hLayout)
        self.vLayout.addLayout(self.gridLayout)

        self.vLayout.setContentsMargins(10, 10, 10, 10)
        self.hLayout.setContentsMargins(10, 10, 10, 10)
        self.vLayout.setSpacing(10)
        self.hLayout.setSpacing(10)

        self.widget = QWidget()
        self.widget.setLayout(self.vLayout)
        self.setCentralWidget(self.widget)
        #endregion

        #region Buttons
        self.button1 = QPushButton('Channel 1')
        self.button2 = QPushButton('Channel 2')
        self.button3 = QPushButton('Channel 3')
        self.button4 = QPushButton('Channel 4')

        self.button1.setFixedSize(80, 30)
        self.button2.setFixedSize(80, 30)
        self.button3.setFixedSize(80, 30)
        self.button4.setFixedSize(80, 30)

        self.button1.setCheckable(True)
        self.button2.setCheckable(True)
        self.button3.setCheckable(True)
        self.button4.setCheckable(True)

        self.button1.clicked.connect(self.update_plot_data)
        self.button2.clicked.connect(self.update_plot_data)
        self.button3.clicked.connect(self.update_plot_data)
        self.button4.clicked.connect(self.update_plot_data)

        self.button1.setStyleSheet("background-color : lightgrey")
        self.button2.setStyleSheet("background-color : lightgrey")
        self.button3.setStyleSheet("background-color : lightgrey")
        self.button4.setStyleSheet("background-color : lightgrey")

        self.hLayout.addWidget(self.button1)
        self.hLayout.addWidget(self.button2)
        self.hLayout.addWidget(self.button3)
        self.hLayout.addWidget(self.button4)
        #endregion

        #region Graphs
        self.graphWidget1 = pg.PlotWidget()
        self.graphWidget1.setTitle('Channel 1', **styles)
        self.graphWidget1.setLabel('left', 'Amplitude', **styles)
        self.graphWidget1.setLabel('bottom', 'Time', **styles)
        self.graphWidget1.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget1, 0, 0)

        self.graphWidget2 = pg.PlotWidget()
        self.graphWidget2.setTitle('Channel 2', **styles)
        self.graphWidget2.setLabel('left', 'Amplitude', **styles)
        self.graphWidget2.setLabel('bottom', 'Time', **styles)
        self.graphWidget2.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget2, 1, 0)

        self.graphWidget3 = pg.PlotWidget()
        self.graphWidget3.setTitle('Channel 3', **styles)
        self.graphWidget3.setLabel('left', 'Amplitude', **styles)
        self.graphWidget3.setLabel('bottom', 'Time', **styles)
        self.graphWidget3.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget3, 2, 0)

        self.graphWidget4 = pg.PlotWidget()
        self.graphWidget4.setTitle('Channel 4', **styles)
        self.graphWidget4.setLabel('left', 'Amplitude', **styles)
        self.graphWidget4.setLabel('bottom', 'Time', **styles)
        self.graphWidget4.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget4, 3, 0)
        #endregion

        pen = pg.mkPen(color=(255, 0, 0))
        self.x = list(range(100))
        self.y = [0] * 100
        self.data_line1 = self.graphWidget1.plot(self.x, self.y, pen=pen)
        self.data_line2 = self.graphWidget2.plot(self.x, self.y, pen=pen)
        self.data_line3 = self.graphWidget3.plot(self.x, self.y, pen=pen)
        self.data_line4 = self.graphWidget4.plot(self.x, self.y, pen=pen)

        self.timer = QtCore.QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.update_plot_data)
        self.timer.start()

    def update_plot_data(self):
        data = self.board_shim.get_current_board_data(self.num_points)

        if self.button1.isChecked():
            pass
        else:
            # what does this do?
            # DataFilter.detrend(data[0], DetrendOperations.CONSTANT.value)
            # append for y? and which index is for channel 1?
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            # self.y = self.y[1:]
            # self.y.append(randint(0, 100))
            self.y = data[self.eeg_channels[0]].tolist()
            self.data_line1.setData(self.y)

        if self.button2.isChecked():
            pass
        else:
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            self.y = data[self.eeg_channels[1]].tolist()
            self.data_line2.setData(self.y)

        if self.button3.isChecked():
            pass
        else:
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            self.y = data[self.eeg_channels[2]].tolist()
            self.data_line3.setData(self.y)

        if self.button4.isChecked():
            pass
        else:
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            self.y = data[self.eeg_channels[3]].tolist()
            self.data_line4.setData(self.y)

        # self.app.processEvents()

def main():
    BoardShim.enable_dev_board_logger()
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument('--timeout', type=int, help='timeout for device discovery or connection', required=False,
                        default=0)
    parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0)
    parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False,
                        default=0)
    parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='')
    parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='COM4')
    parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='')
    parser.add_argument('--other-info', type=str, help='other info', required=False, default='')
    parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='')
    parser.add_argument('--serial-number', type=str, help='serial number', required=False, default='')
    parser.add_argument('--board-id', type=int, help='board id, check docs to get a list of supported boards',
                        required=False, default=BoardIds.CYTON_BOARD)
    parser.add_argument('--file', type=str, help='file', required=False, default='')
    args = parser.parse_args()

    params = BrainFlowInputParams()
    params.ip_port = args.ip_port
    params.serial_port = args.serial_port
    params.mac_address = args.mac_address
    params.other_info = args.other_info
    params.serial_number = args.serial_number
    params.ip_address = args.ip_address
    params.ip_protocol = args.ip_protocol
    params.timeout = args.timeout
    params.file = args.file

    try:
        board_shim = BoardShim(args.board_id, params)
        board_shim.prepare_session()
        board_shim.start_stream(450000, args.streamer_params)
        app = QtWidgets.QApplication(sys.argv)
        main = graph_win(board_shim)
        main.show()
        data = board_shim.get_board_data()
        print(data)
        sys.exit(app.exec())
    except BaseException:
        logging.warning('Exception', exc_info=True)
    finally:
        logging.info('End')
        if board_shim.is_prepared():
            logging.info('Releasing session')
            board_shim.release_session()

if __name__ == '__main__':
    main()


#!/usr/bin/python

import requests
import random
import threading
from termcolor import colored

def request(url):

	try:
		return requests.get("http://" + url, timeout=1)
	except requests.exceptions.ConnectionError:
		pass

def banner():
 print ('''\033[1;35m
  _________       __            __    __                            ___
 /   _____/ ____ |  |__ _____ _/  |__/  |_  ____   ________________ \_ |__   ____
 \_____  \_/ ___\|  |  \__    \   __\   __\/ __ \ /    \_  __ \__  \ | __ \_/ __ \
 /        \  \___|   Y  \/ __ \|  |  |  | \  ___/|   |  \  | \// __ \| \_\ \  ___/
/_______  /\___  >___|  (____  /__|  |__|  \___  >___|  /__|  (____  /___  /\___  >
        \/     \/     \/     \/                \/     \/           \/    \/     \/  ''')

def main():
	target = input("[*] Target Domain: ")

	file = open("package/subdomains.txt", "r")

	for line in file:
		try:
			word = line.strip()
			full_url = word + "." + target
			response = request(full_url)
			if response:
				print (colored("[+] Discovered subdomain: " + full_url, 'green'))
		except:
			return()


import xlrd
import matplotlib.pyplot as plt
from UserData import UserDataInfo
import datetime
import pandas as pd
import json
from station2location import station2location
import os
# def readData(url):
#     data = xlrd.open_workbook(url)
#     table = data.sheets()[0]  # 多张sheet的情况读取第一张
#     nrows = table.nrows
#     ncols = table.ncols
#     list = []
#     for rownum in range(0, nrows):
#         row = table.row_values(rownum)
#         print(row)
#         # for i in range(0, ncols):  # 转码unicode转utf-8
#         #     row[i] = row[i]
#         if row:
#             list.append(row)
#     return list

#读取文件，返回data（类型dataframe）
#同时读取多个excel文件进行合并

#从excel中读取数据
def readDate_pd(url):
    data = pd.read_excel(url,usecols=[u'起始时间', u'通信地点', u'通信方式',
                                        u'对方号码', u'通信时长', u'通信类型',
                                        u'基站小区号', u'IMEI', u'IMSI'],
                        dtype={'IMEI':str,'IMSI':str,u'基站小区号':str})
    # print(data.index)
    return data
'''
Operation	                    Syntax	        Result
Select column	                df[col]	        Series
Select row by label	            df.loc[label]	Series
Select row by integer location	df.iloc[loc]	Series
Slice rows	                    df[5:10]	DataFrame
Select rows by boolean vector	df[bool_vec]	DataFrame
'''
#处理data中相关数据,添加loc和cid选项后合并表
def dealData(data):

    for i in data.index:
        # 将表中通话起始时间序列化，转换成timestamp
        datetimes = data['起始时间'].at[i]
        data['起始时间'].at[i] = datetimeDecode(datetimes)
        # 将表中通信时长序列化，str转换成int，单位为秒
        calltimes = data['通信时长'].at[i]
        data['通信时长'].at[i] = timeDecode(calltimes)
        # 处理小区基站号,并加入到新表当中
    stationlists = data['基站小区号'].str.split('/',expand=True)
    data['loc'] = stationlists[0].str.upper()
    data['cid'] = stationlists[1].str.upper()

    return data
# # 行为分析
# def behavior_analysis(datalist):
#     t = 1
#     for line in datalist:
#         if (t == 1):
#             t = 3
#             continue
#         dh = dateDecode(line[2])
#         day = int(dh[0])
#         hour = int(dh[-1])
#
#         user.day_intervel[day] += 1
#         user.time_intervel[hour / 2] += 1
#
#         timeStr = line[3]
#         timelong = timeDecode(timeStr)
#
#         if line[4] == '主叫':
#             user.calling_times += 1
#             user.calling_long += timelong
#         if line[4] == '被叫':
#             user.called_times += 1
#             user.called_long += timelong
#
#     user.call_times = user.calling_times + user.called_times  # 总次数
#     user.call_long = user.calling_long + user.called_long  # 总时长

# 序列化通话时间,返回为(int类型)秒
#将字符串转成timestamp格式
def timeDecode(timeStr):
    call_time = 0
    if timeStr.find('时') != -1:
        call_time = pd.to_datetime(timeStr, format='%H时%M分%S秒')
        # print((call_time-basetime).seconds)
        return (call_time-basetime).seconds
    if timeStr.find('时') == -1 and timeStr.find('分') !=-1:
        call_time = pd.to_datetime(timeStr, format='%M分%S秒')
        # print((call_time-basetime).seconds)
        return (call_time-basetime).seconds
    if timeStr.find('时') == -1 and timeStr.find('分') ==-1:
        call_time = pd.to_datetime(timeStr, format='%S秒')
        # print((call_time-basetime).seconds)
        return (call_time-basetime).seconds
    else:
        return call_time

#通话时间里面定义一个基准时间
basetime = pd.to_datetime('1900-01-01 00:00:00',format='%Y-%m-%d %H:%M:%S')

# 序列化通话时间戳
def datetimeDecode(datetimeStr):
    datetime = pd.to_datetime(datetimeStr,format='%Y-%m-%d %H:%M:%S')
    return datetime

# def printout():
#     print
#     "被叫次数：", user.called_times
#     print
#     "被叫时长：", timeEncode(user.called_long)
#
#     print
#     "主叫次数：", user.calling_times
#     print
#     "主叫时长：", timeEncode(user.calling_long)
#
#     print
#     "总次数：", user.call_times
#     print
#     "总时长：", timeEncode(user.call_long)
#
#     print
#     "日期", user.day_intervel
#     print
#     "时段", user.time_intervel

#类型str，基站返回列表[0]:lac,[1]:cid
#基站数据16进制转换10进制
def stationDecode(data):
    hex_header = '0x'
    for i in data.index:
        if data['loc'].at[i] == 'NULL':
            data['loc'].at[i] = None
        else:
            data['loc'].at[i] = hex_header + data['loc'].at[i]

        if data['cid'].at[i] == 'NULL':
            data['cid'].at[i] = None
        else:
            data['cid'].at[i] = hex_header + data['cid'].at[i]
    # print(data)
        return data

#格式化基站代码，station2location解析出经纬度和地址，返回
def getlocation(data):
    locations = stationDecode(data)
    for i in range(20):
        stations = []
        stations.extend([data['loc'].at[i],data['cid'].at[i]])
        station2location(stations)

# 数据可视化
def dataVisualization(data):
    plt.plot(data[u'通信时长'].sum(), 'k')
    plt.plot(data[u'起始时间'].sum(), 'bo')
    plt.xlabel(u'date')
    plt.ylabel(u'通话次数')
    plt.title(u'每日通话分析')
    plt.grid(color='#95a5a6', linestyle='--', linewidth=1, axis='y', alpha=0.4)
    plt.show()

#连续读取多个文件话单
def listDir(rootdir):
    filelist = []
    files_num = 0
    for filename in os.listdir(rootdir):
        pathname = os.path.join(rootdir, filename)
        if (os.path.isfile(pathname)):
            filelist.append(pathname)
            files_num= files_num+1
        else:
            listDir(pathname)
    print('一共{}个话单文件'.format(files_num))
    return filelist

#合并多个话单
def append_list(filelist):
    load_files_Num = 0
    big_data = 0
    for filename in filelist:
        try:
            #读取每一个话单文件
            data_temp = readDate_pd(filename)
            #按条件处理好每个话单文件
            datas = dealData(data_temp)
            load_files_Num = load_files_Num +1
            if load_files_Num ==1:
                big_data = datas
            else:
                big_data = big_data.append(datas,ignore_index=True)
        except:
            print("格式出错,请确认文件格式是否为xlsx或者标准导出格式")
    print('共处理了{}个话单文件'.format(load_files_Num))
    big_data.to_excel('D:/data/1/1.xlsx')

# # stationDecode(' /0169ba83')
# url = "D:/data/1.xlsx"
# # datalist = readData(url)
# a = readDate_pd(url)
# b = dealData(a)
# getlocation(b)
# datetimeDecode('2019-01-01 14:06:48')
# user = UserDataInfo()
# behavior_analysis(datalist)
#
# printout()

HD_file_name_list = listDir('D:/data/1')
append_list(HD_file_name_list)


import numpy as np

from query_rewriter.io.rfd.rfd_extractor import RFDExtractor

def main():
    print("[Test]")
    args = ["-c", "../dataset/dataset_string.csv", "--human"]
    rfd_extractor = RFDExtractor(args, False)
    rfd_data_frames: list = rfd_extractor.rfd_data_frame_list

    print("[Test]")
    print("RFDs.Count:", len(rfd_data_frames))
    for rfd_data_frame in rfd_data_frames:
        print("RFD_DataFrame:\n", rfd_data_frame)
        print()
        print("Number of RFDs found:", len(rfd_data_frame))

        string = ""
        for _, row in rfd_data_frame.iterrows():
            string += "".join(
                ["" if np.isnan(row[col]) else "{}(<= {}), ".format(rfd_data_frame.columns[col],
                                                                    round(row[col], ndigits=2))
                 # it starts from 1 and not 0 'cause at position 0 there is the RHS
                 for col in range(1, len(row))
                 ]
            )

            string += "-> {}(<= {})".format(rfd_data_frame.columns[0], round(row[0], ndigits=2))
            string += "\n"
        print(string)

        for _, row in rfd_data_frame.iterrows():
            rfd_dictionary = {}
            for col in range(0, len(row)):
                rfd_dictionary[rfd_data_frame.columns[col]] = round(row[col], ndigits=2)

            print("RFD_Dictionary:", rfd_dictionary)

        print()

if __name__ == "__main__":
    main()


import os

filename = 'labelmap_voc.prototxt'

label_ids = []
label_txt = []
with open(filename) as f:
	for line in f:
		ss = [i.strip().strip('\"') for i in line.split(':')]
		if ss[0]=='label':
			label_ids.append(ss[1])
		if ss[0]=='display_name':
			label_txt.append(ss[1])

d = dict(zip(label_ids,label_txt))

with open('labels.txt','w') as f:
	for i in label_ids:
		f.write('%s,%s,%s\n'%(i,i,d[i]))


#!/usr/bin/env python

"""Classes that provide abstractions of different image source manifest lists."""

from typing import List

from docker_registry_client_async import (
    DockerMediaTypes,
    FormattedSHA256,
    Manifest,
    OCIMediaTypes,
)

TYPES = [DockerMediaTypes.DISTRIBUTION_MANIFEST_LIST_V2, OCIMediaTypes.IMAGE_INDEX_V1]

class RegistryV2ManifestList(Manifest):
    """
    Class to retrieve and manipulate image manifest lists.
    """

    @staticmethod
    def is_type(manifest: Manifest) -> bool:
        """
        Checks if the media type of a given manifest is acceptable for this class.

        Args:
            manifest: The manifest to be checked.

        Returns:
            True if the manifest is acceptable, false otherwise.
        """
        return manifest.get_media_type() in TYPES

    def __init__(self, *, manifest: Manifest):
        """
        Args:
            manifest: The raw image manifest value.
        """
        super().__init__(
            manifest=manifest.get_bytes(), media_type=manifest.get_media_type()
        )

    def get_manifests(
        self, *, architecture: str = None, operating_system: str = None
    ) -> List[FormattedSHA256]:
        """
        Retrieves the listing of manifest layer identifiers.

        Args:
            architecture: The name of the CPU architecture.
            operating_system: The name of the operating system.

        Returns:
            list: Manifest identifiers in the form: <hash type>:<digest value>.
        """
        if self.get_media_type() not in TYPES:
            raise NotImplementedError(
                f"Unsupported media type: {self.get_media_type()}"
            )

        result = []
        for manifest in self.get_json()["manifests"]:
            if (
                architecture
                and manifest.get("platform", "").get("architecture", "") != architecture
            ):
                continue
            if (
                operating_system
                and manifest.get("platform", "").get("os", "") != operating_system
            ):
                continue
            result.append(FormattedSHA256.parse(manifest["digest"]))
        return result


from nltk.corpus import stopwords
from nltk.stem.lancaster import LancasterStemmer
import pymysql.cursors

filler_words = stopwords.words('english')
filler_words.append('think')
st = LancasterStemmer()

verbs = [
	"hurt",
	"pain",
	"itch",
	"burn",
	"agitat",
	"spasm",
	"accelerat",
	"aggrevat",
	"sweat",
	"attack",
	"chang",
	"drink",
	"feel",
	"swell",
	"itch",
	"ach",
	"vomit",
	"hear",
	"cough",
]

body_parts = [
	"abdomin",
	"nose",
	"ear",
	"eye",
	"feet",
	"teeth",
	"leg",
	"throat",
	"chest",
	"heart",
	"lung",
	"back",
	"head",
	"finger",
	"toe",
	"anus",
	"knees",
	"waist",
	"thigh",
	"tongue",
	"neck",
	"shoulder",
	"joint",
	"mouth",
	"blood",

]

body_part_association = {
	"teeth":"tooth",
	"tooth":"teeth",
	"feet":"foot",
	"foot":"feet",
}

body_parts_conversion = {
	"stomach": "abdominal",
	"tummy": "abdominal",
	"poop": "stools",
	"butt":"anus",
	"pee":"urin",
	"threw":"vomit",
	"sore":"itch",
}

def decode(phrase, data):
	word_list = phrase.split(" ")
	filtered_words = [word for word in word_list if word not in filler_words]
	temp = " ".join(filtered_words)
	if temp in data.keys():
		return data[temp]

	for index in range(len(filtered_words)):
		if filtered_words[index] in body_parts_conversion.keys():
			filtered_words[index] = body_parts_conversion[filtered_words[index]]
		if filtered_words[index] not in body_parts:
			filtered_words[index] = st.stem(filtered_words[index])

	phrase_verbs = []
	phrase_body_parts = []

	for word in filtered_words:
		if word in verbs:
			phrase_verbs.append(word)
		elif word in body_parts:
			phrase_body_parts.append(word)
			if word in body_part_association.keys():
				phrase_body_parts.append(body_part_association[word])

	related = []

	for body_part in phrase_body_parts:
		for symptom in data.keys():
			if body_part in symptom:
				related.append(symptom)

	if len(related) > 0:
		temp = []
		for symptom in related:
			for verb in phrase_verbs:
				if verb in symptom:
					temp.append(symptom)

		if len(temp) is 0:
			for symptom in related:
				for verb in verbs:
					if verb in symptom:
						temp.append(symptom)

		if len(temp) is not 0:
			related = temp

	if len(related) is 0:
		for verb in phrase_verbs:
			for symptom in data.keys():
				if verb in symptom:
					related.append(symptom)

	if len(related) is 0:
		return ""
	else:
		return data[related[0]]

def load_data():
	data = {}
	connection = pymysql.connect(
							 host='localhost',
                             user='root',
                             password='',
                             db='alexa_md',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
	with connection.cursor() as cursor:
		cursor.execute("SELECT * FROM symptoms")
		fetched = cursor.fetchall()

		for fetch in fetched:
			data[fetch['symptom']] = fetch['id']

	connection.close()

	return data

def get_symptom_ids(symptoms):
	symptom_ids = []
	data = load_data()

	for symptom in symptoms:
		if symptom in data.keys():
			symptom_ids.append(data[symptom])
		else:
			symptom_ids.append(decode(symptom.lower(), data))

	return symptom_ids


"""
author : Julien SEZNEC
Download raw data from R6A - Yahoo! Front Page Today Module User Click Log Dataset, version 1.0 (1.1 GB)
(https://webscope.sandbox.yahoo.com/catalog.php?datatype=r)
and put the content of the unzip dataset 'R6' in ./data/R6A/
Then, you can run this script which outputs arm's reward plot and data for each day in ./data/Reward.
"""
import pandas as pd
import logging
from datetime import datetime
from matplotlib import pyplot as plt
import gzip
import os

logging.getLogger('matplotlib.font_manager').disabled = True
plt.style.use('seaborn-colorblind')
plt.style.use('style.mplstyle')

logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.DEBUG)

def merge_datasets():
    """
    Merge the 10 files and keep the three useful columns ['timestamp', 'article_id', 'click'] in out.csv
    """
    out = open("./Reward/R6A/out.csv", "a+")
    out.write('timestamp article_id click\n')
    for j in range(10):
        f = gzip.open("./Reward/R6A/ydata-fp-td-clicks-v1_0.20090" + str(501 + j) + '.gz', "r")
        for i, line in enumerate(f.readlines()):
            if i % 10000 == 0:
                logging.info("./Reward/R6A/ydata-fp-td-clicks-v1_0.20090" + str(501 + j) + ' : ' + str(i))
            out.write(line.decode('utf-8').split('|')[0][:-1] + '\n')

def prepare_dataset():
    """
    Download out.csv, cast the right datatypes and convert date
    :return: Dataframe - columns =  ['timestamp', 'article_id', 'click', 'date']
    """
    df = pd.read_csv('./Reward/R6A/out.csv', usecols=['timestamp', 'article_id', 'click'], sep=' ')
    df = df.astype({'timestamp': int, 'article_id': int, 'click': bool})
    df['date'] = df.timestamp.apply(lambda dt: datetime.fromtimestamp(dt))
    return df

def compute_average(df):
    """
    Compute 1) rolling average of N sample ; 2) Average for each timestamp of the rolling average
    (one value per timestamp)
    :return: dataframe of the average click probabilities.  columns = article_id ; index = date
    """
    rolling_mean = df.groupby('article_id').click.rolling(30000, min_periods=14000, center=True).mean()
    rolling_mean.index = rolling_mean.index.droplevel(0)
    rolling_mean.name = 'click_mean'
    df_with_rolling = df.join(pd.DataFrame(rolling_mean), how='inner')
    final_mean = df_with_rolling.groupby(['article_id', 'date']).click_mean.mean().unstack().transpose()
    return final_mean

def compute_traffic(df):
    """
    :return: Series. The total traffic (user count) for each timestamp.
    """
    return df.date.value_counts().sort_index()

def split_dataset(df, traffic, freq=10):
    """
    Split the dataset in 10 days with one value per round (i.e. 10 user).
    :return: list of 10 Series (cast article_id on a list of mean rewards)
    """
    dfs = []
    for i in range(1, 11):
        if len(str(i)) == 1:
            dfs.append(
                df[(df.index >= '2009-05-0' + str(i) + ' 00:00:00') & (df.index < '2009-05-0' + str(i) + ' 12:00:00')])
        else:
            dfs.append(
                df[(df.index >= '2009-05-' + str(i) + ' 00:00:00') & (df.index < '2009-05-' + str(i) + ' 12:00:00')])
    dfs = [df[df.columns[~df.isnull().any()]] if len(df) else pd.DataFrame() for df in dfs]
    dfs = [d.apply(lambda row: row.apply(lambda x: [x])) for d in dfs]
    dfs = [
        d.apply(lambda col: col * traffic.loc[col.index])
            .sum()
            .apply(lambda liste: pd.Series(liste[::freq])) for d in dfs
    ]
    for i, d in enumerate(dfs):
        d.to_csv('./Reward/reward_data_day_%s.csv' % (i + 1))
    return dfs

def plot_reward(df, i,freq=1000):
    """
    Plot the reward functions.
    """
    fig, ax = plt.subplots(figsize=(12, 10))
    df.apply(lambda data: ax.plot(range(len(data))[::freq], data[::freq]), axis=1)
    ax.set_ylim([0, 0.075])
    ax.set_xlabel('Round (t)')
    ax.set_ylabel("Arms Average Reward")
    ax.set_title("Day %s - $K = %s$" % (i + 1, len(df)), y= 1.03)
    fig.savefig("./Reward/reward_plot_day%s.pdf" % (i + 1), dpi = 600)

if __name__ == '__main__':
    os.makedirs('./Reward/', exist_ok=True)
    if not os.path.isfile('./Reward/R6A/out.csv'):
        merge_datasets()
    logging.info("Prepare dataset")
    df = prepare_dataset()
    logging.info("Compute average")
    df_average = compute_average(df)
    logging.info("Compute traffic")
    traffic = compute_traffic(df)
    logging.info("Split dataset")
    dfs = split_dataset(df_average, traffic)
    for i, df in enumerate(dfs):
        plot_reward(df, i)


#
#  Project: MXCuBE
#  https://github.com/mxcube
#
#  This file is part of MXCuBE software.
#
#  MXCuBE is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  MXCuBE is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with MXCuBE.  If not, see <http://www.gnu.org/licenses/>.

"""Module contains classes defining graphical objects in MXCuBE"""

from mxcubeqt.utils import property_bag, qt_import

DEFAULT_MARGIN = 2
DEFAULT_SPACING = 2
DEFAULT_ALIGNMENT = "top center"

__license__ = "LGPLv3+"

class _CfgItem(object):
    """Configuration item base class"""

    def __init__(self, name=None, item_type=""):
        self.name = name
        self.type = item_type
        self.children = []
        self.connections = []

        self.signals = {}
        self.slots = {}

        self.properties = property_bag.PropertyBag()
        self.properties.add_property(
            "alignment",
            "combo",
            (
                "none",
                "top center",
                "top left",
                "top right",
                "bottom center",
                "bottom left",
                "bottom right",
                "center",
                "hcenter",
                "vcenter",
                "left",
                "right",
            ),
            "none",
        )

    def set_properties(self, properties):
        """Set properties
           Add new properties (if any) and remove odd ones (if any)
        """
        for item_property in properties:
            if hasattr(item_property, "get_name"):
                prop_name = item_property.get_name()
                if prop_name in self.properties.properties:
                    self.properties.get_property(prop_name).set_value(
                        item_property.get_user_value()
                    )
                elif item_property.hidden or prop_name.startswith("closable_"):
                    self.properties[prop_name] = item_property
                elif item_property.hidden or prop_name.startswith("newdialog_"):
                    self.properties[prop_name] = item_property
            else:
                if item_property["type"] == "combo":
                    arg1 = item_property["choices"]
                else:
                    arg1 = item_property["value"]
                arg2 = item_property["default_value"]
                self.properties.add_property(
                    property_name=item_property["name"],
                    property_type=item_property["type"],
                    arg1=arg1,
                    arg2=arg2,
                    comment=item_property["comment"],
                    hidden=item_property["hidden"],
                )

    def __getitem__(self, item):
        try:
            return getattr(self, item)
        except AttributeError:
            raise KeyError(item)

    def __setitem__(self, item, value):
        setattr(self, item, value)

    def __repr__(self):
        return repr(self.__dict__)

    def rename(self, new_name):
        self.name = new_name

class ContainerCfg(_CfgItem):
    """Container configuration"""

    def __init__(self, *args):
        _CfgItem.__init__(self, *args)

        self.properties.add_property("label", "string", "")
        self.properties.add_property("icon", "string", "")
        self.properties.add_property("spacing", "integer", DEFAULT_SPACING)
        self.properties.add_property("margin", "integer", DEFAULT_MARGIN)
        self.properties.add_property("color", "color", None)
        self.properties.add_property(
            "hsizepolicy", "combo", ("fixed", "expanding", "default"), "default"
        )
        self.properties.add_property(
            "vsizepolicy", "combo", ("fixed", "expanding", "default"), "default"
        )
        self.properties.add_property(
            "frameshape",
            "combo",
            ("Box", "Panel", "StyledPanel", "HLine", "VLine", "default"),
            "default",
        )
        self.properties.add_property(
            "shadowstyle", "combo", ("plain", "raised", "sunken", "default"), "default"
        )
        self.properties.add_property("fixedwidth", "integer", -1)
        self.properties.add_property("fixedheight", "integer", -1)

    def add_child(self, item):
        self.children.append(item)
        return ""

    def child_property_changed(self, child_name, property_name, old_value, new_value):
        pass

    def update_slots(self):
        pass

    def remove_child(self, child_index):
        del self.children[child_index]

class WindowCfg(ContainerCfg):
    """Window configuration item. Contains extra properties to customize window"""

    def __init__(self, *args):
        ContainerCfg.__init__(self, *args)

        self.type = "window"
        self.properties.add_property("caption", "string", "")
        self.properties.add_property("show", "boolean", True)
        self.properties.add_property("closeOnExit", "boolean", True)
        self.properties.add_property("keepOpen", "boolean", False)
        self.properties.add_property("menubar", "boolean", False)
        self.properties.add_property("statusbar", "boolean", False)
        self.properties.add_property("menudata", "", {}, hidden=True)
        self.properties.add_property("expertPwd", "string", "tonic")
        self.properties.add_property("fontSize", "integer", 12)

        self.signals.update(
            {"isShown": (), "isHidden": (), "enableExpertMode": (), "quit": ()}
        )
        self.slots.update(
            {"show": (), "hide": (), "setCaption": (), "exitExpertMode": ()}
        )

class TabCfg(ContainerCfg):
    def __init__(self, *args):
        ContainerCfg.__init__(self, *args)
        self.widget = None

        self.properties.add_property("fontSize", "integer", 0)
        self.signals.update({"notebookPageChanged": "pageName"})

    def __repr__(self):
        if hasattr(self, "widget"):
            widget = getattr(self, "widget")
        else:
            r = repr(self.__dict__)

        delattr(self, "widget")
        r = repr(self.__dict__)
        self.widget = widget
        return r

    def add_child(self, item):
        if isinstance(item, ContainerCfg):
            return ContainerCfg.add_child(self, item)
        else:
            return "Tabs can only have container children."

    def child_property_changed(self, child_name, property_name, old_value, new_value):
        if property_name == "label":
            self.update_slots()

    def remove_child(self, child_index):
        ContainerCfg.remove_child(self, child_index)
        self.update_slots()

    def update_slots(self):
        closable_props = {}
        new_dialog_props = {}
        for prop in self.properties:
            if hasattr(prop, "name"):
                if prop.name.startswith("closable_"):
                    closable_props[prop.name] = prop.get_value()
                elif prop.name.startswith("newdialog_"):
                    closable_props[prop.name] = prop.get_value()
            else:
                if prop["name"].startswith("closable_"):
                    closable_props[prop["name"]] = prop["value"]
                if prop["name"].startswith("newdialog_"):
                    closable_props[prop["name"]] = prop["value"]

        for prop_name in closable_props.keys():
            self.properties.del_property(prop_name)
        for prop_name in new_dialog_props.keys():
            self.properties.del_property(prop_name)

        self.slots = {}
        for child in self.children:
            if "label" in child["properties"].properties:
                child_lbl = child["properties"]["label"]
                child_lbl = child_lbl.replace(" ", "_")
                self.properties.add_property(
                    "closable_%s" % child_lbl,
                    "boolean",
                    closable_props.get("closable_%s" % child_lbl, False),
                )
                self.properties.add_property(
                    "newdialog_%s" % child_lbl,
                    "boolean",
                    closable_props.get("newdialog_%s" % child_lbl, False),
                )
                slot_name = "showPage_%s" % child_lbl
                self.slots[slot_name.replace(" ", "_")] = ()
                slot_name = "hidePage_%s" % child_lbl
                self.slots[slot_name.replace(" ", "_")] = ()
                slot_name = "enablePage_%s" % child_lbl
                self.slots[slot_name.replace(" ", "_")] = ()
                slot_name = "enableTab_%s" % child_lbl
                self.slots[slot_name.replace(" ", "_")] = ()
                slot_name = "incTabCount_%s" % child_lbl
                self.slots[slot_name.replace(" ", "_")] = ()
                slot_name = "resetTabCount_%s" % child_lbl
                self.slots[slot_name.replace(" ", "_")] = ()

    def notebook_page_changed(self, new_tab_label):
        new_tab_label = new_tab_label.replace(" ", "_")
        if self.properties.get_property("closable_%s" % new_tab_label).get_value():
            self.widget.close_tab_button.show()
        else:
            self.widget.close_tab_button.hide()
        if self.properties.get_property("newdialog_%s" % new_tab_label).get_value():
            self.widget.open_in_dialog_button.show()
        else:
            self.widget.open_in_dialog_button.hide()

class SplitterCfg(ContainerCfg):
    def __init__(self, *args):
        ContainerCfg.__init__(self, *args)

        self.properties.add_property("sizes", "string", "[]", hidden=True)
        for key in [
            qt_import.Qt.Key_F9,
            qt_import.Qt.Key_F10,
            qt_import.Qt.Key_F11,
            qt_import.Qt.Key_F12,
        ]:
            self.properties.add_property("sizes_%d" % key, "string", "[]", hidden=True)

class GroupBoxCfg(ContainerCfg):
    def __init__(self, *args):
        ContainerCfg.__init__(self, *args)

        self.properties.add_property("checkable", "boolean", False)
        self.properties.add_property("checked", "boolean", False)

class SpacerCfg(_CfgItem):
    def __init__(self, *args):
        _CfgItem.__init__(self, *args)

        self.properties.add_property("fixed_size", "boolean", False)
        self.properties.add_property("size", "integer", 100)

class LabelCfg(_CfgItem):
    def __init__(self, *args):

        _CfgItem.__init__(self, *args)

        self.properties.add_property("text", "string", "")
        self.properties.add_property("fontSize", "integer", 0)

class IconCfg(_CfgItem):
    def __init__(self, *args):
        _CfgItem.__init__(self, *args)

        self.properties.add_property("filename", "file", "")

class BrickCfg(_CfgItem):
    def __init__(self, name, brick_type, brick=None):

        _CfgItem.__init__(self, name, brick_type)

        self.name = name
        self.type = brick_type

        self.brick = brick

        # bricks have their own thing for signals and slots
        del self.signals
        del self.slots

        # bricks have their own thing for properties
        if brick is not None:
            self.set_properties(brick.property_bag)

    def set_properties(self, properties):
        self.brick.set_persistent_property_bag(properties)
        self.properties = self.brick.property_bag

    def rename(self, new_name):
        _CfgItem.rename(self, new_name)

        if self.brick is not None:
            self.brick.setObjectName(new_name)


from array import array
from re import T
import pygame
import math
import random
from turtle import right, title
from multipledispatch import dispatch
import time
start_time = time.time()
pygame.init()

class DrawInfo:
    BLACK = (0, 0, 0)
    WHITE = (255, 255 ,255)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    MAGENTA = (255, 0, 255)
    CYAN = (0, 255, 255)
    BLUE = (0, 0, 255)
    BACKGROUND_COLOR = WHITE

    GREYS = [ (128, 128, 128),
              (160, 160, 160),
              (192, 192, 192) ]

    FONT = pygame.font.SysFont('tahoma', 30)
    LARGE_FONT = pygame.font.SysFont('tahoma', 40)

    SIDE_PAD = 100
    TOP_PAD = 150

    DELAY = 0.02

    def __init__(self, width, height, arr):
        self.width = width
        self.height = height

        self.window = pygame.display.set_mode((width, height))
        pygame.display.set_caption("Sorting Visualizer")
        self.set_arr(arr)

    def set_arr(self, arr):
        self.arr = arr
        self.max_val = max(arr)
        self.min_val = min(arr)

        self.block_width = round((self.width - self.SIDE_PAD) / len(arr))
        self.block_height = (self.height - self.TOP_PAD) / (self.max_val - self.min_val)
        self.start_x = self.SIDE_PAD // 2

def draw(draw_info, algo_name, ascending):
     draw_info.window.fill(draw_info.BACKGROUND_COLOR)

     title = draw_info.LARGE_FONT.render(f"{algo_name} - {'Ascending' if ascending else 'Descending'}", 1, draw_info.RED)
     draw_info.window.blit(title, (draw_info.width/2 - title.get_width()/2 , 0))

     controls = draw_info.FONT.render("R - Reset | SPACE - Start Sorting | A - Ascending | D - Decending", 1, draw_info.BLACK)
     draw_info.window.blit(controls, (draw_info.width/2 - controls.get_width()/2 , 50))

     sorting = draw_info.FONT.render("B - Bubble Sort | Q - QuickSort | M - MergeSort | H - HeapSort", 1, draw_info.BLACK)
     draw_info.window.blit(sorting, (draw_info.width/2 - sorting.get_width()/2 , 80))

     draw_array(draw_info)
     pygame.display.update()

def draw_array(draw_info, color_positions = {}, clear_bg = False):
    arr = draw_info.arr

    if clear_bg:
        clear_rect = (draw_info.SIDE_PAD // 2, 7 * draw_info.TOP_PAD // 8,
                      draw_info.width - draw_info.SIDE_PAD, draw_info.height)
        pygame.draw.rect(draw_info.window, draw_info.BACKGROUND_COLOR, clear_rect)

    for i, val in enumerate(arr):
        x = draw_info.start_x + (i * draw_info.block_width)
        y = draw_info.height - ((val - draw_info.min_val) * draw_info.block_height)
        color = draw_info.GREYS[i % 3]
        if i in color_positions:
            color = color_positions[i]
        pygame.draw.rect(draw_info.window, color, (x, y, draw_info.block_width, draw_info.height))

    if clear_bg:
        pygame.display.update()

def generate_starting_array(n, min_val, max_val):
     arr = [0] * n
     for i in range(n):
        val = random.randint(min_val, max_val)
        arr[i] = val
     return arr

def perform_chosen_algo(chosen_sorting_algo, draw_info, ascending, arr):
    if chosen_sorting_algo is bubbleSort:
        while(True):
            try:
                next(chosen_sorting_algo(draw_info, ascending, arr, 0, len(arr) - 1))
            except StopIteration:
                break
    else:
        chosen_sorting_algo(draw_info, ascending, arr, 0 , len(arr) - 1)
    yield True

@dispatch(list)
def quickSort(arr):
    quickSort(arr, 0, len(arr)-1)

@dispatch(DrawInfo, bool, list, int, int)
def quickSort(draw_info, ascending, arr, p, r):
    if p < r:
        #yield True
        partition_generator = partition(arr, p, r, draw_info, ascending)
        while True:
            try:
                next(partition_generator)
            except StopIteration as pivot:
                q = pivot.value
                break
        quickSort(draw_info, ascending, arr, p, q-1)
        quickSort(draw_info, ascending, arr, q+1, r)

def partition(arr, p, r, draw_info, ascending):
    x = arr[r]  # pivot
    i = p - 1
    for j in range(p,r):
        if (arr[j] <= x and ascending) or (arr[j] >= x and not ascending):
            i += 1
            swap(arr, i, j)
            draw_array(draw_info, {i: draw_info.MAGENTA, j: draw_info.CYAN}, True)
            time.sleep(draw_info.DELAY)
            yield True

    swap(arr, i+1, r)
    return i+1

def swap(arr, i, j):
    temp = arr[j]
    arr[j] = arr[i]
    arr[i] = temp

@dispatch(list)
def mergeSort(arr):
    mergeSort(arr, 0, len(arr)-1)

@dispatch(DrawInfo, bool, list, int, int)
def mergeSort(draw_info, ascending, arr, p, r):
    if p < r:
        mid = (p+r) // 2
        mergeSort(draw_info, ascending, arr, mid+1, r)
        mergeSort(draw_info, ascending, arr, p, mid)
        merge_generator = merge(draw_info, ascending, arr, p, mid, r)
        while True:
            try:
                next(merge_generator)
            except StopIteration as pivot:
                #q = pivot.value
                break

def merge(draw_info, ascending, arr, p, mid, r):
    inf = float('inf') if ascending else float('-inf')
    n1 = mid - p + 1; n2 = r - mid
    left = [0] * (n1+1)
    right = [0] * (n2+1)
    left[n1] = inf; right[n2] = inf
    for t in range(p, r+1):
        if t <= mid:
            left[t-p] = arr[t]
        else:
            right[t-mid-1] = arr[t]
    i = 0; j = 0; idx = 0
    for k in range(p, r+1):
        if left[i] <= right[j] and ascending or left[i] >= right[j] and not ascending:
            idx = i
            arr[k] = left[i]
            i += 1
        else:
            idx = j
            arr[k] = right[j]
            j += 1
        draw_array(draw_info, {k: draw_info.MAGENTA, idx: draw_info.CYAN}, True)
        time.sleep(draw_info.DELAY)
        yield True

def heapify(draw_info, ascending, arr, n, i):
    if ascending:
        compare = lambda x, y: x > y
    else:
        compare = lambda x, y: x < y

    largest = i  # Initialize the largest element as the root
    left = 2 * i + 1  # Left child index
    right = 2 * i + 2  # Right child index

    # Check if left child exists and is larger than the root
    if left < n and compare(arr[left], arr[largest]):
        largest = left

    # Check if right child exists and is larger than the root
    if right < n and compare(arr[right], arr[largest]):
        largest = right

    # If the largest element is not the root, swap them
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]  # Swap
        draw_array(draw_info, {largest: draw_info.MAGENTA, i: draw_info.CYAN}, True)
        time.sleep(draw_info.DELAY)
        heapify(draw_info, ascending, arr, n, largest)  # Recursively heapify the affected sub-tree

def heapSort(draw_info, ascending, arr, p, r):
    n = len(arr)

    # Build a max-heap
    for i in range(n // 2 - 1, -1, -1):
        heapify(draw_info, ascending, arr, n, i)

    # Extract elements one by one from the heap
    for i in range(n - 1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i]  # Swap the current root with the last element
        draw_array(draw_info, {0: draw_info.MAGENTA, i: draw_info.CYAN}, True)
        time.sleep(draw_info.DELAY)
        heapify(draw_info, ascending, arr, i, 0)  # Heapify the reduced heap

@dispatch(DrawInfo, bool, list)
def bubbleSort(draw_info, ascending, arr):
    bubbleSort(draw_info, ascending, arr, 0, len(arr) - 1)

@dispatch(DrawInfo, bool, list, int, int)
def bubbleSort(draw_info, ascending, arr, p , r):
    n = r - p + 1
    for i in range(1, n):
        swapped = False
        for j in range(p, r - i + 1):
            if (arr[j] > arr[j+1] and ascending) or (arr[j] < arr [j+1] and not ascending):
                swap(arr, j, j+1)
                draw_array(draw_info, {j: draw_info.MAGENTA, j + 1: draw_info.CYAN}, True)
                time.sleep(draw_info.DELAY)
                swapped = True
                yield True
        if not swapped:
            return;

def is_sorted(arr, ascending):
    return (all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) if ascending
            else all(arr[i] >= arr[i + 1] for i in range(len(arr) - 1)))

def main():
    run = True
    clock = pygame.time.Clock()
    n = 70; min_val = 1; max_val = 100
    arr = generate_starting_array(n, min_val, max_val)
    draw_info = DrawInfo(1000, 600, arr)
    sorting = False
    ascending = True
    sorting_algo = bubbleSort
    sorting_algo_name = "Bubble Sort"
    sorting_algo_generator = None

    while run:
        clock.tick(60)
        if sorting:
            try:
                next(sorting_algo_generator)
            except StopIteration:
                sorting = False
        else:
            draw(draw_info, sorting_algo_name, ascending)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type != pygame.KEYDOWN:
                continue
            if event.key == pygame.K_r:
                arr = generate_starting_array(n, min_val, max_val)
                draw_info.set_arr(arr)
                sorting = False
            elif event.key == pygame.K_SPACE and sorting == False:
                if not is_sorted(arr, ascending):
                    sorting = True
                    sorting_algo_generator = perform_chosen_algo(sorting_algo, draw_info, ascending, arr)
            elif event.key == pygame.K_a and not sorting:
                ascending = True
            elif event.key == pygame.K_d and not sorting:
                ascending = False
            elif event.key == pygame.K_q and not sorting:
                sorting_algo = quickSort
                sorting_algo_name = "QuickSort"
            elif event.key == pygame.K_m and not sorting:
                sorting_algo = mergeSort
                sorting_algo_name = "MergeSort"
            elif event.key == pygame.K_h and not sorting:
                sorting_algo = heapSort
                sorting_algo_name = "HeapSort"
            elif event.key == pygame.K_b and not sorting:
                sorting_algo = bubbleSort
                sorting_algo_name = "Bubble Sort"

    pygame.quit()

if __name__ == "__main__":
    main()

arr = [34,2,7,2,9,29,-14,16,89,76,35,104,32,18,1203,156,1367,1785,352,573, 10000, 10000000, 999999,10000000,19030303,10339,20193,5256,2672]
#mergeSort(arr)
quickSort(arr)
#bubbleSort(arr)
print(arr)
duration = round((time.time() - start_time)*1000,3)
print("Process finished in %sms" %duration)


import requests

api_key = 'YOUR_API_KEY'
origin = f'{startLat},{startLng}'
destination = f'{endLat},{endLng}'

url = f'https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&mode=bicycling&key={api_key}'

response = requests.get(url)
data = response.json()
duration = data['routes'][0]['legs'][0]['duration']['text']
print(duration)


from xoeuf.osv.writers import ORMWriter as get_writer  # noqa

orm_writer = get_writer

from xoeuf.osv.writers import ORMCreator as get_creator  # noqa

orm_creator = get_creator

def get_treeview_action(self, **options):
    """Return the tree view action for `self`.

    If the `self` is a singleton, return the view type 'form' so that it's
    easier to see the full object.

    :rtype: An action `dict` you can return to the web client.

    `options` is used to override **almost any** key in the returned dict.  An
    interesting option is `target`.

    """
    _, _, context = self.env.args
    ids = self.ids
    if not ids or len(ids) > 1:
        vtype = "list"
        active_id = None
    else:
        vtype = "form"
        active_id = ids[0]
    result = {
        "type": "ir.actions.act_window",
        "res_model": self._name,
        "src_model": False,
        "view_id": False,
        "view_type": vtype,
        "view_mode": "list,form",
        "views": [(False, "list"), (False, "form")],
        "target": "current",
        "context": context,
    }
    if ids:
        result["domain"] = [("id", "in", tuple(ids))]
    if active_id:
        result["active_id"] = active_id
    result.update(options)
    return result

def get_ref(self, xmlid, depth=1):
    """Get the XMLID in the caller's addon.

    If `xmlid` is missing the addon, then will try to guess it from the
    `calling addon <xoeuf.modules.get_caller_addon>`:func:.

    `depth` is passed directly to `~xoeuf.modules.get_caller_addon`:func:.

    """
    if "." in xmlid:
        return self.env.ref(xmlid)
    else:
        from xoeuf.modules import get_caller_addon

        addon = get_caller_addon(depth=depth)
        return self.env.ref(addon + "." + xmlid)


from pyaxidraw import axidraw   # import module
ad = axidraw.AxiDraw()          # Initialize class
ad.interactive()                # Enter interactive context
if not ad.connect():            # Open serial port to AxiDraw;
    quit()                      #   Exit, if no connection.
ad.moveto(1, 1)                 # Pen-up move to (1, 1) inch
ad.options.units = 1            # set working units to cm.
ad.options.speed_pendown = 10   # set pen-down speed to 10%
ad.update()                     # Process changes to options
ad.move(5.08, 5.08)             # Relative move: (2, 2) inches
ad.moveto(0,0)                  # Pen-up move, back to origin.
ad.disconnect()                 # Close serial port to AxiDraw


import mimetypes
import werkzeug
from functools import wraps

from flask import Flask, send_file, request, Response, render_template
from flask.ext.restful import Api, Resource, reqparse, fields, marshal_with
from flask_cors import CORS
from werkzeug.exceptions import Unauthorized

from image_service.storage import *

CONFIG_STORAGE_DIR = 'STORAGE_DIRECTORY'

app = Flask(__name__)
app.config.from_pyfile('../config.py', silent=True)
api = Api(app)
cors = CORS(app, resources={r'/*': {'origins': '*'}})

_storage = None

@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Headers'] = ', '.join((
            'Origin',
            'X-Requested-With',
            'Content-Type',
            'Accept',
            'Cache-Control',
            'Authorization'
    ))
    return response

def storage():
    """returns access to the storage (save_image(), get() and exists())"""
    global _storage
    if not _storage:
        _storage = FileSystemStorage(app.config[CONFIG_STORAGE_DIR])
    return _storage

def _serve_image(image_file, extension):
    mime_type = mimetypes.types_map['.%s' % extension.lower()]
    return send_file(image_file, mimetype=mime_type, add_etags=False)

def _check_auth_token(origin, token):
    if 'AUTH_TOKEN' in app.config and app.config['AUTH_TOKEN'] != '':
        expected_origin, expected_token = app.config['AUTH_TOKEN']
        return (expected_origin == '*' or expected_origin == origin) and expected_token == token

def _check_auth_basic(username, password):
    if 'AUTH_BASIC' in app.config and app.config['AUTH_BASIC'] != '':
        correct_user, correct_pass = app.config['AUTH_BASIC']
        return username == correct_user and password == correct_pass

@app.route('/')
def index():
    if app.config['ENABLE_DEMO']:
        return render_template('demo.html')
    return Response('Nothing to see here ;)', 404)

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # check if it has auth token
        auth_header = request.headers.get('Authorization')
        origin = request.headers.get('Origin')
        if auth_header is not None:
            if auth_header.startswith('Token'):
                # get the origin header
                key, token = auth_header.split(' ')
                if _check_auth_token(origin, token):
                    return f(*args, **kwargs)
            if auth_header.startswith('Basic'):
                auth = request.authorization
                if _check_auth_basic(auth.username, auth.password):
                    return f(*args, **kwargs)
        raise Unauthorized()
    return decorated

def _upload_json_response(success, **kwargs):
    res_dict = dict(status='ok' if success else 'fail')
    res_dict.update(kwargs)
    code = 201 if success else 500
    return res_dict, code

def serve_image(project_name, name, extension, mode=None, size=None):
    if project_name not in app.config['PROJECTS']:
        raise NotFound()
    return _serve_image(project_name, name, extension, mode, size)

class UploadResponse:
    resource_fields = {
        'url': fields.String
    }

class UploadAPI(Resource):
    """
    API that supports POST for images.
    """
    decorators = [requires_auth]

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('file', type=werkzeug.datastructures.FileStorage, required=True,
                                   help='No file provided', location='files')
        super(UploadAPI, self).__init__()

    @marshal_with(UploadResponse.resource_fields)
    def post(self):
        args = self.reqparse.parse_args()
        uploaded_file = args['file']
        filename, extension = secure_filename(uploaded_file.filename).rsplit(
            '.', 1)
        filename = storage().safe_name(filename, extension)
        storage().save(filename, extension, uploaded_file.read())
        url = api.url_for(ImageAPI, name=filename, extension=extension)
        return {'url': url}, 201

class ImageAPI(Resource):
    """
    API that supports GET, PUT and DELETE for images.
    """

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('file', type=werkzeug.datastructures.FileStorage, required=True,
                                   help='No file provided', location='files')
        super(ImageAPI, self).__init__()

    @requires_auth
    def put(self, name, extension):
        args = self.reqparse.parse_args()
        uploaded_file = args['file']
        created = not storage().exists(name, extension)
        storage().save(name, extension, uploaded_file.read())
        return Response('', 201 if created else 200)

    @requires_auth
    def delete(self, project, name, extension):
        if storage().exists(project, name, extension):
            storage().delete(project, name, extension)
            return Response('', 200)
        raise NotFound()

    def get(self, name, extension):
        image = storage().get(name, extension)
        return _serve_image(image, extension)

class ManipulatedImageAPI(Resource):
    """
    API that supports GET for manipulated images.
    """

    def get(self, name, mode, width, height, extension):
        try:
            image = storage().get(name, extension, mode, (int(width), int(height)))
        except ValueError:
            raise NotFound()
        return _serve_image(image, extension)

api.add_resource(UploadAPI, '/images/')
api.add_resource(ImageAPI, '/images/<name>.<extension>')
api.add_resource(ManipulatedImageAPI, '/images/<name>@<mode>-<width>x<height>.<extension>')


#Python Functions
#Example of return
def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    if num >= 0:
        return num
    else:
        return -num

print(absolute_value(2))

print(absolute_value(-4))

#Scope and Lifetime Variables
def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

#Python Function Arguments
#Variable Function Arguments
def greet(name, msg="Good morning!"):
    """
    This function greets to
    the person with the
    provided message.

    If the message is not provided,
    it defaults to "Good
    morning!"
    """

    print("Hello", name + ', ' + msg)

greet("Kate")
greet("Bruce", "How do you do?")

#Python Arbitrary Arguments
def greet(*names):
    """This function greets all
    the person in the names tuple."""

    # names is a tuple with arguments
    for name in names:
        print("Hello", name)

greet("Monica", "Luke", "Steve", "John")

#Python Recursion
#Example of a recursive function
def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

#Python anonymous/Lambda Function
#Example of Lambda Function in python

# Program to show the use of lambda functions
double = lambda x: x * 2

print(double(5))

#Python global, local, non-local
#Create a Global Variable
x = "global"

def foo():
    print("x inside:", x)

foo()
print("x outside:", x)

# Create a Local Variable

def foo():
    y = "local"
    print(y)

foo()

#Using Global and Local variables in the same code
x = "global "

def foo():
    global x
    y = "local"
    x = x * 2
    print(x)
    print(y)

foo()

#Create a nonlocal variable
def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)

outer()

#Python Global Keyword
#Accessing global Variable From Inside a Function
c = 1 # global variable

def add():
    print(c)

add()

# Changing Global Variable From Inside a Function using global
c = 0 # global variable

def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)

add()
print("In main:", c)


from welcome import display_welcome_message
from weather import obter_localizacao_por_ip, obter_clima

if __name__ == "__main__":
    display_welcome_message()

    cidade_usuario = obter_localizacao_por_ip()
    print(f"Localização detectada: {cidade_usuario}")

    resposta_correta = input("Essa é a localização correta? (sim/não): ").lower()
    while resposta_correta != 'sim':
        cidade_usuario = input("Digite o nome da cidade correta: ")
        resposta_correta = input("Essa é a localização correta? (sim/não): ").lower()

    obter_clima(cidade_usuario)


import urllib.request, urllib.parse, urllib.error
import twurl
import json
import ssl

# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py

TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    print('')
    acct = input('Enter Twitter Account:')
    if (len(acct) < 1): break
    url = twurl.augment(TWITTER_URL,
                        {'screen_name': acct, 'count': '5'})
    print('Retrieving', url)
    connection = urllib.request.urlopen(url, context=ctx)
    data = connection.read().decode()

    js = json.loads(data)
    print(json.dumps(js, indent=2))

    headers = dict(connection.getheaders())
    print('Remaining', headers['x-rate-limit-remaining'])

    for u in js['users']:
        print(u['screen_name'])
        if 'status' not in u:
            print('   * No status found')
            continue
        s = u['status']['text']
        print('  ', s[:50])


class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """

    def maxProfit(self, prices):
        if len(prices) < 2:
            return 0

        h1 = h2 = -max(prices)
        s1 = s2 = 0

        for price in prices:
            s1 = max(s1, h1 + price)
            s2 = max(s2, h2 + price)
            h1 = max(h1, - price)
            h2 = max(h2, s1 - price)
        return s2

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """

    def maxProfit(self, prices):
        if len(prices) < 2:
            return 0

        n = len(prices)
        k = 2
        dp = [[0] * n for _ in range(k + 1)]

        for i in range(1, k + 1):
            maxDiff = -float('inf')
            for j in range(1, n):
                maxDiff = max(maxDiff, dp[i - 1][j - 1] - prices[j - 1])
                dp[i][j] = max(dp[i][j - 1], prices[j] + maxDiff)
        return dp[k][n - 1]

"""
timeout
"""
class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """

    def maxProfit(self, prices):
        memo = {}
        return self.dfs(prices, 0, 0, 2, 2, memo)

    def dfs(self, prices, index, profit, buy_times, sell_times, memo):

        if buy_times == 0 and sell_times == 0:
            return profit

        if index == len(prices):
            return profit

        key = (index, buy_times, sell_times, profit)
        if key in memo:
            return memo[key]
        ans = -float('inf')
        if buy_times == sell_times and buy_times > 0:
            ans = max(ans, self.dfs(prices, index + 1, profit - prices[index], buy_times - 1, sell_times, memo))

        if sell_times > buy_times and sell_times > 0:
            ans = max(ans, self.dfs(prices, index + 1, profit + prices[index], buy_times, sell_times - 1, memo))
        ans = max(ans, self.dfs(prices, index + 1, profit, buy_times, sell_times, memo))
        memo[key] = ans
        return ans

"""
timeout
"""

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """

    def maxProfit(self, prices):
        if len(prices) < 2:
            return 0

        n = len(prices)
        k = 2
        dp = [[0] * n for _ in range(k + 1)]

        for i in range(1, k + 1):
            for j in range(1, n):
                for m in range(j):
                    dp[i][j] = max(dp[i][j], dp[i][j - 1], dp[i - 1][m] + prices[j] - prices[m])
        return dp[k][n - 1]


#!/usr/bin/env python
# coding: utf-8

# In[12]:

import findspark
findspark.init()

# In[13]:

import pyspark
import random
from pyspark.sql import SQLContext
from pyspark.sql.types import  (StructType,
                                StructField,
                                DateType,
                                BooleanType,
                                DoubleType,
                                IntegerType,
                                StringType,
                               TimestampType)

# In[14]:

emp_schema = StructType([StructField("ID", StringType(), True),
                            StructField("Name", StringType(), True),
                            StructField("age", StringType(), True ),
                            StructField("City", StringType(), True)
                            ])
schema_lst = ["Id","Name","age","city"]

# In[31]:

spark = pyspark.SparkContext.getOrCreate()
words = spark.textFile("/home/cgt_jpr_lin_nikhil/nikhil/spark/data/emp.txt")
print(type(words))
#print(words.getNumPartitions())
rdd_new = words.collect
print(type(rdd_new))

# In[16]:

# function to convert RDD to dataframe
def RDD_to_df(sqlContext,df,schema):

  # converting RDD to df using createDataframe()
  # in which we are passing RDD and schema of df
  df1 = sqlContext.createDataFrame(df,schema)
  return df1

# In[26]:

sqlContext = SQLContext(spark)
converted_df = RDD_to_df(sqlContext,words,emp_schema)
print(converted_df.first)

# In[24]:

print(type(words))
converted_df.show()

# In[ ]:

# In[ ]:

# In[ ]:


from sqlalchemy import create_engine, desc
from sqlalchemy.orm import sessionmaker
from draft_kings_db import models, db_data

class DraftKingsHistory(object):
    def __init__(
        self,
        db_url='sqlite:///:memory:',
        verbose=False
    ):
        self.most_recent_data = None
        if verbose:
            self.verbose = True
        else:
            self.verbose = False

        engine = create_engine(db_url)
        models.Base.metadata.create_all(engine)
        Session = sessionmaker(bind=engine)
        self.session = Session()

    def __del__(self):
        self.session.close()

    def initialize_nba(self, to_date=None, from_date=None):
        self.most_recent_data = db_data.retrieve_data(
            self.session,
            self.verbose,
            to_date=to_date,
            from_date=from_date,
        )
        print('Retrieved data from {} to {}'.format(
            from_date or db_data.DB_START,
            to_date or self.most_recent_data,
        ))

    def lookup_nba_performances(self, name=None, date=None, limit=5):
        query = self.session.query(models.NBAPerformance)

        if name:
            query = query.filter(models.NBAPerformance.name == name)
        if date:
            query = query.filter(models.NBAPerformance.date == date)

        query = query.order_by(desc(models.NBAPerformance.date))
        return query.limit(limit) if limit else query.all()


from typing import Dict, List, Optional
import torch
from fairseq.distributed import fsdp_wrap
from fairseq.models import (
    register_model,
    register_model_architecture,
)
from fairseq.models.transformer.transformer_config import (
    TransformerConfig,
    DEFAULT_MAX_SOURCE_POSITIONS,
    DEFAULT_MAX_TARGET_POSITIONS,
    DEFAULT_MIN_PARAMS_TO_WRAP,
)
import math
import torch.nn as nn
from fairseq.models.transformer import (
    TransformerModel,
    TransformerEncoder,
    TransformerDecoder
)
from fairseq.modules import (
    FairseqDropout,
    LayerDropModuleList,
    LayerNorm,
    PositionalEmbedding,
    SinusoidalPositionalEmbedding,
)
from fairseq.modules import transformer_layer, TransformerEncoderLayer
from fairseq.modules.checkpoint_activations import checkpoint_wrapper
from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_
from torch import Tensor

# rewrite name for backward compatibility in `make_generation_fast_`
def module_name_fordropout(module_name: str) -> str:
    if module_name == 'TransformerEncoderBase':
        return 'TransformerEncoder'
    else:
        return module_name

class T5TransformerEncoderLayer(TransformerEncoderLayer):
    """Encoder layer block.

    In the original paper each operation (multi-head attention or FFN) is
    postprocessed with: `dropout -> add residual -> layernorm`. In the
    tensor2tensor code they suggest that learning is more robust when
    preprocessing each layer with layernorm and postprocessing with:
    `dropout -> add residual`. We default to the approach in the paper, but the
    tensor2tensor approach can be enabled by setting
    *cfg.encoder.normalize_before* to ``True``.

    Args:
        args (argparse.Namespace): parsed command-line arguments
    """

    def __init__(self, args, dictionary, embed_tokens):
        super().__init__(args, dictionary, embed_tokens)

    def forward(
            self,
            x,
            encoder_padding_mask: Optional[Tensor],
            attn_mask: Optional[Tensor] = None,
    ):
        """
        Args:
            x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
            encoder_padding_mask (ByteTensor): binary ByteTensor of shape
                `(batch, seq_len)` where padding elements are indicated by ``1``.
            attn_mask (ByteTensor): binary tensor of shape `(tgt_len, src_len)`,
                where `tgt_len` is the length of output and `src_len` is the
                length of input, though here both are equal to `seq_len`.
                `attn_mask[tgt_i, src_j] = 1` means that when calculating the
                embedding for `tgt_i`, we exclude (mask out) `src_j`. This is
                useful for strided self-attention.

        Returns:
            encoded output of shape `(seq_len, batch, embed_dim)`
        """
        # anything in original attn_mask = 1, becomes -1e8
        # anything in original attn_mask = 0, becomes 0
        # Note that we cannot use -inf here, because at some edge cases,
        # the attention weight (before softmax) for some padded element in query
        # will become -inf, which results in NaN in model parameters
        if attn_mask is not None:
            attn_mask = attn_mask.masked_fill(
                attn_mask.to(torch.bool),
                -1e8 if x.dtype == torch.float32 else -1e4
            )

        residual = x
        if self.normalize_before:
            x = self.self_attn_layer_norm(x)
        x, _ = self.self_attn(
            query=x,
            key=x,
            value=x,
            key_padding_mask=encoder_padding_mask,
            need_weights=False,
            attn_mask=attn_mask,
        )
        x = self.dropout_module(x)
        x = self.residual_connection(x, residual)
        if not self.normalize_before:
            x = self.self_attn_layer_norm(x)

        residual = x
        if self.normalize_before:
            x = self.final_layer_norm(x)
        x = self.activation_fn(self.fc1(x))
        x = self.activation_dropout_module(x)
        x = self.fc2(x)
        x = self.dropout_module(x)
        x = self.residual_connection(x, residual)
        if not self.normalize_before:
            x = self.final_layer_norm(x)
        return x

class T5TransformerEncoder(TransformerEncoder):
    """
    Transformer encoder consisting of *cfg.encoder.layers* layers. Each layer
    is a :class:`TransformerEncoderLayer`.

    Args:
        args (argparse.Namespace): parsed command-line arguments
        dictionary (~fairseq.data.Dictionary): encoding dictionary
        embed_tokens (torch.nn.Embedding): input embedding
    """

    def __init__(self, cfg, dictionary, embed_tokens):
        self.cfg = cfg
        super().__init__(dictionary)
        self.register_buffer("version", torch.Tensor([3]))

        self.dropout_module = FairseqDropout(
            cfg.dropout, module_name=module_name_fordropout(self.__class__.__name__)
        )
        self.encoder_layerdrop = cfg.encoder.layerdrop

        embed_dim = embed_tokens.embedding_dim
        self.padding_idx = embed_tokens.padding_idx
        self.max_source_positions = cfg.max_source_positions

        self.embed_tokens = embed_tokens

        self.embed_scale = 1.0 if cfg.no_scale_embedding else math.sqrt(embed_dim)

        self.embed_positions = (
            PositionalEmbedding(
                cfg.max_source_positions,
                embed_dim,
                self.padding_idx,
                learned=cfg.encoder.learned_pos,
            )
            if not cfg.no_token_positional_embeddings
            else None
        )
        if cfg.layernorm_embedding:
            self.layernorm_embedding = LayerNorm(embed_dim, export=cfg.export)
        else:
            self.layernorm_embedding = None

        if not cfg.adaptive_input and cfg.quant_noise.pq > 0:
            self.quant_noise = apply_quant_noise_(
                nn.Linear(embed_dim, embed_dim, bias=False),
                cfg.quant_noise.pq,
                cfg.quant_noise.pq_block_size,
            )
        else:
            self.quant_noise = None

        if self.encoder_layerdrop > 0.0:
            self.layers = LayerDropModuleList(p=self.encoder_layerdrop)
        else:
            self.layers = nn.ModuleList([])
        self.layers.extend(
            [self.build_encoder_layer(cfg) for i in range(cfg.encoder.layers)]
        )
        self.num_layers = len(self.layers)

        if cfg.encoder.normalize_before:
            self.layer_norm = LayerNorm(embed_dim, export=cfg.export)
        else:
            self.layer_norm = None

    def build_encoder_layer(self, args):
        return super().build_encoder_layer(
            TransformerConfig.from_namespace(args),
        )

    def forward_embedding(
            self, src_tokens, token_embedding: Optional[torch.Tensor] = None
    ):
        # embed tokens and positions
        if token_embedding is None:
            token_embedding = self.embed_tokens(src_tokens)
        x = embed = self.embed_scale * token_embedding
        if self.embed_positions is not None:
            x = embed + self.embed_positions(src_tokens)
        if self.layernorm_embedding is not None:
            x = self.layernorm_embedding(x)
        x = self.dropout_module(x)
        if self.quant_noise is not None:
            x = self.quant_noise(x)
        return x, embed

    # TorchScript doesn't support super() method so that the scriptable Subclass
    # can't access the base class model in Torchscript.
    # Current workaround is to add a helper function with different name and
    # call the helper function from scriptable Subclass.
    def forward_scriptable(
            self,
            src_tokens,
            src_lengths: Optional[torch.Tensor] = None,
            return_all_hiddens: bool = False,
            token_embeddings: Optional[torch.Tensor] = None,
    ):
        """
        Args:
            src_tokens (LongTensor): tokens in the source language of shape
                `(batch, src_len)`
            src_lengths (torch.LongTensor): lengths of each source sentence of
                shape `(batch)`
            return_all_hiddens (bool, optional): also return all of the
                intermediate hidden states (default: False).
            token_embeddings (torch.Tensor, optional): precomputed embeddings
                default `None` will recompute embeddings

        Returns:
            dict:
                - **encoder_out** (Tensor): the last encoder layer's output of
                  shape `(src_len, batch, embed_dim)`
                - **encoder_padding_mask** (ByteTensor): the positions of
                  padding elements of shape `(batch, src_len)`
                - **encoder_embedding** (Tensor): the (scaled) embedding lookup
                  of shape `(batch, src_len, embed_dim)`
                - **encoder_states** (List[Tensor]): all intermediate
                  hidden states of shape `(src_len, batch, embed_dim)`.
                  Only populated if *return_all_hiddens* is True.
        """
        # compute padding mask
        encoder_padding_mask = src_tokens.eq(self.padding_idx)
        has_pads = src_tokens.device.type == "xla" or encoder_padding_mask.any()

        x, encoder_embedding = self.forward_embedding(src_tokens, token_embeddings)

        self_attn_mask = self.build_self_attn_mask(src_tokens, bidirectional=True)
        # relative positions bias
        if self.relative_position is not None:
            rel_pos_bias = self.relative_position(
                batch_size=src_tokens.size(0),
                qlen=src_tokens.size(1),
                klen=src_tokens.size(1)
            )
            self_attn_mask = self_attn_mask.unsqueeze(0) + rel_pos_bias

        # account for padding while computing the representation
        if has_pads:
            x = x * (1 - encoder_padding_mask.unsqueeze(-1).type_as(x))

        # B x T x C -> T x B x C
        x = x.transpose(0, 1)

        encoder_states = []

        if return_all_hiddens:
            encoder_states.append(x)

        # encoder layers
        for layer in self.layers:
            x = layer(
                x,
                self_attn_mask=self_attn_mask,
                encoder_padding_mask=encoder_padding_mask if has_pads else None
            )
            if return_all_hiddens:
                assert encoder_states is not None
                encoder_states.append(x)

        if self.layer_norm is not None:
            x = self.layer_norm(x)

        # The Pytorch Mobile lite interpreter does not supports returning NamedTuple in
        # `forward` so we use a dictionary instead.
        # TorchScript does not support mixed values so the values are all lists.
        # The empty list is equivalent to None.
        src_lengths = src_tokens.ne(self.padding_idx).sum(dim=1, dtype=torch.int32).reshape(-1, 1).contiguous()
        return {
            "encoder_out": [x],  # T x B x C
            "encoder_padding_mask": [encoder_padding_mask],  # B x T
            "encoder_embedding": [encoder_embedding],  # B x T x C
            "encoder_states": encoder_states,  # List[T x B x C]
            "src_tokens": [],
            "src_lengths": [src_lengths],
        }

@register_model("t5_transformer")
class T5TransformerModel(TransformerModel):
    """
    This is the legacy implementation of the transformer model that
    uses argparse for configuration.
    """

    @classmethod
    def build_encoder(cls, args, src_dict, embed_tokens):
        return T5TransformerEncoder(TransformerConfig.from_namespace(args), src_dict, embed_tokens)

    @classmethod
    def build_decoder(cls, args, tgt_dict, embed_tokens):
        return super().build_decoder(
            TransformerConfig.from_namespace(args), tgt_dict, embed_tokens
        )

# architectures
@register_model_architecture("t5_transformer", "t5_transformer")
def t5_transformer_base_architecture(args):
    args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
    args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
    args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
    args.encoder_layers = getattr(args, "encoder_layers", 6)
    args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
    args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
    args.encoder_learned_pos = getattr(args, "encoder_learned_pos", True)
    args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
    args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
    args.decoder_ffn_embed_dim = getattr(
        args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
    )
    args.decoder_layers = getattr(args, "decoder_layers", 6)
    args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
    args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
    args.decoder_learned_pos = getattr(args, "decoder_learned_pos", True)
    args.attention_dropout = getattr(args, "attention_dropout", 0.0)
    args.activation_dropout = getattr(args, "activation_dropout", 0.0)
    args.activation_fn = getattr(args, "activation_fn", "relu")
    args.dropout = getattr(args, "dropout", 0.1)
    args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
    args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
    args.share_decoder_input_output_embed = getattr(
        args, "share_decoder_input_output_embed", False
    )
    args.share_all_embeddings = getattr(args, "share_all_embeddings", True)
    args.no_token_positional_embeddings = getattr(
        args, "no_token_positional_embeddings", False
    )
    args.adaptive_input = getattr(args, "adaptive_input", False)
    args.no_cross_attention = getattr(args, "no_cross_attention", False)
    args.cross_self_attention = getattr(args, "cross_self_attention", False)

    args.decoder_output_dim = getattr(
        args, "decoder_output_dim", args.decoder_embed_dim
    )
    args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)

    args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
    args.layernorm_embedding = getattr(args, "layernorm_embedding", False)
    args.tie_adaptive_weights = getattr(args, "tie_adaptive_weights", False)
    args.checkpoint_activations = getattr(args, "checkpoint_activations", False)
    args.offload_activations = getattr(args, "offload_activations", False)
    if args.offload_activations:
        args.checkpoint_activations = True
    args.encoder_layers_to_keep = getattr(args, "encoder_layers_to_keep", None)
    args.decoder_layers_to_keep = getattr(args, "decoder_layers_to_keep", None)
    args.encoder_layerdrop = getattr(args, "encoder_layerdrop", 0)
    args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0)
    args.quant_noise_pq = getattr(args, "quant_noise_pq", 0)
    args.quant_noise_pq_block_size = getattr(args, "quant_noise_pq_block_size", 8)
    args.quant_noise_scalar = getattr(args, "quant_noise_scalar", 0)

@register_model_architecture("t5_transformer", "t5_transformer_base")
def t5_transformer_base(args):
    t5_transformer_base_architecture(args)

@register_model_architecture("t5_transformer", "t5_transformer_big")
def t5_transformer_big(args):
    args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
    args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
    args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
    args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
    args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 1024)
    args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 4096)
    args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
    args.dropout = getattr(args, "dropout", 0.3)
    t5_transformer_base_architecture(args)


import myservo

servoBasePin = 5
servoLeftPin = 18
servoRightPin = 19
servoGripPin = 21
servoGripRotatePin = 22

servoBasePosition = 90
servoBaseLow = 0
servoBaseHigh = 180

servoLeftPosition = 30
servoLeftLow = 20
servoLeftHigh = 100

servoRightPosition = 100
servoRightLow = 90
servoRightHigh = 160

servoGripPosition = 95
servoGripLow = 0
servoGripHigh = 180

servoGripRotatePosition = 90
servoGripRotateLow = 0
servoGripRotateHigh = 180

class Arm:
    def __init__(self):
        self.servoBase = myservo.MyServo(
            servoBasePin, servoBaseLow, servoBaseHigh, servoBasePosition)
        self.servoLeft = myservo.MyServo(
            servoLeftPin, servoLeftLow, servoLeftHigh, servoLeftPosition)
        self.servoRight = myservo.MyServo(
            servoRightPin, servoRightLow, servoRightHigh, servoRightPosition)
        self.servoGripRotate = myservo.MyServo(
            servoGripRotatePin, servoGripRotateLow, servoGripRotateHigh, servoGripRotatePosition)
        self.servoGrip = myservo.MyServo(
            servoGripPin, servoGripLow, servoGripHigh, servoGripPosition)

    def getData(self):
        data = [self.servoBase.getPosition(), self.servoLeft.getPosition(), self.servoRight.getPosition(), self.servoGripRotate.getPosition(), self.servoGrip.getPosition()]
        return '|'.join(str(d) for d in data)

    def setData(self, data):
        print('set data1 %s' % data)
        positions = data.split('|')
        if len(positions) != 5:
            return
        self.servoBase.moveTo(int(positions[0]))
        self.servoLeft.moveTo(int(positions[1]))
        self.servoRight.moveTo(int(positions[2]))
        self.servoGripRotate.moveTo(int(positions[3]))
        print('set data2 %s' % positions)

        if positions[4] == 'open':
            self.servoGrip.moveTo(servoGripLow)
        elif positions[4] == 'close':
            self.servoGrip.moveTo(servoGripHigh)

    def setPosition(self, servo, position):
        armData = self.getData().split('|')
        armData[servo] = str(position)
        self.setData('|'.join(armData))

    def incrementPosition(self, servo, value):
        armData = self.getData().split('|')
        armData[servo] = str(int(armData[servo]) + int(value))
        self.setData('|'.join(armData))

    def clawOpen(self):
        armData = self.getData().split('|')
        armData[4] = 'open'
        self.setData('|'.join(armData))

    def clawClose(self):
        armData = self.getData().split('|')
        armData[4] = 'close'
        self.setData('|'.join(armData))


from sympy import symbols, diff, pprint, factorial, ln, exp, sin, cos, log, sqrt
import numpy as np

#(K^n/1-k) * (p1-p0)

#para escoger que funcion es mejor, evaluo la funcion en los extremos del intervalo
#y escogo la que los resultados den valores dentro del rango

# K - saco la primera derivada y la evaluo en los extremos del intervalo
#y me tiene que dar menor a uno, escogo el x mas grande

# para sacar la g() se despeja la x de una de las variables

def puntoFijo(f,g,x0,tol,nmax):
    dx0 = 0
    fx = f(x0)
    cont = 0
    err = tol+1
    err1 = tol+1
    print("\n-------------------------------------------------------")
    print("iteracion | xcentro | fxcentro |error abs")
    print(cont, "|", x0,"|",fx,"|",err1)
    while((fx != 0) and (err1 > tol) and (cont < nmax) ):
        dx0 = g(x0)
        fx = f(dx0)
        err1 = abs(dx0-x0) #dx0 = xn x0= xn-1
        err = abs((dx0-x0)/dx0) #err relativo
        x0 = dx0
        cont = cont+1
        print(cont, "|", x0,"|",fx,"|",err1)
    if(fx == 0):
        print("\n error:",err1)
        print(x0, "no es raiz")
    elif(err1 < tol):
        print("\n error:",err1)
        print(x0, "aproxima a la raiz")
    else:
        print("\n el metodo fracaso")

def f(x): #fucnion originaĺ
    #print("exp(-x) - sin(4*x)")
    return -exp(7-4*x) - x**2 +10

def g(x): #despejo la x (del termino que quiera)
    return sqrt(10-exp(7-4*x)) #xn+1

#         f,g,x0,tol,nmax
puntoFijo(f,g,3.15,1e-7,100)
#derivada()


from django import forms
from django.utils.translation import gettext_lazy as _

from leerming.users.models import User

def recipient_exists_in_db(email: str):
    try:
        User.objects.get(email=email)
    except User.DoesNotExist as e:
        raise forms.ValidationError(
            _(f"Utilisateur avec le {email} introuvable")
        ) from e

class GiftForm(forms.Form):
    recipient_email = forms.EmailField(label="", validators=[recipient_exists_in_db])


# imports and setup
import numpy as np
import os.path
import scipy.io
from loadmat import loadmat

import matplotlib as mpl
default_dpi = mpl.rcParamsDefault['figure.dpi']
mpl.rcParams['figure.dpi'] = default_dpi*2
import matplotlib.pyplot as plt

# load gulfport campus image
img_fname = 'muufl_gulfport_campus_w_lidar_1.mat'
spectra_fname = 'tgt_img_spectra.mat'

dataset = loadmat(img_fname)['hsi']

hsi = dataset['Data'][:,:,4:-4] # trim noisy bands
valid_mask = dataset['valid_mask'].astype(bool)
n_r,n_c,n_b = hsi.shape
wvl = dataset['info']['wavelength'][4:-4]
rgb = dataset['RGB']

# extract some endmembers using Pixel Purity Index algorithm
#  using PySptools from https://pysptools.sourceforge.io
import pysptools
import pysptools.eea

hsi_array = np.reshape(hsi,(n_r*n_c,n_b))
valid_array = np.reshape(valid_mask,(n_r*n_c,))
M = hsi_array[valid_array,:]
q = 3
numSkewers = 500
E,inds = pysptools.eea.eea.PPI(M, q, numSkewers)

# plot the endmembers we found
plt.plot(wvl,E.T)
plt.xlabel('wavelength (nm)')
plt.ylabel('reflectance')
plt.legend([str(i+1) for i in range(q)])
plt.title("PPI Endmembers")

# find abundances given the endmembers
import pysptools.abundance_maps

maps = pysptools.abundance_maps.amaps.FCLS(M, E)
#maps = np.zeros((M.shape[0],E.shape[1]))

# re-ravel abundance maps
map_imgs = []
for i in range(q):
    map_lin = np.zeros((n_r*n_c,))
    map_lin[valid_array] = maps[:,i]
    map_imgs.append(np.reshape(map_lin,(n_r,n_c)))

# display abundance maps
for i in range(q):
    plt.figure()
    plt.imshow(map_imgs[i],vmin=0,vmax=1)
    plt.colorbar()
    plt.title('FCLS Abundance Map %d'%(i+1,))

	# run SPICE to find number of endmembers, endmembers, and abundances simultaneously
from SPICE import *

params = SPICEParameters()
inputData = M.T.astype(float)
# to save time, downsample inputData
dsData = inputData[:,::20]
dsData.shape

# run SPICE
[eM,dsP] = SPICE(dsData,params)

# unmix endmembers again with full data matrix (because we downsampled for sake of time)
P = unmix2(inputData,eM)
n_em = eM.shape[1]

#plot endmembers
plt.plot(wvl,eM)
plt.xlabel('wavelength (nm)')
plt.ylabel('reflectance')
plt.legend([str(i+1) for i in range(5)])
plt.title('SPICE Endmembers')

# re-reval abundance maps
P_imgs = []
for i in range(n_em):
    map_lin = np.zeros((n_r*n_c,))
    map_lin[valid_array] = P[:,i]
    P_imgs.append(np.reshape(map_lin,(n_r,n_c)))

	# display abundance maps
for i in range(n_em):
    plt.figure()
    plt.imshow(P_imgs[i],vmin=0,vmax=1)
    plt.colorbar()
    plt.title('SPICE Abundance Map %d'%(i+1,))


import numpy as np
import matplotlib.pyplot as plt

def main():

    # our system definition - vanilla second order system
    A = np.matrix([[1, 0.1], [0, 1]])
    B = np.matrix([[0], [0.1]])

    # penalty for position, velocity
    Q = np.matrix([[5, 0], [0, 1]])

    # penalty for controls
    R = np.matrix([[0.1]])

    # run for 100 timesteps
    T = 100

    ##################################################
    # pre-compute my K, V matrices

    Kmats = [ np.matrix([[0, 0]]) ]

    V = Q
    Vmats = [ V ]

    for i in range(T-1):

        K = np.linalg.inv( B.T * V * B + R ) * B.T * V * A

        ABthing = A - B*K
        V = Q + K.T * R * K + ABthing.T * V * ABthing

        Kmats.insert(0, K)
        Vmats.insert(0, V)

    plt.plot([Ki[0,0] for Ki in Kmats], label='pos gain (kp)')
    plt.plot([Ki[0,1] for Ki in Kmats], label='vel gain (kd)')

    plt.legend()
    plt.xlabel('Timestep')
    plt.ylabel('Gain value')
    plt.title('Optimized gains from LQR')
    plt.show()

    '''
    ##################################################
    # simulate the system

    # for each timestep
    for i in range(T):

        # append the current state
        qdata.append(q)

        # compute a control
        u = -K_fixed*q

        # append the next state
        q = A*q + B*u

    # plot the trajectory
    qdata = np.array(qdata)
    plt.plot(qdata[:,0])
    plt.xlabel('Timestep')
    plt.ylabel('Position (m)')
    plt.title('Non-optimal control')
    plt.show()
    '''

if __name__ == '__main__':
    main()


import docker

base_url='unix://var/run/docker.sock'

def find_container(needle):
    cli = docker.APIClient(base_url='unix://var/run/docker.sock',version='auto')
    for container in cli.containers():
        for name in container['Names']:
            if needle in name:
                return container
    return False


### To Run : "python3 a b c" , where 'a' is the method, 'b' is the function number and 'c' represent de dimension to the function

import matplotlib.pyplot as plt
import sys

names = ["elDE", "elDE_SHADE","elDE_EDM", "elDE_EDM_v2"]

method = names[int(sys.argv[1])-1]
func_num = sys.argv[2]
dimension = int(sys.argv[3])

name = "Resumen_"+method+"_"+func_num+"_"+str(dimension)+".txt"

X = [ i for i in range(4000) ]
Y = [ [] for i in range(dimension) ]

for line in open(name, 'r'):
    values = line.split()
    k = 2
    for j in range(dimension):
        Y[j].append(float(values[k]))
        k = k + 2

plt.title("SD")
plt.ylabel(r'$SD( \overrightarrow{x_i})$')
plt.xlabel('iterations')

k = 1
for y in Y:
    name = "x" + str(k)
    y = y[0:int(sys.argv[4])]
    X = X[0:int(sys.argv[4])]
    plt.plot(X, y , label = name )
    k = k + 1

nameOutout = "Graphs/"+method+"_"+func_num+"_"+str(dimension)+".png"
plt.legend( loc = 'upper right')
plt.savefig(nameOutout)