#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#By Neo-Jack 2021

class color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

class varT:
    info = color.YELLOW + "[INFO]:" + color.END
    home = "/home/"
    escrSP = "/Escritorio/"
    libSP = "Instalando Libreria faltante."
    listo = " Listo..."
    insDepSP = " Instalando dependencia..."
    espera = " Esperando..."
    traSP = " Traducido..."
    ingrSP = " Tienes que ingresar un Directorio y nombre de Archivo valido."
    expFileSP = " Archivo exportado en "
    metaSP = " Meta Data Eliminada de: "
    escrEN = "/Desktop/"
    done = " Done..."
    instDepEN = " Installing dependency ... "
    wait = " Waiting..."
    traEN = " Translated..."
    ingrEN = " You have to enter a valid Directory and Filename. "
    expFileEN = " Exported file in  "
    metaEN = " Meta Data Removed from:  "

def clear():
	if name == 'nt':
		_ = system('cls')
	else:
		_ = system('clear')

from os import system, name
import sys, os, time
from PIL import Image
import pickle

try:
    from PyQt5 import QtCore, QtGui, QtWidgets
except:
    clear()
    print(color.PURPLE + color.UNDERLINE + varT.libSP + color.END)
    system('pip3 install pyqt5')

usr = os.getlogin()

def db():
    global baseInsExif
    global baseidioma
    baseInsExif = "SI"; baseidioma = "SP";
    try:
        baseInsExif, baseidioma = pickle.load(open("conf.neo","rb"))
        if baseInsExif == "SI":
            if baseidioma == "SP":
                try:
                    clear()
                    print(varT.info + varT.insDepSP)
                    system('sudo apt-get update')
                    system('sudo apt-get install libimage-exiftool-perl') # Ubuntu, Debian, Mint, Kali
                    clear()
                    print(varT.info + varT.listo)
                except:
                    clear()
                    print(varT.info + varT.insDepSP)
                    system('sudo dnf update')
                    system('sudo dnf install perl-Image-ExifTool.noarch') # Fedora, CentOS, RedHat
                    clear()
                    print(varT.info + varT.listo)
            elif baseidioma == "EN":
                try:
                    clear()
                    print(varT.info + varT.instDepEN)
                    system('sudo apt-get update')
                    system('sudo apt-get install libimage-exiftool-perl') # Ubuntu, Debian, Mint, Kali
                    clear()
                    print(varT.info + varT.done)
                except:
                    clear()
                    print(varT.info + varT.insDepEN)
                    system('sudo dnf update')
                    system('sudo dnf install perl-Image-ExifTool.noarch') # Fedora, CentOS, RedHat
                    clear()
                    print(varT.info + varT.done)
        elif baseInsExif == "NO":
            if baseidioma == "SP":
                clear()
                print(varT.info + varT.espera)
            elif baseidioma == "EN":
                clear()
                print(varT.info + varT.wait)
        baseInsExif = "NO"
        pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
    except:
        pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
        baseInsExif, baseidioma = pickle.load(open("conf.neo","rb"))
        if baseInsExif == "SI":
            if baseidioma == "SP":
                try:
                    clear()
                    print(varT.info + varT.insDepSP)
                    system('sudo apt-get update')
                    system('sudo apt-get install libimage-exiftool-perl') # Ubuntu, Debian, Mint, Kali
                    clear()
                    print(varT.info + varT.listo)
                except:
                    clear()
                    print(varT.info + varT.insDepSP)
                    system('sudo dnf update')
                    system('sudo dnf install perl-Image-ExifTool.noarch') # Fedora, CentOS, RedHat
                    clear()
                    print(varT.info + varT.listo)
            elif baseidioma == "EN":
                try:
                    clear()
                    print(varT.info + varT.instDepEN)
                    system('sudo apt-get update')
                    system('sudo apt-get install libimage-exiftool-perl') # Ubuntu, Debian, Mint, Kali
                    clear()
                    print(varT.info + varT.done)
                except:
                    clear()
                    print(varT.info + varT.insDepEN)
                    system('sudo dnf update')
                    system('sudo dnf install perl-Image-ExifTool.noarch') # Fedora, CentOS, RedHat
                    clear()
                    print(varT.info + varT.done)
        elif baseInsExif == "NO":
            if baseidioma == "SP":
                clear()
                print(varT.info + varT.espera)
            elif baseidioma == "EN":
                clear()
                print(varT.info + varT.wait)
        baseInsExif = "NO"
        pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))

db()

class Ui_MainWindow(object):

    def rutaE(self):
        global folder
        baseInsExif, baseidioma = pickle.load(open("conf.neo","rb"))
        if self.sp_radio.isChecked():
            escritorio = varT.escrSP
            baseidioma = "SP"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
        elif self.en_radio.isChecked():
            escritorio = varT.escrEN
            baseidioma = "EN"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
        folder = varT.home + usr + escritorio
        self.ruta_e.setText(folder)

    def confInstala(self):
        baseInsExif, baseidioma = pickle.load(open("conf.neo","rb"))
        if self.si_radio.isChecked():
            baseInsExif = "SI"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
        elif self.no_radio.isChecked():
            baseInsExif = "NO"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))

    def instalar(self):
        if self.si_radio.isChecked():
            baseInsExif = "SI"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
            try:
                if self.sp_radio.isChecked():
                    clear()
                    print(varT.info + varT.insDepSP)
                elif self.en_radio.isChecked():
                    clear()
                    print(varT.info + varT.instDepEN)
                system('sudo apt-get update')
                system('sudo apt-get install libimage-exiftool-perl') # Ubuntu, Debian, Mint, Kali
                clear()
                if self.sp_radio.isChecked():
                    clear()
                    print(varT.info + varT.listo)
                elif self.en_radio.isChecked():
                    clear()
                    print(varT.info + varT.done)
            except:
                if self.sp_radio.isChecked():
                    clear()
                    print(varT.info + varT.insDepSP)
                elif self.en_radio.isChecked():
                    clear()
                    print(varT.info + varT.varT.instDepEN)
                system('sudo dnf update')
                system('sudo dnf install perl-Image-ExifTool.noarch') #Fedora, CentOS, RedHat
                clear()
                if self.sp_radio.isChecked():
                    clear()
                    print(varT.info + varT.listo)
                elif self.en_radio.isChecked():
                    clear()
                    print(varT.info + varT.done)
            baseInsExif = "NO"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
            self.no_radio.setChecked(True)

        elif self.no_radio.isChecked():
            baseInsExif = "NO"
            pickle.dump([baseInsExif, baseidioma], open("conf.neo","wb"))
            clear()
            if self.sp_radio.isChecked():
                clear()
                print(varT.info + varT.espera)
            elif self.en_radio.isChecked():
                clear()
                print(varT.info + varT.wait)
            pass

    def idioma(self):
        global escritorio
        if self.sp_radio.isChecked():
            self.retranslate_SP(MainWindow)
            escritorio = varT.escrSP
            self.rutaE()
            clear()
            print(varT.info + varT.traSP + varT.listo)
        elif self.en_radio.isChecked():
            self.retranslate_EN(MainWindow)
            escritorio = varT.escrEN
            self.rutaE()
            clear()
            print(varT.info + varT.traEN + varT.done)

    def cambia_img(self):
        folder = str(self.ruta_e.text())
        imagen = str(self.img_name_e.text())
        rutaCompleta = folder + imagen
        if imagen != ".png, .jpg, .gif, .pdf, .zip, .doc, etc.":
            try:
                icon1 = QtGui.QIcon()
                icon1.addPixmap(QtGui.QPixmap(rutaCompleta), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                self.abrir_img_b.setIcon(icon1)
            except:
                print("err")
                icon1 = QtGui.QIcon()
                icon1.addPixmap(QtGui.QPixmap("img/no2.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                self.abrir_img_b.setIcon(icon1)
        else:
            if self.sp_radio.isChecked():
                clear()
                print(varT.info + varT.ingrSP)
            elif self.en_radio.isChecked():
                clear()
                print(varT.info + varT.ingrEN)

    def abreimg(self):
        folder = str(self.ruta_e.text())
        imagen = str(self.img_name_e.text())
        rutaCompleta = folder + imagen
        try:
            icon1 = QtGui.QIcon()
            icon1.addPixmap(QtGui.QPixmap(rutaCompleta), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.abrir_img_b.setIcon(icon1)
            ruta = Image.open(folder + imagen, 'r')
            ruta.show()
        except:
            icon1 = QtGui.QIcon()
            icon1.addPixmap(QtGui.QPixmap("img/no2.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.abrir_img_b.setIcon(icon1)

    def ver_exif(self):
        folder = str(self.ruta_e.text())
        imagen = str(self.img_name_e.text())
        rutaCompleta = folder + imagen
        clear()
        os.system('exiftool ' + rutaCompleta)

    def exportar(self):
        folder = str(self.ruta_e.text())
        imagen = str(self.img_name_e.text())
        rutaCompleta = folder + imagen
        clear()
        if self.sp_radio.isChecked():
            print(varT.info + varT.expFileSP + rutaCompleta + ".html")
            os.system('exiftool -h ' + rutaCompleta + ' > ' + rutaCompleta + '.html')
        elif self.en_radio.isChecked():
            print(varT.info + varT.expFileEN + rutaCompleta + ".html")
            os.system('exiftool -h ' + rutaCompleta + ' > ' + rutaCompleta + '.html')

    def limpiaExif(self):
        folder = str(self.ruta_e.text())
        imagen = str(self.img_name_e.text())
        rutaCompleta = folder + imagen
        clear()
        if self.sp_radio.isChecked():
            print(varT.info + varT.metaSP + imagen)
            os.system('exiftool -all= ' + rutaCompleta)
        elif self.en_radio.isChecked():
            print(varT.info + varT.metaEN + imagen)
            os.system('exiftool -all= ' + rutaCompleta)

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(394, 494)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("img/anon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(20, 30, 351, 58))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.grid1 = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.grid1.setContentsMargins(0, 0, 0, 0)
        self.grid1.setObjectName("grid1")
        self.ruta_txt = QtWidgets.QLabel(self.gridLayoutWidget)
        self.ruta_txt.setObjectName("ruta_txt")
        self.grid1.addWidget(self.ruta_txt, 0, 0, 1, 1)
        self.ruta_e = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.ruta_e.setTabletTracking(False)
        self.ruta_e.setObjectName("ruta_e")
        self.grid1.addWidget(self.ruta_e, 0, 1, 1, 1)
        self.img_nombre_txt = QtWidgets.QLabel(self.gridLayoutWidget)
        self.img_nombre_txt.setObjectName("img_nombre_txt")
        self.grid1.addWidget(self.img_nombre_txt, 1, 0, 1, 1)
        self.img_name_e = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.img_name_e.setObjectName("img_name_e")
        self.grid1.addWidget(self.img_name_e, 1, 1, 1, 1)
        self.titulo_txt = QtWidgets.QLabel(self.centralwidget)
        self.titulo_txt.setGeometry(QtCore.QRect(140, 10, 121, 17))
        self.titulo_txt.setObjectName("titulo_txt")
        self.abrir_img_b = QtWidgets.QToolButton(self.centralwidget)
        self.abrir_img_b.setGeometry(QtCore.QRect(20, 140, 351, 291))
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("img/no.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.abrir_img_b.setIcon(icon1)
        self.abrir_img_b.setIconSize(QtCore.QSize(250, 400))
        self.abrir_img_b.setAutoRepeat(False)
        self.abrir_img_b.setAutoExclusive(False)
        self.abrir_img_b.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
        self.abrir_img_b.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.abrir_img_b.setAutoRaise(False)
        self.abrir_img_b.setObjectName("abrir_img_b")
        self.abrir_img_b.clicked.connect(self.abreimg)
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(20, 90, 351, 51))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontal1 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontal1.setContentsMargins(0, 0, 0, 0)
        self.horizontal1.setObjectName("horizontal1")
        self.ver_img_b = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.ver_img_b.setObjectName("ver_img_b")
        self.ver_img_b.clicked.connect(self.cambia_img)
        self.horizontal1.addWidget(self.ver_img_b)
        self.ver_exif_b = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.ver_exif_b.setObjectName("ver_exif_b")
        self.ver_exif_b.clicked.connect(self.ver_exif)
        self.horizontal1.addWidget(self.ver_exif_b)
        self.exportar_b = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.exportar_b.setObjectName("exportar_b")
        self.exportar_b.clicked.connect(self.exportar)
        self.horizontal1.addWidget(self.exportar_b)
        self.borrar_exif_b = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.borrar_exif_b.setObjectName("borrar_exif_b")
        self.borrar_exif_b.clicked.connect(self.limpiaExif)
        self.horizontal1.addWidget(self.borrar_exif_b)
        self.horizontalLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(139, 430, 231, 31))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
        self.horizontal2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontal2.setContentsMargins(0, 0, 0, 0)
        self.horizontal2.setObjectName("horizontal2")
        self.instala_txt = QtWidgets.QLabel(self.horizontalLayoutWidget_2)
        self.instala_txt.setObjectName("instala_txt")
        self.horizontal2.addWidget(self.instala_txt)
        self.si_radio = QtWidgets.QRadioButton(self.horizontalLayoutWidget_2)
        if baseInsExif == "SI":
            self.si_radio.setChecked(True)
        self.si_radio.setObjectName("si_radio")
        self.si_radio.clicked.connect(self.instalar)
        self.horizontal2.addWidget(self.si_radio)
        self.no_radio = QtWidgets.QRadioButton(self.horizontalLayoutWidget_2)
        if baseInsExif == "NO":
            self.no_radio.setChecked(True)
        self.no_radio.setObjectName("no_radio")
        self.no_radio.clicked.connect(self.instalar)
        self.horizontal2.addWidget(self.no_radio)
        self.horizontalLayoutWidget_3 = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(20, 460, 191, 31))
        self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")
        self.horizontal3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
        self.horizontal3.setContentsMargins(0, 0, 0, 0)
        self.horizontal3.setObjectName("horizontal3")
        self.idioma_txt = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.idioma_txt.setObjectName("idioma_txt")
        self.horizontal3.addWidget(self.idioma_txt)
        self.sp_radio = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
        if baseidioma == "SP":
            self.sp_radio.setChecked(True)
        self.sp_radio.setObjectName("sp_radio")
        self.sp_radio.clicked.connect(self.idioma)
        self.horizontal3.addWidget(self.sp_radio)
        self.en_radio = QtWidgets.QRadioButton(self.horizontalLayoutWidget_3)
        if baseidioma == "EN":
            self.en_radio.setChecked(True)
        self.en_radio.setObjectName("en_radio")
        self.en_radio.clicked.connect(self.idioma)
        self.horizontal3.addWidget(self.en_radio)
        self.neo_txt = QtWidgets.QLabel(self.centralwidget)
        self.neo_txt.setGeometry(QtCore.QRect(230, 470, 111, 17))
        self.neo_txt.setStyleSheet("font: 9pt \"Ubuntu\";")
        self.neo_txt.setObjectName("neo_txt")
        self.rutaE()
        self.confInstala()
        MainWindow.setCentralWidget(self.centralwidget)
        if baseidioma == "SP":
            self.retranslate_SP(MainWindow)
        else:
            self.retranslate_EN(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslate_SP(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MetaData-Tool v.1"))
        self.ruta_txt.setText(_translate("MainWindow", "Ruta:"))
        self.img_nombre_txt.setText(_translate("MainWindow", "IMG Nombre:"))
        self.img_name_e.setText(_translate("MainWindow", ".png, .jpg, .gif, .pdf, .zip, .doc, etc."))
        self.titulo_txt.setText(_translate("MainWindow", "MetaData-Tool"))
        self.abrir_img_b.setText(_translate("MainWindow", "Abrir IMG"))
        self.ver_img_b.setText(_translate("MainWindow", "Ver IMG"))
        self.ver_exif_b.setText(_translate("MainWindow", "Ver Exif"))
        self.exportar_b.setText(_translate("MainWindow", "Exp. Exif"))
        self.borrar_exif_b.setText(_translate("MainWindow", "Limpiar Exif"))
        self.neo_txt.setText(_translate("MainWindow", "by Neo-Jack 2021"))
        self.instala_txt.setText(_translate("MainWindow", "Instalar ExifTool:"))
        self.si_radio.setText(_translate("MainWindow", "Si"))
        self.no_radio.setText(_translate("MainWindow", "No"))
        self.idioma_txt.setText(_translate("MainWindow", "Lenguaje:"))
        self.sp_radio.setText(_translate("MainWindow", "SP"))
        self.en_radio.setText(_translate("MainWindow", "EN"))

    def retranslate_EN(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MetaData-Tool v.1"))
        self.ruta_txt.setText(_translate("MainWindow", "File Path :"))
        self.img_nombre_txt.setText(_translate("MainWindow", "IMG Name:"))
        self.img_name_e.setText(_translate("MainWindow", ".png, .jpg, .gif, .pdf, .zip, .doc, etc."))
        self.titulo_txt.setText(_translate("MainWindow", "MetaData-Tool"))
        self.abrir_img_b.setText(_translate("MainWindow", "Open IMG"))
        self.ver_img_b.setText(_translate("MainWindow", "View IMG"))
        self.ver_exif_b.setText(_translate("MainWindow", "View Exif"))
        self.exportar_b.setText(_translate("MainWindow", "Exp. Exif"))
        self.borrar_exif_b.setText(_translate("MainWindow", "Wipe out Exif"))
        self.neo_txt.setText(_translate("MainWindow", "by Neo-Jack 2021"))
        self.instala_txt.setText(_translate("MainWindow", "Install ExifTool:"))
        self.si_radio.setText(_translate("MainWindow", "Yes"))
        self.no_radio.setText(_translate("MainWindow", "No"))
        self.idioma_txt.setText(_translate("MainWindow", "Language :"))
        self.sp_radio.setText(_translate("MainWindow", "SP"))
        self.en_radio.setText(_translate("MainWindow", "EN"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


from .forms import UserProfileForm
from .models import UserProfile

def retrieve(request):
    """ gets the UserProfile instance for a user,
    creates one if it does not exist """
    try:
        # Get the profile of the currently authenticated user
        profile = UserProfile()
    except UserProfile.DoesNotExist:
        # If the User has not been created, create and save the
        # profile instance for the user
        profile = UserProfile(user=request.user)
        profile.save()
    return profile

def set(request):
    """ updates the information stored in the user's profile """
    profile = retrieve(request)
    profile_form = UserProfileForm(request.POST, instance=profile)
    profile_form.save()


# coding: utf-8
from itertools import count, takewhile, tee

def prime_gen():
    """ Gerador de números primos """
    yield 2
    primes = []
    for value in count(start=3, step=2):
        iter_primes = takewhile(lambda x: x * x <= value, primes)
        if all(value % p != 0 for p in iter_primes):
            primes.append(value)
            yield value

primes, primes_copy = tee(prime_gen(), 2)

for idx, p in enumerate(primes, 1):
    print(u"{:>5}º primo: {}".format(idx, p))
    if idx == 200:
        break

for idx, p in enumerate(primes_copy, 1):
    print(u"{:>5}º primo ao quadrado: {}".format(idx, p ** 2))
    if idx == 200:
        break


#!/usr/bin/python

import sys

stopwords = ['the', 'is', 'and', 'in', 'of', 'a', 'to','in','its','i']

# get all the lines from stdin

for line in sys.stdin:

	# removing all leading and trailing whitespaces

	line = line.strip()

	# split the line into words
	words = line.split()

	filered_words = [text for text in words if text not in stopwords]

	#output tuples in tab-delimited format
	for word in filered_words:
		print("%s\t%s" % (word, "1"))

# Read stopwords from the external file

# stopwords_file = "sw.txt"
# with open(stopwords_file, "r") as f:
#     stopwords = set([line.strip() for line in f])


import pandas as pd

# read each label sas file
# separate the variable and its label
# add its year
# convert to a dataframe
# write to a csv file

# Parses through label text file and separates the variable and its label.
# Returns a list of lists.
def parse_text(year):
    data = []
    with open(f"data/chis/{year}/ADULT_LABEL.SAS") as f:
        lines = f.readlines()
        # iterate through each line except the first and last line
        for line in lines[1:-1]:
            # remove whitespace and then split on "="
            l = line.strip().split("=")
            l[0] = l[0].strip()

            # Does not include columns that start with RAKED
            if l[0].startswith("RAKED") == False:
                # remove whitespace and then the double quotes
                l[1] = l[1].strip().strip('\"')
                data.append(l)

    return data

# Creates the list of lists to a dataframe and adds the year
# Returns the dataframe
def convert_to_dataframe(data, year):
    df = pd.DataFrame(data, columns=["Variable", "Label"])
    df["Year"] = year

    return df

if __name__ == "__main__":
    # Creates new empty dataframe with 3 columns: Variable, Label, and Year
    df = pd.DataFrame(columns=["Variable", "Label", "Year"])

    # List of years that we want
    years = [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]

    # Iterate through the years and parse each years ADULT_LABEL.SAS
    # Convert to another dataframe and then concatenate both into one
    for year in years:
        data = parse_text(year)
        df2 = convert_to_dataframe(data, year)
        df = pd.concat([df, df2])

    # Write to csv file
    df.to_csv("data/variables12to20.csv", index=False)


from xml.dom.minidom import Element
'''

def get_hash(key):
    sum = 0
    for c in key:
        sum += ord(c)
    print(sum % 100)

get_hash('march 6')

# ==================================  ==============================

class HashTable:
    def __init__(self):
        self.MAX = 100
        self.arr = [None]*self.MAX

    def get_hash(self, key):
        sum = 0
        for c in key:
            sum += ord(c)
        return sum % self.MAX

    def __setitem__(self, key, val):
        h = self.get_hash(key)
        self.arr[h] = val

    def __getitem__(self, key):
        h = self.get_hash(key)
        return self.arr[h]

    def __delitem__(self, key):
        h = self.get_hash(key)
        self.arr[h] = None

h = HashTable()
h['march 6'] = 302
h['march 7'] = 303
h['march 8'] = 304
h['march 9'] = 305

print(h['march 7'])

del h['march 7']
print(h['march 7'])
'''
# ==========================================================================================

class HashTable:
    def __init__(self):
        self.MAX = 10
        self.arr = [[] for i in range(self.MAX)]

    def get_hash(self, key):
        sum = 0
        for c in key:
            sum += ord(c)
        return sum % self.MAX

    def __setitem__(self, key, val):
        h = self.get_hash(key)
        found  = False
        for idx, element in enumerate(self.arr[h]):
            if len(element) == 2 and element[0] == key:
                self.arr[h][idx] = (key, val)
                found = True

        if not found:
            self.arr[h] .append((key, val))

    def __getitem__(self, key):
        h = self.get_hash(key)
        for kv in self.arr[h]:
            if kv[0] == key:
                return kv[1]

    def __delitem__(self, key):
        h = self.get_hash(key)
        for index, kv in enumerate(self.arr[h]):
            if kv[0] == key:
                print(f"Delete elementindex in : {index}")
                del self.arr[h][index]

t = HashTable()
print(t.get_hash('march 6'))
print(t.get_hash('march 17'))

t['march 6'] = 123
t['march 9'] = 163
t['march 45'] = 523
t['march 17'] = 923

print(t['march 6'])
print(t['march 17'])
print(t.arr)

t['march 17'] = 999
print(t.arr)

del t['march 17']

print(t.arr)


import warnings
import numpy as np
import pandas as pd
import random
import gzip
import io
import datetime

warnings.filterwarnings('ignore')

from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from datetime import date, datetime
from xgboost import XGBClassifier

# 1. Preprocessing

# 1.1 Randomized line extraction

line_count = 40428968
n = 100000
skip = sorted(random.sample(range(1,line_count + 1), line_count - n))
df = pd.read_csv("train.gz", skiprows=skip, index_col=0)

# 1.3 Preprocessing

df["weekday"] = df["hour"].apply(lambda x: datetime.strptime(str(x), '%y%m%d%H').weekday())
df["hour"] = df["hour"].apply(lambda x: int(str(x)[-2:]))
df["area"] = df["C15"] * df["C16"]

# Separation X / y

y = df[['click']]
X = df[['C1', 'hour', 'banner_pos', 'site_category', 'app_category', 'device_type', 'device_conn_type', 'C14', 'C15', 'C16', 'C17', 'C18',
           'C19', 'C20','C21', 'area', 'weekday', 'User_freq']]

# C20 column preparation

X['C20'] = X['C20'].replace(-1, np.nan)
X['C20'] = X['C20'].replace(np.nan, X['C20'].median())

# One hot encoding with get_dummies

columns_to_encode = ['device_type', 'device_conn_type', 'site_category', 'app_category', 'banner_pos', 'C18']
df_full_columns = pd.read_csv("train.gz", usecols=columns_to_encode)
for col in columns_to_encode:
    X[col] = X[col].astype('category', categories = df_full_columns[col].unique().tolist())
X = pd.get_dummies(X, columns=columns_to_encode, prefix = columns_to_encode)

# 1.4. Folding

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, shuffle=False)

# 2. LogisticRegression (a gridsearch was implemented to determine the hyperparameters)

lr = LogisticRegression(penalty='l1',
                        solver='liblinear',
                        C=0.1,
                        verbose=2)
lr.fit(X,y)

# 3. XGBoost (a gridsearch was implemented to determine the hyperparameters)

xgb = XGBClassifier(verbose=2,
                    n_jobs=-1,
                    max_depth=4,
                    learning_rate=0.2,
                    colsample_bytree=0.9,
                    n_estimators=600,
                    reg_alpha=1,
                    reg_lambda=1,
                    objective='binary:logistic',
                    booster='gbtree')
xgb.fit(X,y)

# ## 4. RandomForests

rf = RandomForestClassifier(n_jobs=-1)
rf.fit(X,y)

# ## 5. Blending

lr_preds = lr.predict_proba(X_test)
xgb_preds = xgb.predict_proba(X_test)
rf_preds = rf.predict_proba(X_test)

preds_table = pd.DataFrame({"LR":lr_preds[:,1], "XGBoost":xgb_preds[:,1], "RandomForests":rf_preds[:,1]}, index=X_test.index)

# We use a LogisiticRegression to determine how to blend the models predictions

lr_blending = LogisticRegression(penalty='l1',
                                 solver='liblinear',
                                 C=0.5,
                                 verbose=2)
lr_blending.fit(preds_table, y_test)

# 5. Predictions on test.gz

test = pd.read_csv("test.gz")

test["weekday"] = test["hour"].apply(lambda x: datetime.strptime(str(x), '%y%m%d%H').weekday())
test["hour"] = test["hour"].apply(lambda x: int(str(x)[-2:]))
test["area"] = test["C15"] * test["C16"]

test['User_freq'] = test['device_id'] + test['device_ip'] + test['device_model'] #on crée une feature user
values = test['User_freq'].value_counts() # on remplace la valeur de user par sa fréquence d'apparition
test['User_freq'] = test['User_freq'].apply(lambda row: values[row])

test = test[['C1', 'hour', 'banner_pos', 'site_category', 'app_category', 'device_type', 'device_conn_type', 'C14','C15', 'C16', 'C17', 'C18',
           'C19', 'C20','C21', 'area', 'weekday', 'User_freq']]

test['C20'] = test['C20'].replace(-1, np.nan)
test['C20'] = test['C20'].replace(np.nan, X['C20'].median())

for col in columns_to_encode:
    test[col] = test[col].astype('category',categories = df_full_columns[col].unique().tolist())

test = pd.get_dummies(test, columns=columns_to_encode, prefix = columns_to_encode)

lr_preds_test = lr.predict_proba(test)
xgb_preds_test = xgb.predict_proba(test)
rf_preds_test = rf.predict_proba(test)

preds_table_final = pd.DataFrame({"LR":lr_preds_test[:,1], "XGBoost":xgb_preds_test[:,1], "RandomForests":rf_preds_test[:,1]}, index=test.index)

# 5.2. Export for the evaluation on kaggle.com

preds = lr_blending.predict_proba(preds_table_final)[:,1]
submission_file = pd.read_csv("sampleSubmission.gz")
submission_file['click'] = preds
submission_file.to_csv(path_or_buf= './submission_files/preds_' + datetime.now().strftime("%d%m%Y-%H%M%S") + '.gz', index = False, sep = ',', compression='gzip')


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

import platform
import subprocess
import re

# Function to run a shell command and return the output
def run_command(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    output, _ = process.communicate()
    return output.decode('utf-8').strip()

# Function to get disk usage
def get_disk_usage():
    df_output = run_command('df -kh')
    df_lines = df_output.split('\n')[1:]

    disk_usage = []
    for line in df_lines:
        parts = line.split()
        if len(parts) >= 5:
            filesystem = parts[0]
            size = parts[1]
            used = parts[2]
            available = parts[3]
            percentage_used = parts[4]

            # Handle the case when the percentage used is not in a recognized format
            try:
                percentage = float(percentage_used.strip('%'))
            except ValueError:
                percentage = 0.0

            disk_usage.append({
                'Filesystem': filesystem,
                'Size': size,
                'Used': used,
                'Available': available
            })
    return disk_usage

# Function to get network cards and their IP addresses
def get_network_cards():
    network_cards_output = run_command('networksetup -listallhardwareports')
    network_cards_lines = network_cards_output.split('\n')
    network_cards = []
    for line in network_cards_lines:
        if line.startswith('Hardware Port:'):
            network_card = line.split(':')[1].strip()
            network_cards.append(network_card)

    ip_addresses_output = run_command('ifconfig | grep "inet " | awk \'{print $2}\'')
    ip_addresses = ip_addresses_output.split('\n')

    # Print the number of network cards
    print('Total Network Cards:', len(network_cards))

    return network_cards, ip_addresses

# Get system information
def get_system_info():
    system_info = {}

    # Get host name
    host_name = run_command('scutil --get ComputerName')
    system_info['Host Name'] = host_name

    # Get operating system information
    os_name = platform.system()
    os_version = platform.mac_ver()[0]
    os_build = run_command('sw_vers -buildVersion')
    os_manufacturer = platform.system()
    system_info['OS Name'] = os_name
    system_info['OS Version'] = os_version
    system_info['OS Build'] = os_build
    system_info['OS Manufacturer'] = os_manufacturer

    # Get processor information
    processor_name = run_command('sysctl -n machdep.cpu.brand_string')
    system_info['Processor'] = processor_name

    # Get memory information
    memory_info = run_command('sysctl -n hw.memsize')
    system_info['Memory'] = memory_info

    # Get disk usage information
    disk_usage = get_disk_usage()
    system_info['Disk Usage'] = disk_usage

    # Get network cards and their IP addresses
    network_cards, ip_addresses = get_network_cards()
    system_info['Network Cards'] = network_cards
    system_info['IP Addresses'] = ip_addresses

    return system_info

# Get and print system information
system_info = get_system_info()
for key, value in system_info.items():
    print(f'{key}:')
    if key == 'Disk Usage':
        for disk in value:
            print(f'Filesystem: {disk["Filesystem"]}')
            print(f'Used: {disk["Used"]}')
            print(f'Available: {disk["Available"]}')
            print('-' * 50)
    elif key == 'Network Cards':
        print(f'Total Network Cards: {len(value)}')
        for card in value:
            print(card)
    else:
        print(value)
    print('--' * 50)
#end


import streamlit
import functions
# import PySimpleGUI

# PySimpleGUI.theme("BLACK")

streamlit.set_page_config(layout='wide')

tasks = functions.get_testdata()

def add_task():
    task = streamlit.session_state["new_task"] + "\n"
    tasks.append(task)
    functions.wrt_testdata(tasks)

streamlit.title("TASKS TO DO")
streamlit.subheader("This is developed for Bhavya Sri :)")

streamlit.text_input(label="", placeholder="Add new task or "
                                           "to delete check the box beside task",
                     on_change=add_task, key="new_task")

for index, task in enumerate(tasks):
    checkbox = streamlit.checkbox(task, key=task)
    if checkbox:
        tasks.pop(index)
        functions.wrt_testdata(tasks)
        del streamlit.session_state[task]
        streamlit.experimental_rerun()


__all__ = ["fit_thin_plate_spline_displacement_field"]

import numpy as np

from ..core import ants_image as iio
from .. import core
from .. import utils

def fit_thin_plate_spline_displacement_field(displacement_origins=None,
                                             displacements=None,
                                             origin=None,
                                             spacing=None,
                                             size=None,
                                             direction=None):

    """
    Fit a thin-plate spline object to a a set of points with associated displacements.
    This is basically a wrapper for the ITK filter

    https://itk.org/Doxygen/html/itkThinPlateSplineKernelTransform_8h.html

    ANTsR function: `fitThinPlateSplineToDisplacementField`

    Arguments
    ---------

    displacement_origins : 2-D numpy array
        Matrix (number_of_points x dimension) defining the origins of the input
        displacement points.  Default = None.

    displacements : 2-D numpy array
        Matrix (number_of_points x dimension) defining the displacements of the input
        displacement points.  Default = None.

    origin : n-D tuple
        Defines the physical origin of the B-spline object.

    spacing : n-D tuple
        Defines the physical spacing of the B-spline object.

    size : n-D tuple
       Defines the size (length) of the spline object.  Note that the length of the
       spline object in dimension d is defined as spacing[d] * size[d]-1.

    direction : 2-D numpy array
       Booleans defining whether or not the corresponding parametric dimension is
       closed (e.g., closed loop).  Default = None.

    Returns
    -------
    Returns an ANTsImage.

    Example
    -------
    >>> # Perform 2-D fitting
    >>>
    >>> import ants, numpy
    >>>
    >>> points = numpy.array([[-50, -50]])
    >>> deltas = numpy.array([[10, 10]])
    >>>
    >>> tps_field = ants.fit_thin_plate_spline_displacement_field(
    >>>   displacement_origins=points, displacements=deltas,
    >>>   origin=[0.0, 0.0], spacing=[1.0, 1.0], size=[100, 100],
    >>>   direction=numpy.array([[-1, 0], [0, -1]]))
    """

    dimensionality = displacement_origins.shape[1]
    if displacements.shape[1] != dimensionality:
        raise ValueError("Dimensionality between origins and displacements does not match.")

    if displacement_origins is None or displacement_origins is None:
        raise ValueError("Missing input.  Input point set (origins + displacements) needs to be specified." )

    if origin is not None and len(origin) != dimensionality:
        raise ValueError("Origin is not of length dimensionality.")

    if spacing is not None and len(spacing) != dimensionality:
        raise ValueError("Spacing is not of length dimensionality.")

    if size is not None and len(size) != dimensionality:
        raise ValueError("Size is not of length dimensionality.")

    if direction is not None and (direction.shape[0] != dimensionality and direction.shape[1] != dimensionality):
        raise ValueError("Direction is not of shape dimensionality x dimensionality.")

    # It would seem that pybind11 doesn't really play nicely when the
    # arguments are 'None'

    if origin is None:
        origin = np.empty(0)

    if spacing is None:
        spacing = np.empty(0)

    if size is None:
        size = np.empty(0)

    if direction is None:
        direction = np.empty((0, 0))

    tps_field = None
    libfn = utils.get_lib_fn("fitThinPlateSplineDisplacementFieldToScatteredDataD%i" % (dimensionality))
    tps_field = libfn(displacement_origins, displacements, origin, spacing, size, direction)

    tps_displacement_field = iio.ANTsImage(pixeltype='float',
        dimension=dimensionality, components=dimensionality,
        pointer=tps_field).clone('float')
    return tps_displacement_field


#!/usr/bin/env python

"""Plot the residual, data, and total loss functions by model.

Plot the residual, data, and total loss functions by model.
The plots are saved as a single PNG file.
"""

# Import standard modules.
import argparse
import importlib
import os
import sys

# # Import 3rd-party modules.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# Import project-specific modules.
from pinn import standard_plots

# Program constants and defaults

# Program description.
DESCRIPTION = (
    "Plot the residual, data, and total loss functions by model."
)

# Default maximum and minimum values to show in loss function plots.
DEFAULT_LMIN = 1.0e-9
DEFAULT_LMAX = 1.0

def create_command_line_parser():
    """Create the command-line argument parser.

    Create the command-line argument parser.

    Parameters
    ----------
    None

    Returns
    -------
    parser : argparse.ArgumentParser
        Command-line argument parser for this script.
    """
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument(
        "--debug", "-d", action="store_true",
        help="Print debugging output (default: %(default)s)."
    )
    parser.add_argument(
        "--Lmax", type=float, default=DEFAULT_LMAX,
        help="Maximum L value to plot (default: %(default)s)."
    )
    parser.add_argument(
        "--Lmin", type=float, default=DEFAULT_LMIN,
        help="Minimum L value to plot (default: %(default)s)."
    )
    parser.add_argument(
        "--verbose", "-v", action="store_true",
        help="Print verbose output (default: %(default)s)."
    )
    parser.add_argument(
        "problem_name", type=str,
        help="Name of problem."
    )
    parser.add_argument(
        "results_path", type=str, nargs="?", default=os.getcwd(),
        help="Directory containing model results (default: %(default)s)."
    )
    return parser

def main():
    """Main program logic.

    The program starts here.

    Parameters
    ----------
    None

    Returns
    -------
    None
    """

    # Set up the command-line parser.
    parser = create_command_line_parser()

    # Parse the command-line arguments.
    args = parser.parse_args()
    debug = args.debug
    Lmax = args.Lmax
    Lmin = args.Lmin
    verbose = args.verbose
    problem_name = args.problem_name
    results_path = args.results_path
    if debug:
        print(f"args = {args}")
        print(f"debug = {debug}")
        print(f"Lmax = {Lmax}")
        print(f"Lmin = {Lmin}")
        print(f"verbose = {verbose}")
        print(f"problem_name = {problem_name}")
        print(f"results_path = {results_path}")

    # Import the problem definition.
    sys.path.append(results_path)
    p = importlib.import_module(problem_name)

    # Load the overall, residual, and data losses for the each model.
    losses_model = np.loadtxt(os.path.join(results_path, "losses_model.dat"))
    losses_model_res = np.loadtxt(os.path.join(results_path, "losses_model_res.dat"))
    losses_model_data = np.loadtxt(os.path.join(results_path, "losses_model_data.dat"))

    # Plot the loss functions and save as a PNG.
    mpl.use("Agg")
    standard_plots.plot_model_loss_functions(
        losses_model_res, losses_model_data, losses_model,
        p.dependent_variable_labels
    )
    plt.savefig("L_models.png")

if __name__ == "__main__":
    """Begin main program."""
    main()


from .setup import *

import cr.wavelets._src.wavelet as wt_int

@pytest.mark.parametrize("name", ['haar', 'db2', 'sym4', 'coif2', 'bior1.1', 'rbio1.1', 'dmey'])
def test_build_wavelet(name):
    wavelet = wt.build_wavelet(name)
    assert wavelet
    s = str(wavelet)
    bank = wavelet.filter_bank
    assert len(bank) == 4
    inverse_bank = wavelet.inverse_filter_bank
    assert len(inverse_bank) == 4
    assert_array_equal(bank[0], inverse_bank[2][::-1])
    assert_array_equal(bank[1], inverse_bank[3][::-1])
    assert_array_equal(bank[2], inverse_bank[0][::-1])
    assert_array_equal(bank[3], inverse_bank[1][::-1])
    wavefun = wavelet.wavefun(2)
    assert wavefun is not None
    integration = wt.integrate_wavelet(wavelet, 2)
    assert integration is not None

@pytest.mark.parametrize("name,order", [ (wt.FAMILY.CMOR, 4),
    (wt.FAMILY.DB, 100), (wt.FAMILY.SYM, 400), (wt.FAMILY.COIF, 500),
    (wt.FAMILY.BIOR, 120), (wt.FAMILY.RBIO, 340), ])
def test_build_wavelet_fail(name, order):
    wavelet = wt.build_discrete_wavelet(name, order)
    assert wavelet is None

def test_fake():
    wavelet = wt.DiscreteWavelet()
    with assert_raises(NotImplementedError):
        wavelet.wavefun()

def test_qmf():
    h = jnp.ones(4)
    g = wt_int.qmf(h)
    hh = wt_int.qmf(g)
    assert_array_equal(h, -hh)

def test_orthogonal_filter_bank():
    h = jnp.ones(4)
    bank = wt_int.orthogonal_filter_bank(h)
    dec_lo, dec_hi, rec_lo, rec_hi = bank
    assert_array_equal(rec_hi, wt_int.qmf(rec_lo))

def test_filter_bank_():
    h = jnp.ones(4)
    bank = wt_int.filter_bank_(h)
    dec_lo, dec_hi, rec_lo, rec_hi = bank
    assert_array_equal(rec_hi, wt_int.qmf(rec_lo))

def test_mirror():
    h = jnp.ones(4)
    h_m = wt_int.mirror(h)
    h_mm = wt_int.mirror(h_m)
    assert_array_equal(h, h_mm)

def test_negate_evens():
    h = jnp.ones(4)
    h_m = wt_int.negate_evens(h)
    h_mm = wt_int.negate_evens(h_m)
    assert_array_equal(h, h_mm)

def test_negate_odds():
    h = jnp.ones(4)
    h_m = wt_int.negate_odds(h)
    h_mm = wt_int.negate_odds(h_m)
    assert_array_equal(h, h_mm)

@pytest.mark.parametrize("n,m", [ (1, 1), (2, 2), (2, 4),
    (3, 1), (3,9), (4, 4), (5, 5), (6, 8)])
def test_bior_index(n, m):
    idx, max =  wt_int.bior_index(n, m)
    assert idx >= 0
    assert max > 0

def test_bior_index_invalid():
    idx, max =  wt_int.bior_index(7, 0)
    assert idx is None
    assert max is None

@pytest.mark.parametrize("name", ['mexh', 'cmor1.5-2.0'])
def test_build_continuous_wavelet(name):
    wavelet = wt.build_wavelet(name)
    assert wavelet
    s = str(wavelet)
    wavefun = wavelet.wavefun(level=2)
    assert wavefun is not None
    assert wavelet.domain > 0
    cf = wt.central_frequency(wavelet)
    scales = jnp.array([1., 2.])
    frequencies = wt.scale2frequency(wavelet, scales)
    integrated = wt.integrate_wavelet(wavelet, precision=2)

def test_to_wavelet():
    wavelet = wt.to_wavelet('haar')
    wavelet2 = wt.to_wavelet(wavelet)
    assert wavelet2 is wavelet
    with assert_raises(ValueError):
        wt.to_wavelet(None)

@pytest.mark.parametrize("name,family,order,valid", [
    ('gaus', wt.FAMILY.GAUS, 2, True),
    ('gaus', wt.FAMILY.GAUS, 3, True),
    ('gaus', wt.FAMILY.GAUS, 10, False),
    ('morl', wt.FAMILY.MORL, 0, True),
    ('cgau', wt.FAMILY.CGAU, 2, True),
    ('cgau', wt.FAMILY.CGAU, 3, True),
    ('cgau', wt.FAMILY.CGAU, 10, False),
    ('shan', wt.FAMILY.SHAN, 0, True),
    ('fbsp40.20', wt.FAMILY.FBSP, 0, True),
    ])
def test_unsupported_continuous_wavelets(name, family, order, valid):
    wavelet = wt.build_continuous_wavelet(name, family, order)
    if valid:
        assert wavelet is not None
    else:
        assert wavelet is None


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df=pd.read_csv('data.txt', sep=" ", header=None , names=["a","b","c","d","e"])
x=df["b"].tolist()
print(x)
df['a'] = df['a'].map(lambda x: x.lstrip('+-').rstrip('\tReading:'))
y=df["a"].tolist()
print(y)

n=5
def divide_chunks(x, n):
    # looping till length l
    for i in range(0, len(x), n):
        yield x[i:i + n]

    # How many elements each

a=[]
b = list(divide_chunks(x, n))
print("The list is")
print(b)

for elements in b:
    val=(sum(elements)/5)
    a.append(val)

print("Final Values")
print(a)

fl=len(a)
time_array=[]
for i in range(fl):
    time_array.append(i)

plt.rcParams['figure.figsize'] = (10, 5)
plt.xlabel('Time (s)')
plt.ylabel('Thrust (N)')
plt.plot(time_array,a)
plt.show()

area=np.trapz(a, dx=5)
print("Area:")
print(area)
print("The Impulse is "+str(area)+" Ns")
mass_fuel=float(input("Enter the amount of Fuel Taken in Kg "))
specific_impulse=float(area/mass_fuel)
print(specific_impulse)
print("The Specific Impulse is "+str(specific_impulse)+" m/s")


que = list(input().strip())
t = int(input().strip())
for i in range(t):
    met = [e for e in input().strip().split()]
    if met[0] == "in":
        que.insert(int(met[2]),met[1])
        print("".join(que))
    if met[0] == "out":
        que.pop(int(met[1]))
        print("".join(que))
    if met[0] == "swap":
        i1 = int(met[1])
        i2 = int(met[2])
        que[i1],que[i2] = que[i2],que[i1]
        print("".join(que))


#!/usr/bin/python
#
# Nikhil Handigol <nikhilh@stanford.edu>

'''Logging utility for the simulator

-- Nikhil Handigol'''

import logging
from logging import Logger
import types

LEVELS = { 'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL }

LOGLEVELDEFAULT = logging.WARNING

#default: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOGMSGFORMAT = '%(message)s'

class StreamHandlerNoNewline( logging.StreamHandler ):
    """StreamHandler that doesn't print newlines by default.
       Since StreamHandler automatically adds newlines, define a mod to more
       easily support interactive mode when we want it, or errors-only logging
       for running unit tests."""

    def emit( self, record ):
        """Emit a record.
           If a formatter is specified, it is used to format the record.
           The record is then written to the stream with a trailing newline
           [ N.B. this may be removed depending on feedback ]. If exception
           information is present, it is formatted using
           traceback.printException and appended to the stream."""
        try:
            msg = self.format( record )
            fs = '%s'  # was '%s\n'
            if not hasattr( types, 'UnicodeType' ):  # if no unicode support...
                self.stream.write( fs % msg )
            else:
                try:
                    self.stream.write( fs % msg )
                except UnicodeError:
                    self.stream.write( fs % msg.encode( 'UTF-8' ) )
            self.flush()
        except ( KeyboardInterrupt, SystemExit ):
            raise
        except:
            self.handleError( record )

class Singleton( type ):
    """Singleton pattern from Wikipedia
       See http://en.wikipedia.org/wiki/SingletonPattern#Python

       Intended to be used as a __metaclass_ param, as shown for the class
       below.

       Changed cls first args to mcs to satisfy pylint."""

    def __init__( mcs, name, bases, dict_ ):
        super( Singleton, mcs ).__init__( name, bases, dict_ )
        mcs.instance = None

    def __call__( mcs, *args, **kw ):
        if mcs.instance is None:
            mcs.instance = super( Singleton, mcs ).__call__( *args, **kw )
            return mcs.instance

class SimLogger(Logger, object):
    """SDN-Ctrl-Sim specific logger
       Enable each .py file to with one import:
       from log import [lg, info, error]

       ...get a default logger that doesn't require one newline per logging
       call.

       Use singleton pattern to ensure only one logger is ever created."""

    __metaclass__ = Singleton

    def __init__( self ):

        Logger.__init__( self, "sdnctrlsim" )

        # create console handler
        ch = StreamHandlerNoNewline()
        # create formatter
        formatter = logging.Formatter( LOGMSGFORMAT )
        # add formatter to ch
        ch.setFormatter( formatter )
        # add ch to lg
        self.addHandler( ch )
        self.setLogLevel()

    def setLogLevel( self, levelname=None ):
        """Setup loglevel.
           Convenience function to support lowercase names.
           levelName: level name from LEVELS"""
        level = LOGLEVELDEFAULT
        if levelname != None:
            if levelname not in LEVELS:
                raise Exception( 'unknown levelname seen in setLogLevel' )
            else:
                level = LEVELS.get( levelname, level )

        self.setLevel( level )
        self.handlers[ 0 ].setLevel( level )

lg = SimLogger()
info, warn, error, debug = (
    lg.info, lg.warn, lg.error, lg.debug)
setLogLevel = lg.setLogLevel


def reverse(s):
	"""
	>>> reverse('happy')
	'yppah'
	>>> reverse('Python')
	'nohtyP'
	>>> reverse("")
	''
	>>> reverse("P")
	'P'
	"""
	i = 1
	result = ""
	while i < len(s) + 1:
		result += s[-i]
		i += 1

	return result

def mirror(s):
	"""
	>>> mirror("good")
	'gooddoog'
	>>> mirror("yes")
	'yessey'
	>>> mirror('Python')
	'PythonnohtyP'
	>>> mirror("")
	''
	>>> mirror("a")
	'aa'
	"""
	return s + reverse(s)

def remove_letter(letter, strng):
	"""
	>>> remove_letter('a','apple')
	'pple'
	>>> remove_letter('a','banana')
	'bnn'
	>>> remove_letter('z','banana')
	'banana'
	>>> remove_letter('i','Mississippi')
	'Msssspp'
	"""

	result = ""
	for i in strng:
		if i != letter:
			result += i

	return result

def is_palindrome(s):
	"""
	>>> is_palindrome('abba')
	True
	>>> is_palindrome('abab')
	False
	>>> is_palindrome('tenet')
	True
	>>> is_palindrome('banana')
	False
	>>> is_palindrome('straw warts')
	True
	"""
	# if s == reverse(s):
	# 	return True
	# else:
	# 	return False
	for i in range(0,int(len(s)/2)):
		if s[i] != s[-(i+1)]:
			return False

	return True

def count(sub, s):
	"""
	>>> count('is', 'Mississippi')
	2
	>>> count('an', 'banana')
	2
	>>> count('ana', 'banana')
	2
	>>> count('nana', 'banana')
	1
	>>> count('nanan', 'banana')
	0
	"""
	count = 0
	for i in range(0, len(s)):
		if len(s) - i >= len(sub) and s[i] == sub[0]:
			if  s[i:len(sub)+i] == sub:
				count += 1

	return count

def remove_all(sub, s):
	"""
	>>> remove_all('an', 'banana')
	'ba'
	>>> remove_all('cyc', 'bicycle')
	'bile'
	>>> remove_all('iss', 'Mississippi')
	'Mippi'
	>>> remove_all('eggs', 'bicycle')
	'bicycle'
	"""
	i = 0
	while i < len(s):
		if len(s) - i >= len(sub):
			if  s[i:len(sub)+i] == sub:
				s = s[:i] + s[len(sub)+i:]
				break
		i += 1
	return s

def remove_all(sub, s):
	"""
	>>> remove_all('an', 'banana')
	'ba'
	>>> remove_all('cyc', 'bicycle')
	'bile'
	>>> remove_all('iss', 'Mississippi')
	'Mippi'
	>>> remove_all('eggs', 'bicycle')
	'bicycle'
	"""
	i = 0
	while i < len(s):
		if len(s) - i >= len(sub):
			if  s[i:len(sub)+i] == sub:
				s = s[:i] + s[len(sub)+i:]
				i -= 1
		i += 1
	return s

def replace(s, old, new):
	"""
	>>> replace('Mississippi', 'i', 'I')
	'MIssIssIppI'
	>>> s = 'I love spom! Spom is my favorite food. Spom, spom, spom, yum!'
	>>> replace(s, 'om', 'am')
	'I love spam! Spam is my favorite food. Spam, spam, spam, yum!'
	>>> replace(s, 'o', 'a')
	'I lave spam! Spam is my favarite faad. Spam, spam, spam, yum!'
	"""
	i = 0
	while i < len(s):
		if len(s) - i >= len(old):
			if  s[i:len(old)+i] == old:
				s = s[:i] + new + s[len(old)+i:]
				i -= 1
		i += 1
	return s

if __name__ == '__main__':
	import doctest
	doctest.testmod()


from flask_restplus import Resource, fields
from flask_jwt_extended import decode_token
from ducttapp import repositories, models
from flask import request
from . import ns

user_model = ns.model(
    name='user_res',
    model={
        'id': fields.Integer(),
        'email': fields.String(),
        'username': fields.String(),
        'is_admin': fields.Boolean(),
        'is_active': fields.Boolean(),
        'updated_at': fields.DateTime(),
        'fullname': fields.String(),
        'phone_number': fields.String(),
        'gender': fields.Boolean(),
        'birthday': fields.DateTime(),
        'avatar': fields.String(),
        'roles': fields.List(fields.Integer())
    }
)

@ns.route('/currentUser')
class CurrentUser(Resource):
    @ns.marshal_with(user_model)
    def get(self):
        if 'access_token_cookie' not in request.cookies:
            return None
        try:
            raw_token = decode_token(request.cookies['access_token_cookie'])
            user_id = raw_token['identity']
            user = repositories.user.find_one_by_id(
                user_id=user_id
            )
            return user.to_dict() or None
        except ValueError:
            return None


import tarfile
from zipfile import ZipFile, ZIP_DEFLATED

def tar_to_zip(*tarfiles, zippath):
    zipfile = zippath.joinpath("output.zip")

    for archive in tarfiles:
        with ZipFile(zipfile, "w", compression=ZIP_DEFLATED) as zf:
            try:
                with tarfile.open(archive, "r") as tf:
                    for info in tf:
                        tf.extract(info, path="/tmp/")
                        zf.write(f"/tmp/{info.name}", arcname=info.name)
            except tarfile.ReadError as e:
                print(f"There was an error reading the file {archive}")


import requests
import os

class FlightChecker:
    def __init__(self):
        self.TEQUILA_API_KEY = os.environ.get('TEQUILA_API_KEY')
        self.SEARCH_URL = 'https://api.tequila.kiwi.com/v2/search'
        self.IATA_URL = 'https://api.tequila.kiwi.com/locations/query'

        self.header = {
            'apikey': self.TEQUILA_API_KEY,
        }

    def get_codes(self, places):
        codes = []
        for name_of_place in places:
            parameters = {
                'term': name_of_place,
            }
            iata_code = requests.get(self.IATA_URL, headers=self.header, params=parameters).json()['locations'][0][
                'code']
            codes.append(iata_code)

        return codes

    def get_names(self, codes):
        names = []
        for code in codes:
            parameters = {
                'term': code,
            }
            try:
                name = \
                    requests.get(self.IATA_URL, headers=self.header, params=parameters).json()['locations'][0]['city'][
                        'name']
            except:
                name = requests.get(self.IATA_URL, headers=self.header, params=parameters).json()['locations'][0][
                    'name']
            names.append(name)

        return names

    def check_flight(self, user):
        flights = []
        for i in range(len(user['fly_to'])):
            parameters = {
                "fly_from": user['fly_from'],
                "fly_to": user['fly_to'][i],
                "date_from": user['date_from'],
                "date_to": user["date_to"],
                "return_from": user['return_from '],
                "return_to": user["return_to"],
                "price_to": user['price_to'][i],
                'curr': 'USD',
            }
            response = requests.get(self.SEARCH_URL, headers=self.header, params=parameters).json()
            try:
                if len(response['data']) > 0:
                    flight_dict = {
                        'cityFrom': response['data'][0]['cityFrom'],
                        'cityTo': response['data'][0]['cityTo'],
                        'price': response['data'][0]['price'],
                    }
                    flights.append(flight_dict)
            except:
                flights = flights

        return flights


import pytest
from nose.plugins.skip import SkipTest
import logging
from ansible.modules.cloud.oracle import oci_sender
from ansible.module_utils.oracle import oci_utils

try:
    import oci
    from oci.util import to_dict
    from oci.email.models import Sender
    from oci.exceptions import ServiceError, ClientError
except ImportError:
    raise SkipTest("test_oci_sender.py requires `oci` module")

class FakeModule(object):
    def __init__(self, **kwargs):
        self.params = kwargs

    def fail_json(self, *args, **kwargs):
        self.exit_args = args
        self.exit_kwargs = kwargs
        raise Exception(kwargs["msg"])

    def exit_json(self, *args, **kwargs):
        self.exit_args = args
        self.exit_kwargs = kwargs

@pytest.fixture()
def email_client(mocker):
    mock_email_client = mocker.patch("oci.email.email_client.EmailClient")
    return mock_email_client.return_value

@pytest.fixture()
def create_and_wait_patch(mocker):
    return mocker.patch.object(oci_utils, "create_and_wait")

@pytest.fixture()
def delete_and_wait_patch(mocker):
    return mocker.patch.object(oci_utils, "delete_and_wait")

def setUpModule():
    logging.basicConfig(
        filename="/tmp/oci_ansible_module.log", filemode="a", level=logging.INFO
    )
    oci_sender.set_logger(logging)

def test_create_sender(email_client, create_and_wait_patch):
    module = get_module(dict(email_address="ansible@test.com"))
    sender = get_sender()
    create_and_wait_patch.return_value = {"sender": to_dict(sender), "changed": True}
    result = oci_sender.create_sender(email_client, module)
    assert result["sender"]["email_address"] is sender.email_address

def test_delete_sender(email_client, delete_and_wait_patch):
    module = get_module(dict({"sender_id": "{ocid1.sender..aa}"}))
    sender = get_sender()
    delete_and_wait_patch.return_value = dict(
        {"sender": to_dict(sender), "changed": True}
    )
    result = oci_sender.delete_sender(email_client, module)
    assert result["changed"] is True

def get_sender():
    sender = Sender()
    sender.email_address = "ansible@test.com"
    return sender

def get_response(status, header, data, request):
    return oci.Response(status, header, data, request)

def get_module(additional_properties):
    params = {"compartment_id": "ocid1.compartment.oc1"}
    params.update(additional_properties)
    module = FakeModule(**params)
    return module


from datetime import datetime, timedelta
from typing import MutableMapping, List, Union

from bson.objectid import ObjectId
from fastapi.security import OAuth2PasswordBearer
from fastapi import HTTPException, Depends, status
from jose import jwt, JWTError

from app.api.helpers.config import settings
from app.database.mongodb import db
from app.api.auth.models import Token, TokenData
from app.api.users.models import Role, UserResponse
from app.api.helpers import exceptions

JWTPayloadMapping = MutableMapping[str, Union[datetime, bool, str, List[str], List[int]]]
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_STR}/auth/login")

def fix_id(data):
    data["id"] = str(data["_id"])
    return data

def fix_product_seller_id(data):
    data["id"] = str(data["_id"])
    data["seller_id"] = str(data["seller_id"])
    return data

async def get_user_by_username_or_404(username: str):
    user = await db.vending.users.find_one({"username": username})
    return user

async def get_product_or_404(id):
    product_cursor = db.vending.products.find({"_id": ObjectId(id)})
    product = await product_cursor.to_list(length=1)
    if len(product) > 0:
        return product[0]
    else:
        raise exceptions.ProductNotFoundException()

async def get_product_by_name_or_404(name):
    product_cursor = db.vending.products.find({"product_name": name})
    product = await product_cursor.to_list(length=1)
    if len(product) > 0:
        return product[0]
    else:
        raise exceptions.ProductNotFoundException()

async def does_seller_have_products(seller_id):
    products_cursor = db.vending.products.find({"seller_id": ObjectId(seller_id)})
    products = await products_cursor.to_list(length=1)
    if len(products) > 0:
        return True
    else:
        return False

async def get_user_and_check_if_seller(id):
    user = await db.vending.users.find_one({"$and": [{"_id": ObjectId(id), "role": Role.seller}]})
    if user:
        user = fix_id(user)
        return user
    else:
        raise exceptions.SellerDoesNotExistException()

async def get_current_user(token: str = Depends(oauth2_scheme)) -> UserResponse:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token,settings.JWT_SECRET,algorithms=[settings.ALGORITHM],options={"verify_aud": False})
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except JWTError as e:
        raise credentials_exception

    user = await get_user_by_username_or_404(username=token_data.username)
    if user is None:
        raise credentials_exception
    user = fix_id(data=user)
    return user


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('C:\\Users\\박재현\\Desktop\\deep learning\\Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values

# Encodeing Categorical data
from sklearn.preprocessing import OneHotEncoder, LabelEncoder

from sklearn.compose import ColumnTransformer

label_encoder_x_1 = LabelEncoder()
X[: , 2] = label_encoder_x_1.fit_transform(X[:,2])
transformer = ColumnTransformer(
    transformers=[
        ("OneHot",        # Just a name
         OneHotEncoder(), # The transformer class
         [1]              # The column(s) to be applied on.
         )
    ],
    remainder='passthrough' # donot apply anything to the remaining columns
)
X = transformer.fit_transform(X.tolist())
X = X.astype('float64')

# To avoid Dummy variable Trap
X = X[:, 1:]

# Spitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=0)

#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

import keras
from keras.models import Sequential
from keras.layers import Dense

# Initializing the ANN
classifier = Sequential()

# Adding the input layer and the first hidden Layer
classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu', input_dim=11))

# Adding the second hidden Layer
classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))

# Adding the output layer
classifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))

# Compiling the ANN
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size=10, epochs=10)

# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)


"""
Author:
Purpose:
Date：
"""

import argparse
import pandas
import sqlite3

def getargs():
    """
    :arg
    :return   programare guemnts
    :date
    """
    argparser = argparse.ArgumentParser(description='say')
    argparser.add_argument('--name', default='world!', help='name message')
    return argparser.parse_args()

def main():
    """the entrance of this file"""
    query = 'create table t1(a integer)'
    con = sqlite3.connect(':memory:')
    con.execute(query)
    con.execute('insert into t1 values(10)')
    con.execute('insert into t1 values(20)')
    for item in con.execute('select * from t1'):
        print(item)
    pd=pandas.read_sql('select * from t1',con)
    print(pd)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

import socket
import struct

HOST1_MAC = '00:0f:c9:0c:f7:8c'
HOST1_IP = '192.168.84.64'
HOST2_MAC = '00:0f:c9:0c:ee:ed'
HOST2_MAC_BYTES = [0x00, 0x0f, 0xc9, 0x0c, 0xee, 0xed]
HOST2_IP = '192.168.84.44'
MY_MAC = '3c:a9:f4:47:eb:c8'
MY_MAC_BYTES = [0x3c, 0xa9, 0xf4, 0x47, 0xeb, 0xc8]
MY_INTERFACE = 'wlo1'
SN1 = 's1010048XXXX'
SN2 = 's1013414YYYY'

def parse_ethernet(packet):
    (dest1, dest2, source1, source2, type_code) = struct.unpack('!IHHIH', packet[:14])
    data = packet[14:]

    if type_code == 0x8100:
        type_code = struct.unpack_from('!H', packet, 16)
        data = packet[18:]

    dest = (dest1 << 16) | dest2
    source = (source1 << 32) | source2
    dest_bytes = dest.to_bytes(6, byteorder='big')
    source_bytes = source.to_bytes(6, byteorder='big')
    dest_mac = ':'.join('{:02x}'.format(b) for b in dest_bytes)
    source_mac = ':'.join('{:02x}'.format(b) for b in source_bytes)

    return data, dest_mac, source_mac, type_code

def parse_ip(packet):
    header_length = (packet[0] & 0x0f) * 4
    header = packet[:header_length]
    data = packet[header_length:]

    (total_length, protocol, source_address, dest_address) = struct.unpack('!xxHxxxxxBxxII', header[:20])

    return header_length, header, data, total_length, protocol, source_address, dest_address

def parse_udp(packet):
    header_length = 8
    header = packet[:header_length]
    data = packet[header_length:]
    (source_port, dest_port, data_length, checksum) = struct.unpack('!HHHH', header)

    return source_port, dest_port, data_length, checksum, data

def patch_packet(packet, payload, dest_mac):
    new_packet = bytearray(packet)
    payload_offset = len(packet) - len(payload)

    # set dest mac to that of HOST2
    new_packet[0] = dest_mac[0]
    new_packet[1] = dest_mac[1]
    new_packet[2] = dest_mac[2]
    new_packet[3] = dest_mac[3]
    new_packet[4] = dest_mac[4]
    new_packet[5] = dest_mac[5]

    # set source mac to our mac
    new_packet[6] = MY_MAC_BYTES[0]
    new_packet[7] = MY_MAC_BYTES[1]
    new_packet[8] = MY_MAC_BYTES[2]
    new_packet[9] = MY_MAC_BYTES[3]
    new_packet[10] = MY_MAC_BYTES[4]
    new_packet[11] = MY_MAC_BYTES[5]

    # clear udp checksum
    new_packet[40] = 0
    new_packet[41] = 0

    # insert student numbers into payload
    payload_str = payload.decode('utf-8')
    payload_str = payload_str.replace('XXXXXXXXXXXX', SN1)
    payload_str = payload_str.replace('YYYYYYYYYYYY', SN2)
    new_payload = payload_str.encode('utf-8')
    new_packet[payload_offset:] = new_payload

    return new_packet

def main():
    # bind to wireless interface
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
    s.bind((MY_INTERFACE, 0))

    while True:
        (packet, address) = s.recvfrom(65565)
        (ethernet_data, dest_mac, source_mac, type_code) = parse_ethernet(packet)

        if type_code == 0x800 and source_mac == HOST1_MAC and dest_mac == MY_MAC:
            (ip_header_length, ip_header, ip_data, total_length, protocol, source_address, dest_address) = parse_ip(ethernet_data)
            source_ip = socket.inet_ntoa(struct.pack('!I', source_address))
            dest_ip = socket.inet_ntoa(struct.pack('!I', dest_address))

            if protocol == 17 and source_ip == HOST1_IP and dest_ip == HOST2_IP:
                (source_port, dest_port, data_length, checksum, data) = parse_udp(ip_data)

                # Patch packet and then forward it to HOST2
                new_packet = patch_packet(packet, data, HOST2_MAC_BYTES)
                s.send(new_packet)

                print('[*] Forwarded packet from {} ({}) to {} ({})'.format(source_ip, source_mac, dest_ip, HOST2_MAC))

if __name__ == '__main__':
    main()


# @File  : serviceCollect.py
# @Time  : 2022/10/30 8:37
# @Author: Tr0e
# @Blog  : https://tr0e.github.io/

import os
import time

import pandas as pd
from colorama import Fore, init

init(autoreset=True)
serviceDict = {}  # 用于全局存放所有系统服务的字典（key:value=服务名：aidl文件名）
interfaceDict = {}  # 用于全局存放所有系统服务接口的字典（key:value=服务名：接口列表）
transactionDict = {}  # 用于全局存放所有系统服务接口的transaction Code字典的嵌套字典（key:value=服务名：接口与code值字典）

def getServiceList():
    """
    生成系统服务、AIDL文件的字典
    :return: null
    """
    global serviceDict
    print(Fore.BLUE + "[*]Start collecting data…")
    localTxtFile = "data/serviceList.txt"
    serviceListCmd = "adb shell service list >" + localTxtFile
    os.system(serviceListCmd)
    print("[+]successfully save service list to %s." % localTxtFile)
    lineNum = 1
    with open(localTxtFile, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            if lineNum == 1:
                lineNum = lineNum + 1
                continue
            else:
                # 提取每行格式为：”2	nfc: [android.nfc.INfcAdapter]“的服务名”nfc"和aidl文件名
                serviceName = line.strip('\n').split(":")[0].split("\t")[1]
                aidlFileName = line.strip('\n').split(":")[1].lstrip(" ")[1:-1]
                serviceDict[serviceName] = aidlFileName
    print("[+]Len of serviceDict：" + str(len(serviceDict)))
    # print("[+]Data of serviceDict：" + str(serviceDict))
    print(Fore.BLUE + "[*]successfully collect data.")

def findAidlPath(filePath, aidlFileName):
    """
    查询指定文件夹下的aidl文件的绝对路径（支持目录嵌套）
    :param filePath: 存放了反编译资源的目标文件夹
    :param aidlFileName: aidl文件名称
    :return: 目标aidl文件的路径
    """
    for filePath, dirNames, fileNames in os.walk(filePath):
        for filename in fileNames:
            if filename == aidlFileName + ".java":
                result = os.path.join(filePath, filename)
                # print(Fore.GREEN + "[+]Path is: %s" % result)
                return result

def getAidlFile(serviceName, aidlFilePath):
    """
    从AIDL文件提取出该服务所有接口的列表
    :param serviceName: 服务名称
    :param aidlFilePath: aidl文件的路径，
    :return: 服务接口列表（含接口名、返回值、参数等）
    """
    # 路径如：r"D:\tmp\serviceFuzz\result\framework.apk\sources\android\app\IActivityManager.java"
    getTransactionDict(serviceName, aidlFilePath)  # 先生成TransactionCode字典
    with open(aidlFilePath, 'r', encoding='utf-8') as f:
        allJava = f.read()
        start = allJava.find('public static class Default implements')
        end = allJava.find('public IBinder asBinder()')
        interfaceInfo = allJava[start:end].replace("\n\n", "\n").strip("\n")
        # print(interfaceInfo)
    interfaceList = interfaceInfo.split("\n")
    # print(interfaceList)
    # 直接在原列表上使用pop删除会出现各种乱七八糟的错误，故使用新的列表来存储符合要求的原列表元素
    newInterfaceList = []
    for lineData in interfaceList:
        if "throws RemoteException" in lineData and "public" in lineData:
            lineData = lineData.lstrip(" ")
            lineData = lineData.replace("public", "").lstrip(" ")
            lineData = lineData.replace(" throws RemoteException {", "")
            newInterfaceList.append(lineData)
        else:
            continue
    # print(len(newInterfaceList))
    # print(Fore.GREEN + str(newInterfaceList))
    global interfaceDict
    interfaceDict[serviceName] = newInterfaceList
    return newInterfaceList

def getTransactionDict(serviceName, aidlFilePath):
    """
    生成所有服务的接口：Code值字典的嵌套字典transactionDict（key:value=服务名：每个服务的所有接口与其对应code值字典）
    :param serviceName: 服务名称
    :param aidlFilePath: aidl文件的路径
    :return: null
    """
    with open(aidlFilePath, 'r', encoding='utf-8') as f:
        allJava = f.read()
        start = allJava.find('static final int TRANSACTION')
        end = allJava.find('public Stub() {')
        interfaceInfo = allJava[start: end].replace("\n\n", "\n").strip("\n")
    interfaceList = interfaceInfo.split("\n")
    interfaceList.pop(len(interfaceList) - 1)
    CodeDict = {}
    for lineData in interfaceList:
        lineData = lineData.lstrip(" ")
        interfaceName = lineData.split("=")[0][29:-1]
        transactionCode = lineData.split("=")[1].replace(";", "").lstrip(" ")
        CodeDict[interfaceName] = transactionCode
    global transactionDict
    transactionDict[serviceName] = CodeDict
    # print(transactionDict)

def writeDataToXlsx(xlsxPath):
    """
    将数据转换成xlsx格式的表格
    :param xlsxPath: 输出的xlsx文件路径
    :return: null
    """
    dataSource = {}
    dictCol0List = []
    dictCol1List = []
    dictCol2List = []
    dictCol3List = []
    dictCol4List = []
    dictCol5List = []
    global interfaceDict, serviceDict, transactionDict
    # 目标行数据样例：'void addPackageDependency(String str)'
    for service, interfaces in interfaceDict.items():
        if len(interfaces) > 1:
            for interface in interfaces:
                aidlName = interface.split("(")[0].split(" ")[1]
                try:
                    dictCol0List.append(service)
                    dictCol1List.append(serviceDict[service])
                    dictCol2List.append(transactionDict[service][aidlName])
                    dictCol3List.append(aidlName)
                    dictCol4List.append(interface.split("(")[0].split(" ")[0])
                    dictCol5List.append(interface.split("(")[1][0:-1])
                except IndexError as e:
                    print(e)
                    continue
    # 设置xlsx表格每列数据的源数据列表
    dataSource["ServiceName"] = dictCol0List
    dataSource["AIDLName"] = dictCol1List
    dataSource["TransactionCode"] = dictCol2List
    dataSource["InterfaceName"] = dictCol3List
    dataSource["ReturnType"] = dictCol4List
    dataSource["ParaType"] = dictCol5List
    # print(dataSource)
    print(Fore.BLUE + "[*]Start generating xlsx…")
    writer = pd.ExcelWriter(xlsxPath)
    dataFrame = pd.DataFrame(dataSource)
    dataFrame.to_excel(writer, sheet_name="sheet1")
    writer.close()  # 保存writer中的数据至excel
    print(Fore.BLUE + "[*]Successfully generated xlsx!")

def main():
    """
    开始生成系统服务统计数据表格
    :return: 生成最终的xlsx数据文档
    """
    start = time.time()
    getServiceList()
    num = 1
    successNum = 0
    for key, value in serviceDict.items():
        if value != '' and "IDevicePolicyManager" not in value:  # Native类型的Service暂不支持获取AIDL文件
            # print(value)
            path = findAidlPath(r"D:\tmp\serviceFuzz\result", value.split(".")[-1])
            if path is not None:
                print("[%d/%d]正在分析的文件: " % (num, len(serviceDict)) + path)
                getAidlFile(key, path)
                successNum = successNum + 1
        num = num + 1
    # print(transactionDict)
    print(Fore.BLUE + "[*]总共成功分析了{0}个服务的AIDL文件!".format(successNum))
    writeDataToXlsx("data/serviceList.xlsx")
    end = time.time()
    print(Fore.GREEN + "[*]Done.Totally time is " + str(end - start) + "s.Enjoy it!")

def copyRight():
    print(Fore.GREEN + "************** CopyRight ****************")
    print(Fore.GREEN + "             Welcome to use               ")
    print(Fore.GREEN + "     Author: Tr0e                         ")
    print(Fore.GREEN + "     Github: https://github.com/Tr0e      ")
    print(Fore.GREEN + "     Blog  : https://tr0e.github.io       ")
    print(Fore.GREEN + "*****************************************")

if __name__ == '__main__':
    copyRight()
    main()
    exit(0)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import re

import argparse
import tensorflow as tf

from models import utils, modeling

def parse_args():
  parser = argparse.ArgumentParser(description="Scoring with NMT")

  ## Required parameters
  parser.add_argument("--nmt_config_file", type=str, required=True)
  parser.add_argument("--source_input_file", type=str, required=True)
  parser.add_argument("--target_input_file", type=str, required=True)
  parser.add_argument("--score_output_file", type=str, required=True)
  parser.add_argument("--vocab_file", type=str, required=True)
  parser.add_argument("--init_checkpoint", type=str, required=True)

  ## Other parameters
  parser.add_argument("--max_seq_length", default=256, type=int)
  parser.add_argument("--decode_alpha", default=1.0, type=float)
  parser.add_argument("--decode_length", default=20, type=int)
  parser.add_argument("--decode_batch_size", default=32, type=int)

  ## TPU parameters
  parser.add_argument("--use_tpu", default=False, type=bool)
  parser.add_argument("--tpu_name", default=None, type=str)

  return parser.parse_args()

def get_evaluation_input(source_inputs,
                         target_inputs,
                         vocabulary,
                         max_seq_length,
                         decode_length,
                         decode_batch_size=32,
                         num_cpu_threads=2,
                         eos="<EOS>",
                         unkId=1):
  source_dataset = tf.data.Dataset.from_tensor_slices(tf.constant(source_inputs))
  target_dataset = tf.data.Dataset.from_tensor_slices(tf.constant(target_inputs))

  dataset = tf.data.Dataset.zip((source_dataset, target_dataset))

  dataset = dataset.map(
      lambda src, tgt: (
          tf.string_split([src]).values[:max_seq_length - 1],
          tf.string_split([tgt]).values[:max_seq_length - 1],
      ),
      num_parallel_calls=num_cpu_threads
  )

  dataset = dataset.map(
      lambda src, tgt: (
          tf.concat([src, [tf.constant(eos)]], axis=0),
          tf.concat([tgt, [tf.constant(eos)]], axis=0),
      ),
      num_parallel_calls=num_cpu_threads
  )

  dataset = dataset.map(
      lambda src, tgt: (
          src,
          tf.shape(src),
          tgt,
          tf.shape(tgt),
      ),
      num_parallel_calls=num_cpu_threads
  )

  dataset = dataset.padded_batch(
      batch_size=decode_batch_size,
      padded_shapes=(max_seq_length, 1, max_seq_length, 1),
      # padded_shapes=(tf.Dimension(None), 1),
      padding_values=(eos, 0, eos, 0))

  dataset = dataset.map(
      lambda src, src_len, tgt, tgt_len: {
          "source": src,
          "source_length": tf.squeeze(src_len, 1),
          "target": tgt,
          "target_length": tf.squeeze(tgt_len, 1),
      },
      num_parallel_calls=num_cpu_threads
  )

  iterator = dataset.make_one_shot_iterator()
  features = iterator.get_next()

  src_table = tf.contrib.lookup.index_table_from_tensor(
      tf.constant(vocabulary),
      default_value=unkId
  )
  features["source"] = src_table.lookup(features["source"])
  features["target"] = src_table.lookup(features["target"])

  return features

def make_vocab(vocab_file):
  vocab = []

  vocab.append("<PAD>")
  vocab.append("<EOS>")
  vocab.append("<UNK>")
  vocab.append("<BOS>")

  with tf.gfile.Open(vocab_file, "r") as fin:
    lines = fin.readlines()

  for line in lines:
    word, freq = line.strip().split()
    if int(freq) >= 5:
      vocab.append(word)

  tf.logging.info("Vocabulary size: %d" % (len(vocab)))

  return vocab

def main(args):
  args.init_checkpoint = args.init_checkpoint.split(',')
  tf.logging.set_verbosity(tf.logging.INFO)

  vocabulary = make_vocab(args.vocab_file)

  nmt_config = modeling.NmtConfig.from_json_file(args.nmt_config_file)

  tf.logging.info("Checkpoint Vocab Size: %d", nmt_config.vocab_size)
  tf.logging.info("True Vocab Size: %d", len(vocabulary))

  assert nmt_config.vocab_size == len(vocabulary)

  vocabulary[nmt_config.padId] = nmt_config.pad.encode()
  vocabulary[nmt_config.eosId] = nmt_config.eos.encode()
  vocabulary[nmt_config.unkId] = nmt_config.unk.encode()
  vocabulary[nmt_config.bosId] = nmt_config.bos.encode()

  # Build Graph
  with tf.Graph().as_default():
    # Read input file
    source_inputs = []
    with tf.gfile.Open(args.source_input_file) as fd:
      for line in fd:
        source_inputs.append(line.strip())
    target_inputs = []
    with tf.gfile.Open(args.target_input_file) as fd:
      for line in fd:
        target_inputs.append(line.strip())

    true_length = len(source_inputs)

    while len(source_inputs) % args.decode_batch_size != 0:
      source_inputs.append('<UNK>')
      target_inputs.append('<UNK>')

    # Build input queue
    with tf.device('/CPU:0'):
      features = get_evaluation_input(source_inputs=source_inputs,
                                      target_inputs=target_inputs,
                                      vocabulary=vocabulary,
                                      max_seq_length=args.max_seq_length,
                                      decode_length=args.decode_length,
                                      decode_batch_size=args.decode_batch_size,
                                      eos=nmt_config.eos.encode(),
                                      unkId=nmt_config.unkId)

    # Create placeholders
    placeholders = {
        "source": tf.placeholder(tf.int32, [args.decode_batch_size, args.max_seq_length], "source_0"),
        "source_length": tf.placeholder(tf.int32, [args.decode_batch_size], "source_length_0"),
        "target": tf.placeholder(tf.int32, [args.decode_batch_size, args.max_seq_length], "target_0"),
        "target_length": tf.placeholder(tf.int32, [args.decode_batch_size], "target_length_0"),
    }

    model = [modeling.NmtModel(config=nmt_config) for _ in range(len(args.init_checkpoint))]
    for i, m in enumerate(model):
      m._scope = m._scope + str(i)

    model_fns = [m.get_evaluation_func() for m in model]

    if args.use_tpu:
      def computation(source, source_length, target, target_length):
        placeholders = {
            "source": source,
            "source_length": source_length,
            "target": target,
            "target_length": target_length,
        }
        scores = [model_fn(placeholders) for model_fn in model_fns]
        scores = tf.add_n(scores) / float(len(scores))
        return scores

      ops = tf.compat.v1.tpu.batch_parallel(computation,
                                            [placeholders["source"],
                                             placeholders["source_length"],
                                             placeholders["target"],
                                             placeholders["target_length"]],
                                            num_shards=8)
    else:
      scores = [model_fn(placeholders) for model_fn in model_fns]
      scores = tf.add_n(scores) / float(len(scores))
      ops = scores

    tvars = tf.trainable_variables()
    name_to_variable = {}
    for var in tvars:
      name = var.name
      m = re.match("^(.*):\\d+$", name)
      if m is not None:
        name = m.group(1)
      name_to_variable[name] = var

    for i, ckpt in enumerate(args.init_checkpoint):
      init_vars = tf.train.list_variables(ckpt)
      assignment_map = {}
      for x in init_vars:
        (name, var) = (x[0], x[1])
        m = re.match("^Tra\w*mer", name)
        if m is not None:
          temp = m.group(0)
          rename = temp + str(i) + name[len(temp):]
        else:
          rename = name
        if rename in name_to_variable:
          assignment_map[name] = rename
      tf.train.init_from_checkpoint(ckpt, assignment_map)

    tf.logging.info("**** Trainable Variables ****")
    total_size = 0
    for var in tvars:
      tf.logging.info("  name = %s, shape = %s", var.name, var.shape)
      total_size += reduce(lambda x, y: x * y, var.get_shape().as_list())
    tf.logging.info("  total variable parameters: %d", total_size)

    results = []

    target = ''
    config = None
    if args.use_tpu:
      tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(args.tpu_name)
      target = tpu_cluster_resolver.get_master()
    else:
      config = tf.ConfigProto(allow_soft_placement=True)

    with tf.Session(target=target, config=config) as sess:
      if args.use_tpu:
        sess.run(tf.contrib.tpu.initialize_system())

      sess.run(tf.global_variables_initializer())
      sess.run(tf.tables_initializer())
      while True:
        try:
          feats = sess.run(features)
          feed_dict = {}
          for name in feats:
            feed_dict[placeholders[name]] = feats[name]
          results.append(sess.run(ops, feed_dict=feed_dict))
          tf.logging.log(tf.logging.INFO, "Finished batch %d" % len(results))
        except tf.errors.OutOfRangeError:
          break

      if args.use_tpu:
        sess.run(tf.contrib.tpu.shutdown_system())

    target_dir, _ = os.path.split(args.score_output_file)
    tf.gfile.MakeDirs(target_dir)

    outputs = []

    for result in results:
      for item in result[0]:
        outputs.append(item)

    with tf.gfile.Open(args.score_output_file, "w") as outfile:
      for output in outputs[:true_length]:
        outfile.write("%f\n" % output)

if __name__ == "__main__":
  main(parse_args())


import tensorflow as tf
import a3c3 as a3c
import a3c3_1 as a3c1
import a3c3_2 as a3c2
import a3c3_3 as a3c3
import numpy as np
import model
import csv

TARGET_BUFFER = [0, 0.04]
S_INFO = 4  #the number of state
S_LEN = 8 #the number of past states
A_DIM = 4
BIT_RATE = [500.0, 850.0, 1200.0, 1850.0]
RAND_RANGE = 1000
ACTOR_LR_RATE = 0.0001
CRITIC_LR_RATE = 0.001

"""
NN_MODEL = "./fixed/nn_model_ep_10800.ckpt" # model path settings
NN_MODEL1 = "./high/nn_model_ep_40400.ckpt"
NN_MODEL2 = "./low/nn_model_ep_5100.ckpt"
NN_MODEL3 = "./medium/nn_model_ep_13400.ckpt"
"""

NN_MODEL = "./fixed/nn_model_ep_10800.ckpt" # model path settings
NN_MODEL1 = "./high/nn_model_ep_40400.ckpt"
NN_MODEL2 = "./low/nn_model_ep_5100.ckpt"
NN_MODEL3 = "./medium/nn_model_ep_13400.ckpt"

GOP = 50
BW_NORM_FACTOR = 1500.0
BUFFER_NORM_FACTOR = 1.0
FPS = 25
M_IN_K = 1000.0

throughput_list_avg = []
frame_count = 0
select_flag = 0
record_flag = 0
frames_size = 0
received_time = 0
previous_time = 0
saver = tf.train.Saver()
graph = tf.get_default_graph()

class Algorithm:
     def __init__(self):
     # fill your self params
         self.buffer_size = 0
         self.bit_rate = 0
         self.last_bit_rate = 0

         self.action_vec = np.zeros(A_DIM)
         self.action_vec[self.bit_rate] = 1
         self.s_batch = [np.zeros((S_INFO, S_LEN))]
         self.a_batch = [self.action_vec]
         self.r_batch = []
         self.entropy_record = []

     # Intial
     def Initial(self):
     # Initail your session or something
         #with tf.Session() as sess:
         self.sess = tf.Session()
         self.actor = a3c.ActorNetwork(self.sess,
                                       state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
                                       learning_rate=ACTOR_LR_RATE)

         self.sess.run(tf.global_variables_initializer())
         #saver = tf.train.Saver()  # save neural net parameters

     # restore neural net parameters
         nn_model = NN_MODEL
         if nn_model is not None:  # nn_model is the path to file
             saver.restore(self.sess, nn_model)
             print("Model restored.")
             #self.critic = a3c.CriticNetwork(sess,
                                         #state_dim=[S_INFO, S_LEN],
                                         #learning_rate=CRITIC_LR_RATE)

     #Define your al
     def run(self, time, S_time_interval, S_send_data_size, S_chunk_len, S_rebuf, S_buffer_size, S_play_time_len,S_end_delay, S_decision_flag, S_buffer_flag,S_cdn_flag,S_skip_time, end_of_video, cdn_newest_id,download_id,cdn_has_frame,IntialVars):

         # If you choose the marchine learning
         if len(self.s_batch) == 0:
             state = [np.zeros((S_INFO, S_LEN))]
         else:
             state = np.array(self.s_batch[-1], copy=True)

             # dequeue history record
         state = np.roll(state, -1, axis=1)
            # this should be S_INFO number of terms
         T_all = float(np.sum(S_time_interval[-51:-1]))
         if T_all > 0:
             num_of_frame = float(GOP / T_all)
         else:
             num_of_frame = 0
         # print 'number of frames:', num_of_frame
         if np.sum(S_time_interval[-51:-1]) > 0:
             throughput = float(np.sum(S_send_data_size[-51:-1])) / float(np.sum(S_time_interval[-51:-1]))
         else:
             throughput = 0
         state[0, -1] = BIT_RATE[self.bit_rate] / float(np.max(BIT_RATE))  # last quality present
         state[1, -1] = num_of_frame / FPS
         state[2, -1] = throughput / M_IN_K / BW_NORM_FACTOR  # kilo byte / ms #history
         state[3, -1] = np.sum(S_rebuf[-51:-1]) / BUFFER_NORM_FACTOR

         #network_condition = 0
         global frame_count, record_flag, select_flag, frames_size, previous_time
         if abs(time - int(round(time / 0.04)) * 0.04) > 1e-10:
             frame_count += 1

         #select_flag = time / 20
         if time > 2940.5 or time == 0:
             record_flag = 0
             select_flag = 0
             previous_time = 0

         print("time:", time)

         if int(time / 0.5) > record_flag:
             record_flag = time / 0.5
             print("record_flag:", record_flag)
             frames_size = float(np.sum(S_send_data_size[-frame_count:]))
             print("frames_size:", frames_size)
             received_time = float(np.sum(S_time_interval[-frame_count:]))
             print("received_time:", received_time)
             throughput_tmp = float(frames_size) / float(received_time) / 1000000
             throughput_list_avg.append(throughput_tmp)
             previous_time = time
             frame_count = 0

         """
         while 0 in S_send_data_size:
             print("S_send_data_size", S_send_data_size)
             S_send_data_size.remove(0)
         print("S_send_data_size", S_send_data_size)
         while 0 in S_time_interval:
             print("S_time_interval", S_time_interval)
             S_time_interval.remove(0)
         print("S_time_interval", S_time_interval)
         """

         #if len(S_send_data_size) >= 602 and len(S_send_data_size[102:]) % 500 == 0:
         #if frame_count % 500 == 0 and S_time_interval[-501] > 0
         if int(time / 20) > select_flag:
             select_flag = time / 20
             #frame_count = 0
             throughput_list = np.true_divide((np.array(S_send_data_size[-501:-1])).astype(float),
                                              (np.array(S_time_interval[-501:-1])).astype(float))
             throughput_list = [x / y for x in throughput_list for y in [1000000]]
             #print("S_send_data_size:", S_send_data_size[-501:-1])
             #print("S_time_interval:", S_time_interval[-501:-1])
             #print("throughput_list:", throughput_list)
             for i in range(40):
                 if i == 0:
                     start = i * 12 + 1
                     end = start + 12
                 elif i > 0 and i % 2 != 0:
                     start = end + 0
                     end = start + 12
                 elif i > 0 and i % 2 == 0:
                     start = end + 1
                     end = start + 12

                 #throughput_list_avg.append(float(np.sum(throughput_list[start:end])) / 12.0)
             #print("throughput_list_avg:", throughput_list_avg[-40:])
             network_condition = model.train(throughput_list_avg[-40:])
             with open("./train_data.csv", 'a') as t:
                 writer = csv.writer(t)
                 writer.writerow(throughput_list_avg[-40:])
             print("network_condition", network_condition)
             network_condition = np.argmax(network_condition)

             if network_condition == 0:
                 nn_model = NN_MODEL
                 #print("Model0 restored.")
             #self.actor = a3c.ActorNetwork(self.sess,
              #                             state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
               #                            learning_rate=ACTOR_LR_RATE)
             elif network_condition == 1:
                 nn_model = NN_MODEL1
                 #print("Model1 restored.")
             #self.actor = a3c.ActorNetwork(self.sess,
              #                             state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
               #                            learning_rate=ACTOR_LR_RATE)
             elif network_condition == 2:
                 nn_model = NN_MODEL2
                 #print("Model2 restored.")
             #self.actor = a3c.ActorNetwork(self.sess,
              #                             state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
               #                            learning_rate=ACTOR_LR_RATE)
             elif network_condition == 3:
                 nn_model = NN_MODEL3
                 #print("Model3 restored.")
             #self.actor = a3c.ActorNetwork(self.sess,
              #                             state_dim=[S_INFO, S_LEN], action_dim=A_DIM,
               #                            learning_rate=ACTOR_LR_RATE)

             if nn_model is not None:
                 saver.restore(self.sess, nn_model)
                 print("NN_MODEL %g restored" % network_condition)
                 with open("./Model_selection.txt", 'a') as t1:
                     t1.write("NN_MODEL %g restored\n" % network_condition)
                     t1.close()

         if not S_decision_flag[-1]:
             return 0, 0, 0

         if S_decision_flag[-1]:
             # compute action probability vector
             with graph.as_default():
                 action_prob = self.actor.predict(np.reshape(state, (1, S_INFO, S_LEN)))
             #action_cumsum = np.cumsum(action_prob)
             self.bit_rate = np.argmax(action_prob)

             self.s_batch.append(state)

             self.entropy_record.append(a3c.compute_entropy(action_prob[0]))

             if end_of_video:
                 self.last_bit_rate = 0
                 self.bit_rate = 0  # use the default action here

                 del self.s_batch[:]
                 del self.a_batch[:]
                 del self.r_batch[:]

                 self.action_vec = np.zeros(A_DIM)
                 self.action_vec[self.bit_rate] = 1

                 self.s_batch.append(np.zeros((S_INFO, S_LEN)))
                 self.a_batch.append(self.action_vec)
                 self.entropy_record = []

             target_buffer = 1
             latency_limit = 4

             return self.bit_rate, target_buffer, latency_limit

         # If you choose other
         #......

     def get_params(self):
     # get your params
        your_params = []
        return your_params


import spotipy
from spotipy.oauth2 import SpotifyOAuth

def get_access(dict_credintials):
    auth_manager=SpotifyOAuth(**dict_credintials)
    sp=spotipy.Spotify(auth_manager=auth_manager)
    return sp

def create_playlists(current_account,names,descriptions,track_list):
    user=current_account.current_user()["id"]
    for name,description,counter in zip(names,descriptions,range(len(names))):
        start_index,end_index=((counter/len(names))*len(track_list),len(track_list)/len(names))
        playlist_id=current_account.user_playlist_create(user=user,name=name,public=False,description=description)["id"]
        current_account.user_playlist_add_tracks(user=user,playlist_id=playlist_id,tracks=track_list[int(start_index):int(end_index)])