#Implement 3 stacks using a single list:

def __main__():
    # Creates the multi-stack and adds a number of entries to test functionality
    stack = triple_stack()
    stack.push("1", 1)
    stack.push("2", 1)
    stack.push("3", 2)
    stack.push("4", 1)
    stack.push("5", 2)
    stack.push("6", 3)
    stack.push("7", 3)
    stack.push("8", 2)
    stack.push("9", 3)
    stack.show()
    # Showing that removal works correctly
    print(f"Removed: {stack.pop(1)}")
    stack.show()
    print(f"Removed: {stack.pop(2)}")
    stack.show()

class triple_stack:

    # Uses a list to act as the stack
    def __init__(self):
        self.list = []

    # When popping from the stack, checks from the top down and pops the first element found that belongs to that stack number
    def pop(self, stack_number):
        for element in reversed(self.list):
            if element[1] == stack_number:
                return self.list.pop(self.list.index(element))

    # Things are added to the stat as part of a tuple containing the item and which stack it belongs too
    def push(self, item, stack_number):
        self.list.append((item, stack_number))

    # Prints the contents of the stack, for testing
    def show(self):
        print(self.list)

if __name__ == "__main__":
    __main__()


class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        isNegative = True if x < 0 else False
        x = -x if isNegative else x
        result = 0
        while x > 0:
            result = result * 10 + (x % 10)
            if result > 0x7fffffff:
                return 0
            x /= 10
        return -result if isNegative else result


from flask import Flask, render_template, request
from keras.preprocessing import image

import testModel as func

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

# json example， {"best":"0","classify":"thing","line_score":"51","score":"50"}
@app.route('/up_photo',methods=['post'])
def up_photo():
    file = request.form.get('photo')
    json = func.getScore(file)
    return json

# json example， {"classify":"thing","line_score":"51","score":"50"}
@app.route('/up_one_photo',methods=['post'])
def up_one_photo():
    file = request.form.get('photo')
    json = func.getOneScore(file)
    return json

@app.route('/style_transfer',methods=['post'])
def style_transfer():
    photo = request.form.get('photo')
    style = request.form.get('style')
    json = func.style_transfer(photo,style)
    return json

if __name__ == "__main__":
    app.run(host='0.0.0.0',port='80')


def load_stop_words(file_name):
    stopwords = set()
    stopwords.add(' ')
    stopFileName = file_name

    with open(stopFileName, 'r', encoding='UTF-8') as f:
        for word in f:
            stopwords.add(word.strip())

    return stopwords


import xml.etree.ElementTree as ET
from threading import Lock

# global configuration managers
overall_config = None
motor_config = None
cam_config = None
auto_config = None

class ConfigurationError(Exception):
    '''Exception class for configuration.'''
    pass

class Configuration:
    def __init__(self, name="settings.xml"):
        try:
            self.tree = ET.parse(name)
        except FileNotFoundError as e:
            raise ConfigurationError(str(e))
        self.root = self.tree.getroot()
        self.tree_lock = Lock()

    @staticmethod
    def ready():
        global overall_config
        global motor_config
        global cam_config
        global auto_config
        if overall_config is None \
           or motor_config is None \
           or cam_config is None \
           or auto_config is None:
            return False
        return True

    @staticmethod
    def settings_file(name="settings.xml"):
        global overall_config
        global motor_config
        global cam_config
        global auto_config
        overall_config = OverallConfiguration(name)
        motor_config = MotorConfiguration(name)
        cam_config = CameraConfiguration(name)
        auto_config = AutonomousConfiguration(name)

    def _getsubelemvalue(self,elem, pred, match):
        for things in elem:
            for subthing in things:
                try:
                    if subthing.attrib[pred] == match:
                        return subthing
                except KeyError:
                    return None

    def _getsubelemvaluebyname(self, elem, subname, pred, match):
        for things in elem:
            for subthing in things:
                if subthing.tag == subname:
                    try:
                        if subthing.attrib[pred] == match:
                            return subthing
                    except KeyError:
                        return None

    def _make_searchstr_list(self, req_list):
        searchstr_list = []
        for elemstr in req_list:
            searchstr = "."
            elem_list = elemstr.split('.')
            for elem in elem_list:
                idx1 = elem.find('{')
                idx2 = elem.find('}')
                tagname = elem[idx1+1:idx2]
                searchstr = searchstr + "/" + tagname.upper()
                idx3 = elem.find('[')
                idx4 = elem.find(']')
                if (idx3 == -1) or (idx4 == -1):
                    continue
                attrtype = elem[idx3+1:idx4].upper()
                attrname = elem[idx4+1:]
                searchstr = searchstr + "[@"+attrtype+"='"+attrname+"']"
            searchstr_list.append(searchstr)
        return searchstr_list

    def provide_settings(self, req_list):
        if not req_list:
            return None
        searchstr_list = self._make_searchstr_list(req_list)
        res_list = []
        with self.tree_lock:
            for searchstr in searchstr_list:
                res = self.root.findall(searchstr)
                res_list.append(res)
        if not res_list[0]:
            return None
        return res_list

    def top_level_element_value(self, name):
        elem_list = self.provide_settings(["{"+name+"}"])
        if not elem_list:
            return None
        return (elem_list[0][0].text.strip())

class MotorConfiguration(Configuration):
    def __init__(self, name="settings.xml"):
        Configuration.__init__(self, name)

    def get_pwm_pin(self, motor_group ,motor_name):
        req = ["{Motors}[name]"+motor_group+".{Motor}[name]"
               +motor_name]
        motor = self.provide_settings(req)
        # pin = self._getsubelemvalue(motor[0],"TYPE","PWM")
        pin = self._getsubelemvaluebyname(motor[0], "PIN", "TYPE", "PWM")
        try:
            return int(pin.text)
        except ValueError as e:
            raise ConfigurationError("Bad value in settings file for pwm pin of motor '"+motor_name+"'. Error: "+str(e))

    def get_digital_pin(self, motor_group, motor_name):
        req = ["{Motors}[name]"+motor_group+".{Motor}[name]"
               +motor_name]
        motor = self.provide_settings(req)
        # pin = self._getsubelemvalue(motor[0], "TYPE", "Digital")
        pin = self._getsubelemvaluebyname(motor[0], "PIN", "TYPE", "Digital")
        try:
            return int(pin.text)
        except ValueError as e:
             raise ConfigurationError("Bad value in settings file for digital pin of motor '"+motor_name+"'. Error: "+str(e))

    def get_pin(self, motor_group, motor_name):
        req = ["{Motors}[name]"+motor_group+".{Motor}[name]"
               +motor_name]
        motor = self.provide_settings(req)
        # pin = self._getsubelemvalue(motor[0], "TYPE", "Other")
        pin = self._getsubelemvaluebyname(motor[0], "PIN", "TYPE", "Other")
        try:
            return int(pin.text)
        except ValueError as e:
            raise ConfigurationError("Bad value in settings file for pin of motor '"+motor_name+"'. Error: "+str(e))

    def get_limit(self, motor_group, motor_name, lim_name):
        req = ["{Motors}[name]"+motor_group+".{Motor}[name]"+motor_name]
        motor = self.provide_settings(req)
        lim_name = str.capitalize(lim_name)
        lim = self._getsubelemvaluebyname(motor[0], "LIMIT" ,"NAME", lim_name)
        try:
            return float(lim.text)
        except ValueError as e:
            raise ConfigurationError("Bad value in settings file for limit '{}'\
 of motor '{}'. Error: {}".format(lim_name,motor_name,str(e)))
        except AttributeError as e:
            raise ConfigurationError("Search for limit '{}' on motor '{}' \
of group '{}' returned no result".format(lim_name,motor_name,motor_group))

class CameraConfiguration(Configuration):
    def __init__(self, name="settings.xml"):
        Configuration.__init__(self,name)

    def _generic_integer_setting(self, name):
        req = ["{Camera}.{"+name+"}"]
        elem_list = self.provide_settings(req)
        if not elem_list:
            return None
        val = int(elem_list[0][0].text.strip())
        return val

    def _generic_string_setting(self, name):
        req = ["{Camera}.{"+name+"}"]
        elem_list = self.provide_settings(req)
        if not elem_list:
            return None
        val = elem_list[0][0].text.strip()
        return val

    def device(self):
        dev = self._generic_string_setting('device')
        if dev == 'rpicamsrc' or dev == 'v4l2src' or dev == 'avfvideosrc' or \
           dev == 'autovideosrc':
            return dev
        raise ConfigurationError("Error in camera settings: invalid device specified, can only be 'rpicamsrc','v4l2src' or 'avfvideosrc'.")

    def capture_framerate(self):
        return self._generic_integer_setting('capture_framerate')

    def capture_frame_width(self):
        return self._generic_integer_setting('capture_frame_width')

    def capture_frame_height(self):
        return self._generic_integer_setting('capture_frame_height')

    def stream_port(self):
        return self._generic_integer_setting('stream_port')

    def stream_framerate(self):
        return self._generic_integer_setting('stream_framerate')
    def stream_frame_width(self):
        return self._generic_integer_setting('stream_frame_width')

    def stream_frame_height(self):
        return self._generic_integer_setting('stream_frame_height')

class AutonomousConfiguration(Configuration):
    def __init__(self, name="settings.xml"):
        Configuration.__init__(self,name)

    def _generic_integer_setting(self,name):
        req = ["{Autonomous}.{"+name+"}"]
        elem_list = self.provide_settings(req)
        if not elem_list:
            return None
        val = int(elem_list[0][0].text.strip())
        return val

    def _generic_string_setting(self,name):
        req = ["{Autonomous}.{"+name+"}"]
        elem_list = self.provide_settings(req)
        if not elem_list:
            return None
        val = elem_list[0][0].text.strip()
        return val

    def cv_engine(self):
        return self._generic_string_setting('cvengine')

    def capture_framerate(self):
        return self._generic_integer_setting('capture_framerate')

    def capture_frame_width(self):
        return self._generic_integer_setting('capture_frame_width')

    def capture_frame_height(self):
        return self._generic_integer_setting('capture_frame_height')

    def stream_port(self):
        return self._generic_integer_setting('stream_port')

    def stream_framerate(self):
        return self._generic_integer_setting('stream_framerate')

    def stream_frame_width(self):
        return self._generic_integer_setting('stream_frame_width')

    def stream_frame_height(self):
        return self._generic_integer_setting('stream_frame_height')

    def ultrasound_trigger_pin(self):
        return self._generic_integer_setting('ultrasound_trigger_pin')

    def ultrasound_echo_pin(self):
        return self._generic_integer_setting('ultrasound_echo_pin')

    def ultrasound_power_pin(self):
        return self._generic_integer_setting('ultrasound_power_pin')

    def ultrasound_ground_pin(self):
        return self._generic_integer_setting('ultrasound_ground_pin')

class OverallConfiguration(Configuration):
    def __init__(self, name="settings.xml"):
        Configuration.__init__(self, name)
        self.connected_ip = '0.0.0.0' # ip address to which remote has connected
        self.running_as_unit = False # if start_rover was called with --as-unit

    def opmodes_directories(self):
        dir_list_str = self.top_level_element_value("OPMODES_DIRECTORIES")
        if dir_list_str is None:
            raise ConfigurationError("No settings found for operational mode directories.")
        dir_list_str = dir_list_str.replace('\n','').replace(' ','')
        dir_list = dir_list_str.split(',')
        if '' in dir_list and len(dir_list) > 1:
            raise ConfigurationError("Error in operational mode settings: probably extra comma in list.")
        return dir_list

    def resources_directories(self):
        dir_list_str = self.top_level_element_value("RESOURCES_DIRECTORIES")
        if dir_list_str is None:
            raise ConfigurationError("No settings found for resources directories.")
        dir_list_str = dir_list_str.replace('\n','').replace(' ','')
        dir_list = dir_list_str.split(',')
        if '' in dir_list and len(dir_list) > 1:
            raise ConfigurationError("Error in resource settings: probably extra comma in list.")
        return dir_list

    def diagnostics_enabled(self):
        req = ["{Diagnostics}.{state}"]
        elem_list = self.provide_settings(req)
        if not elem_list:
            raise ConfigurationError("No settings found for Diagnostics state.")
        en_str = elem_list[0][0].text.strip()
        if en_str == "Enabled":
            return True
        elif en_str == "Disabled":
            return False
        raise ConfigurationError("Error in Diagnostics settings: invalid state, can only be 'Enabled' or 'Disabled'.")

    def diagnostics_port(self):
        req = ["{Diagnostics}.{port}"]
        elem_list = self.provide_settings(req)
        if not elem_list:
            raise ConfigurationError("No settings found for Diagnostics.")
        port_str = elem_list[0][0].text.strip()
        try:
            port = int(port_str)
        except TypeError:
            raise ConfigurationError("Error in Diagnostics settings: port number setting must be an integer.")
        if port < 1000:
            raise ConfigurationError("Error in Diagnostics settings: port number needs to be larger than 1000 to prevent conflict with reserved ports.")
        return port

    def set_unitname(self, unitname):
        self.unitname = unitname

    def main_hostname(self):
        hostname = self.top_level_element_value("MAIN_HOSTNAME")
        if hostname is None:
            raise ConfigurationError("No settings found for main unit hostname.")
        hostname = hostname.replace(' ','')
        return hostname

    def set_ip(self, ip):
        self.connected_ip = ip

    def get_connected_ip(self):
        return self.connected_ip


# -*- coding: utf-8 -*-
"""
File Name：     steam_comments
Description :
Author :       meng_zhihao
mail :       312141830@qq.com
date：          2020/7/4
"""
from crawl_tool_for_py3 import crawlerTool as ct

import csv

FOUT= open('steam_comments.csv', 'w', encoding='utf_8_sig', newline='', )
csv_writer = csv.writer(FOUT)
csv_writer.writerow(['AuthorName','title','hours','date','comment_content','helpfuls','funnys'])

def extractor(page_buf):
    comments = []

    segs = ct.getXpath('//div[contains(@class,"apphub_Card ")]',page_buf)
    for seg in segs:
        helpfuls = ct.getRegex('(\d+) people found this review helpful',seg)
        funnys = ct.getRegex('(\d+) people found this review funny',seg)
        title = ct.getXpath1('//div[@class="title"]/text()',seg)
        hours =  ct.getXpath1('//div[@class="hours"]/text()',seg)
        comment_content_and_date = ct.getXpath('//div[@class="apphub_CardTextContent"]/text()',seg)
        date = ct.getXpath1('//div[@class="date_posted"]/text()',seg)
        comment_content= ' '.join(comment_content_and_date[1:])
        apphub_CardContentAuthorName = ct.getXpath1('//div[contains(@class,"apphub_CardContentAuthorName")]/a/text()',seg)

        comments.append([apphub_CardContentAuthorName,title,hours,date,comment_content,helpfuls,funnys])
    for comment in comments:
        csv_writer.writerow(comment)
        FOUT.flush()
    return comments

def main(app_id):
    app_id = str(app_id)
    ct_obj = ct()
    entry_url = 'https://store.steampowered.com/app/%s'%app_id
    rs = ct_obj.sget(entry_url,cookies={"Steam_Language":"english","birthtime":"725817601","lastagecheckage":"1-January-1993"}) # 语言和18周岁限制
    review_url = 'https://steamcommunity.com/app/%s/reviews/?browsefilter=toprated&snr=1_5_100010_&filterLanguage=english'% app_id
    # review_url = 'https://steamcommunity.com/app/394360/homecontent/?userreviewscursor=AoIIPvnRs3yBhKkB&userreviewsoffset=11428&p=1144&workshopitemspage=1144&readytouseitemspage=1144&mtxitemspage=1144&itemspage=1144&screenshotspage=1144&videospage=1144&artpage=1144&allguidepage=1144&webguidepage=1144&integratedguidepage=1144&discussionspage=1144&numperpage=10&browsefilter=toprated&browsefilter=toprated&appid=394360&appHubSubSection=10&appHubSubSection=10&l=english&filterLanguage=english&searchText=&forceanon=1'
    while True: # 最后会页面空白
        results = []
        for retry_times in range(3): # 异常重试
            page_buf = ct_obj.sget(review_url)
            results = extractor(page_buf)
            if results:break
        if not results:
            break
        userreviewscursor = ct.getXpath1('//input[@name="userreviewscursor"]/@value',page_buf)
        userreviewsoffset = ct.getXpath1('//input[@name="userreviewsoffset"]/@value',page_buf)
        workshopitemspage = ct.getXpath1('//input[@name="workshopitemspage"]/@value',page_buf)
        readytouseitemspage  = ct.getXpath1('//input[@name="readytouseitemspage"]/@value',page_buf)
        p = ct.getXpath1('//input[@name="p"]/@value',page_buf)
        mtxitemspage = ct.getXpath1('//input[@name="mtxitemspage"]/@value',page_buf)
        itemspage =  ct.getXpath1('//input[@name="itemspage"]/@value',page_buf)
        screenshotspage =  ct.getXpath1('//input[@name="screenshotspage"]/@value',page_buf)
        videospage = ct.getXpath1('//input[@name="videospage"]/@value',page_buf)
        artpage = ct.getXpath1('//input[@name="artpage"]/@value',page_buf)
        allguidepage = ct.getXpath1('//input[@name="allguidepage"]/@value',page_buf)
        webguidepage = ct.getXpath1('//input[@name="webguidepage"]/@value',page_buf)
        integratedguidepage = ct.getXpath1('//input[@name="integratedguidepage"]/@value',page_buf)
        discussionspage = ct.getXpath1('//input[@name="discussionspage"]/@value',page_buf)
        numperpage = ct.getXpath1('//input[@name="numperpage"]/@value',page_buf)
        browsefilter = ct.getXpath1('//input[@name="browsefilter"]/@value',page_buf)
        l = ct.getXpath1('//input[@name="l"]/@value',page_buf)
        appHubSubSection = ct.getXpath1('//input[@name="appHubSubSection"]/@value',page_buf)
        browsefilter = ct.getXpath1('//input[@name="browsefilter"]/@value',page_buf)
        filterLanguage = ct.getXpath1('//input[@name="filterLanguage"]/@value',page_buf)
        searchText =  ct.getXpath1('//input[@name="searchText"]/@value',page_buf)
        forceanon = ct.getXpath1('//input[@name="forceanon"]/@value',page_buf)

        review_url =  'https://steamcommunity.com/app/'+app_id+'/homecontent/?userreviewscursor='+ct.quote(userreviewscursor)+'&userreviewsoffset='+userreviewsoffset\
                      +'&p='+p+'&workshopitemspage='+workshopitemspage+'&readytouseitemspage='+readytouseitemspage+\
                      '&mtxitemspage='+mtxitemspage+'&itemspage='+itemspage+'&screenshotspage='+screenshotspage+'&videospage='+videospage+'&artpage='+artpage+'&allguidepage='+allguidepage+\
                          '&webguidepage='+webguidepage+'&integratedguidepage='+integratedguidepage+'&discussionspage='+discussionspage+'&numperpage='+numperpage+'&browsefilter='+browsefilter+'&browsefilter='+browsefilter+\
                          '&appid='+app_id+'&appHubSubSection='+appHubSubSection+'&appHubSubSection='+appHubSubSection+'&l='+l+'&filterLanguage='+filterLanguage+'&searchText='+searchText+'&forceanon='+forceanon
        print(review_url)

if __name__ == '__main__':
    app_id = 394360
    main(app_id)


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

from graphviz import Digraph

class Edge:
    def __init__(self, start, finish, weight=0, min_weight=0, redge=False):
        self.start = start
        self.finish = finish
        self.min_weight = min_weight
        self.weight = weight
        self.redge = redge  # flag for saying, that its incoming edge

    def __repr__(self):
        return '({0})-{1}{2}->({3})'.format(
            self.start,
            '{},'.format(self.min_weight) if self.min_weight != 0 else '',
            self.weight, self.finish)

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, another):
        return self.start == another.start \
               and self.finish == another.finish \
               and self.weight == another.weight \
               and self.min_weight == another.min_weight

class Mark:
    def __init__(self, parent=None, flow=float('inf'), edge=None, sign=1):
        self.parent = parent
        self.flow = flow
        self.edge = edge
        self.sign = sign

    def __repr__(self):
        return '({}, {})'.format(self.parent, self.flow)

class FlowNetwork:
    def __init__(self, file_name):
        self.adj = {}
        self.flow = {}
        self.file_name = file_name

    def add_vertex(self, vertex):
        self.adj[vertex] = []

    def get_vertex(self):
        vertex = self.adj.keys()
        vertex.sort()
        return vertex

    def add_edge(self, u, v, w=0, min_w=0, f=0):
        if u == v:
            raise ValueError('u == v')

        edge = Edge(u, v, w, min_w)
        redge = Edge(u, v, w, min_w, redge=True)

        self.adj[u].append(edge)
        self.adj[v].append(redge)

        self.flow[edge] = f

    def get_edges(self, v):
        """
        Return outcoming edges for v
        :param v: node
        :return: list of Edge object's
        """
        return filter(lambda e: not e.redge, self.adj[v])

    def get_redges(self, v):
        """
        Return incoming edges for v
        :param v: node
        :return: list of Edge object's
        """
        return filter(lambda e: e.redge, self.adj[v])

    def get_marks(self, _from, _to):
        """
        Set marks for nodes
        :param _from: a source
        :param _to: a sink
        :return: list og Mark object's
        """
        marks = dict.fromkeys(self.get_vertex())
        marks[_from] = Mark()
        queue = [_from]

        while queue:
            v = queue.pop(0)
            if v == _to:
                return marks

            for edge in self.get_edges(v):
                if not marks[edge.finish] and self.flow[edge] < edge.weight:
                    flow = min(marks[v].flow, edge.weight - self.flow[edge])
                    marks[edge.finish] = Mark(v, flow, edge)
                    queue.append(edge.finish)

            for redge in self.get_redges(v):
                if not marks[redge.start] and self.flow[redge] > redge.min_weight:
                    flow = min(marks[v].flow, self.flow[redge] - redge.min_weight)
                    marks[redge.start] = Mark(v, flow, redge, sign=-1)
                    queue.append(redge.start)

        return marks

    def max_flow(self, _from, _to, out=None, write=True):
        """
        Find max flow in network
        :param _from: a source
        :param _to: a sink
        :param write: param for disabling file outputs
        :return: max flow, marks from last iteration
        """
        if write:
            out.write('* table with marks by iteration:\n\n')
            self.print_table_head(out)
        marks = self.get_marks(_from, _to)

        while marks[_to]:
            if write:
                self.print_table_row(out, marks)
            i = _to
            min_flow = marks[_to].flow
            while marks[i].parent:
                self.flow[marks[i].edge] += marks[i].sign*min_flow
                i = marks[i].parent
            marks = self.get_marks(_from, _to)

        flow = sum(self.flow[edge] for edge in self.get_edges(_from))
        if write:
            self.print_table_row(out, marks)
            out.write('\n* maximal flow = {}:\n'.format(flow))
            self.print_flow(out)
        return flow, marks

    def print_flow(self, out):
        out.write('```\n')
        keys = self.flow.keys()
        keys.sort()
        for key in keys:
            out.write('\t{0} - [{1}]\n'.format(key, self.flow[key]))
        out.write('```\n\n')

    def print_table_head(self, out):
        out.write(reduce(lambda s, x: '{0} | {1} '.format(s, x), self.get_vertex()) + '\n')
        out.write('--- | '*len(self.get_vertex()) + '\n')

    def print_table_row(self, out, marks):
        for v in self.get_vertex():
            out.write('`{}` | '.format(marks[v]))
        out.write('\n')

    def draw(self, show=False, postfix=''):
        """
        Render graph to png and save to filesystem
        :param show: flag to open image in new window
        :return: None
        """
        g = Digraph('G', filename='{}.gv'.format(self.file_name + postfix), directory='out', format='png')
        for v in self.get_vertex():
            for e in self.get_edges(v):
                flow = ''
                if self.flow[e] != 0:
                    if self.flow[e] != e.weight:
                        flow = '[{0}/{1}]'.format(self.flow[e], e.weight)
                    else:
                        flow = '[{}]'.format(self.flow[e])
                color = 'red' if self.flow[e] != 0 else ''
                g.edge(e.start, e.finish, label=flow, color=color)
        g.render(view=show)


t,k = map(int,input().split())
ans=[]
for j in range(t):
    tmp=list(map(int,input().split()))
    ans.append(tmp)
ans=[(k-abs(ans[i][0]-ans[j][0]))*(k-abs(ans[i][1]-ans[j][1])) if abs(ans[i][0]-ans[j][0])<k and abs(ans[i][1]-ans[j][1])<k else 0 for i in range(len(ans)) for j in range(i+1,len(ans))]
ans=list(filter(lambda x:x,ans))
if len(ans)==1:
    print(ans[0])
elif not ans:
    print(0)
else:
    print(-1)


import Project_Lib as pl
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split

# GPU memory management
gpu = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpu[0], True)

# Load and analyze train and test dataset
dir_path_train = r"C:/Users/ASUS/Desktop/AMLS_Assignment/AMLS_PROJECT/UCI_HAR_Dataset/train"
dir_path_test = r"C:/Users/ASUS/Desktop/AMLS_Assignment/AMLS_PROJECT/UCI_HAR_Dataset/test"
data_train, label_train = pl.build_dataset(dir_path_train, 'Inertial Signals', 'train')
data_test, label_test = pl.build_dataset(dir_path_test, 'Inertial Signals', 'test')
pl.distribution_ana(label_train)
pl.distribution_ana(label_test)
print(data_train.shape)
print(label_train.shape)
print(data_test.shape)
print(label_test.shape)

# plot one data
"""
print('plot begin')
time_steps= range(0, 128, 1)
fig, ax = plt.subplots(1,1, figsize=(10,6))
ax.plot(time_steps, data_train[1,:,1], label='body acc x')
ax.set_title('Body acceleration for one time window)', fontsize=22)
ax.set_xlabel(r'Time steps', fontsize=22)
ax.set_ylabel(r'Acceleration', fontsize=22)
ax.tick_params(labelsize=22)
ax.legend(fontsize=24)
plt.show()
print('plot finished')
"""

# manually shuffle prepared train set and test set
"""
index_train = [i for i in range(len(data_train))]
index_test = [i for i in range(len(data_test))]
np.random.shuffle(index_train)
np.random.shuffle(index_test)
data_train = data_train[index_train, :, :]
data_test = data_test[index_test, :, :]
label_train = label_train[index_train]
label_test = label_test[index_test]
"""

# manually create and shuffle train set and test set; note: the result is very bad! Why?
"""
data = np.concatenate((data_train, data_test), axis=0)
label = np.concatenate((label_train, label_test), axis=0)
print("New data shape: " + str(data.shape))
print("New label shape: " + str(label.shape))
index = [i for i in range(len(data))]
np.random.shuffle(index)
data_ = data[index, :, :]
label = label[index]
data_train, data_test, label_train, label_test = train_test_split(data, label, test_size=0.2, random_state=1)
print("Balance after shuffle: ")
pl.distribution_ana(label_train)
pl.distribution_ana(label_test)
print(data_train.shape)
print(label_train.shape)
print(data_test.shape)
print(label_test.shape)
"""

# Train and test all models without standardization
"""
histories_cnn = pl.evaluate_repreat(data_train, label_train, data_test, label_test, 'cnn', 5)
histories_lstm = pl.evaluate_repreat(data_train, label_train, data_test, label_test, 'lstm', 5)
histories_cnn_lstm = pl.evaluate_repreat(data_train, label_train, data_test, label_test, 'cnn_lstm', 5)
histories_convlstm = pl.evaluate_repreat(data_train, label_train, data_test, label_test, 'conv_lstm', 5)
"""
"""
# Train and test all models with standardization
data_train_std, data_test_std = pl.standardization(data_train, data_test)
data_train_std = data_train
data_test_std = data_test
histories_cnn = pl.evaluate_repreat(data_train_std, label_train, data_test_std, label_test, 'cnn', 5)
histories_lstm = pl.evaluate_repreat(data_train_std, label_train, data_test_std, label_test, 'lstm', 5)
histories_cnn_lstm = pl.evaluate_repreat(data_train_std, label_train, data_test_std, label_test, 'cnn_lstm', 5)
histories_convlstm = pl.evaluate_repreat(data_train_std, label_train, data_test_std, label_test, 'conv_lstm', 5)

# Plot learning curve
fig, ax = plt.subplots(figsize=(15, 50), ncols=1, nrows=4)
histories = [histories_cnn[4], histories_lstm[4], histories_cnn_lstm[4], histories_convlstm[4]]
histories_name = ['cnn', 'lstm', 'cnn-lstm', 'convlstm']
#histories = [histories_cnn[4]]
#histories_name = ['cnn']

for n in range(4):
    print('plot begin')
    time_steps = range(1, len(histories[n].history['acc'])+1)
    ax[n].plot(time_steps, histories[n].history['acc'], 'ro', label=str(histories_name[n])+'acc')
    ax[n].plot(time_steps, histories[n].history['val_acc'], 'b', label=str(histories_name[n])+'val_acc')
    ax[n].set_title(str(histories_name[n]), fontsize=22)
    ax[n].set_xlabel(r'Epochs', fontsize=22)
    ax[n].set_ylabel(r'Accuracy', fontsize=22)
    ax[n].tick_params(labelsize=22)
    ax[n].legend(fontsize=24)
    print('plot finished')
plt.show()
"""
fig, ax = plt.subplots(figsize=(10, 6), ncols=1, nrows=1)
print('plot begin')
sample_num = range(1, len(label_train[0:175])+1)
ax.plot(sample_num, label_train[0:175], 'ro', label=r'labels')
ax.set_title(r'training labels', fontsize=22)
ax.set_xlabel(r'sample number', fontsize=22)
ax.set_ylabel(r'label', fontsize=22)
ax.tick_params(labelsize=22)
ax.legend(fontsize=24)
print('plot finished')
plt.show()


# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import json
from datetime import date,datetime,timedelta
from flyDB import FlyDB
import time
from fly import Fly
'''
机票价格爬虫
'''
def request(url):
    result = requests.get(url)
    if result.status_code == 200:
        return result.content
    else:
        print("请求失败." + str(result.status_code))
        return False

def process(content,fly):
    result = []
    soup = BeautifulSoup(content,"html.parser")
    rows = soup.find_all(class_="cssRadio row3")
    while len(rows) > 0:
        row = rows.pop()
        if row is not None:
            label = row.contents[1]
            labelDict = label.attrs
            departingtime = labelDict['data-departingtime']
            value = labelDict['value']
            label = row.contents[3]
            labelDict = label.attrs
            price = labelDict['data-amount']
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            fly.setValue(departingtime,price,value,now)
            if float(price) < 3000:
                result.append(fly.toTuple())
        else:
            print("请求失败,价格行为空")
        print(json.dumps(fly.toDict()))
    return result

def conf(date,fromdis,todis):
    url = 'https://beta.cebupacificair.com/Flight/InternalSelect?'
    param = 'o1=' + fromdis + "&d1=" + todis + "&o2=&d2=&dd1=" + date + "&p=&ADT=1&CHD=0&INF=0&s=true&mon=true"
    fly = Fly(fromdis,todis,"cebu")
    return url + param,fly

def test():
    day = date(2020,2,1)
    url,fly = conf(day.strftime('%Y-%m-%d'),'MNL','CEB')
    result = request(url)
    rows = process(result,fly)
    print("================================")
    for row in rows:
        print(row)

# HKG,CEB,ILO,
def main():
    day = date(2019,2,1)
    for i in range(3):
        url,fly = conf(day.strftime('%Y-%m-%d'),'HKG','ILO')
        result = request(url)
        if result is False:
            print("获取数据失败")
            return
        rows = (process(result,fly))

        url,fly = conf(day.strftime('%Y-%m-%d'),'HKG','CEB')
        result = request(url)
        if result is False:
            print("获取数据失败")
            return
        rows.extend(process(result,fly))

        url,fly = conf(day.strftime('%Y-%m-%d'),'HKG','MNL')
        result = request(url)
        if result is False:
            print("获取数据失败")
            return
        rows.extend(process(result,fly))

        flyDB = FlyDB("mysql")
        flyDB.insertValue(rows)

        time.sleep(2)
        print("current date is %s ,flydate been Get" % day.strftime('%Y-%m-%d'))
        day = day + timedelta(days=1)

test()


import os
import sys

# Standard simulation configuration
SUMO_TEST_CFG = "cfg/freeway_test.sumocfg"

# Path to SUMO home directory
if 'SUMO_HOME' not in os.environ:
    sys.exit("Please declare environment variable 'SUMO_HOME'")
SUMO_HOME = os.environ['SUMO_HOME']
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)

SUMO_PARAMS = ["--lateral-resolution", "0.8",
               "--quit-on-end"]

# Set to False for faster simulations
SHOW_GUI = False
SHOW_SIMUWATCH = False

# Print debug information
DEBUG = False

# Distance the platoon will drive before the simulation ends (in meters)
DISTANCE_TO_DRIVE = 3200

# Simulation step length (in seconds)
STEP_LENGTH = 0.01

# Recordings per second
REC_PER_SEC = 10

# Seed for random numbers (SUMO default value is 23423)
RND_SEED = '23422'

# Lane width (info value, not a parameter)
LANE_WIDTH = 3.2

# Lateral start position of platoon (info value, not a parameter)
LAT_POS_START = 42

# Minimum lateral offset (in meters) when to look for the crossing of lane markings
LANE_OFFSET_MIN = 0.5

# Oscillation modifier to avoid oscillation
OSCILLATION_MOD = 0.01

# ----- Messaging parameters ----- #

# Reliability of the messaging system (exponentially distributed)
# 5 for conference setup, 0 for thesis and tests
MEAN_STEP_DURATION_MSG_DELIVERY = 5

# ----- Algorithm parameters ----- #

# The distance from the most left edge of the road to the point where the platoon has to be on the right lane
# (e.g., to exit the freeway)
# NEXT_NAV_POINT = 700

# Turn the algorithm on or off (do not enable in combination with Plexe algorithm)
OVERTAKING_ALGORITHM_ON = True

# Turn the Plexe overtaking algorithm on or off (do not enable in combination with algorithm)
PLEXE_OVERTAKING_ON = False

# Exit after one full overtaking maneuver
EXIT_ON_OVERTAKING = False

# Plexe platoon controller
# ACC = 1, CACC = 2, PLOEG = 4, CONSENSUS = 5
PLEXE_LEADER_CONTROLLER = 1
PLEXE_FOLLOWER_CONTROLLER = 2

# Maximum number of simulation steps for an overtaken vehicle not being detected during a lane change to not cause
# abortion of the lane change (if an overtaken vehicle is not detected for MAX_NOT_DETECTED + 1 simulation steps,
# the lane change will be aborted)
# Necessary, because SUMO does not detect the overtaken vehicle when crossing two lanes
MAX_NOT_DETECTED = 3

# Maximum power of back-off. Back-off is computed as 2 ** (back-off), back-off starts at MIN_BACKOFF
# 2 ** MIN_BACKOFF should be bigger than MAX_TIMER
MAX_BACKOFF = 8
MIN_BACKOFF = 5

# Timeout in overtaking algorithm steps
MAX_TIMER = 20

# Speed deviations smaller than ROUND_PRECISION will be handled as equal speeds
ROUND_PRECISION = 0.05

# Maximum length of one truck (in meters)
TRUCK_MAX_LENGTH = 18.75

# Threshold (in seconds) for an overtaking maneuver
# 100000000 for conference setup, 45 for thesis and tests
MAX_OVERTAKING_TIME = 100000000

# Threshold speed delta of platoon and slower vehicle needed to allow overtaking
# 0.1 for conference setup, 2.7 for thesis and tests
MIN_OVERTAKING_SPEED_DELTA = 0.1

# Overtake if distance to slower vehicle is x * safety distance
FACTOR_SAFETY_DISTANCE = 100

# Maximum accepted acceleration (in m/s^2) of closest RL vehicle to avoid collision with platoon when platoon is
# deciding to merge in his lane (lane change left)
MAX_ACCEL_VEHICLE_LEFT = -1.0
# Maximum accepted acceleration (in m/s^2) of closest Rx vehicle to avoid collision with platoon when platoon is
# already merging in his lane
MAX_ACCEL_R_VEHICLE_ABORT = -3.5
# Maximum accepted acceleration (in m/s^2) of closest RR vehicle to avoid collision with platoon when platoon is
# deciding to merge in his lane (lane change right)
MAX_ACCEL_VEHICLE_RIGHT = 0

# Reaction time of other vehicle's drivers (in seconds)
R_REACT = 1

# Desired time gap of other vehicle's drivers (in seconds)
R_TIME_GAP = 0.8

# Min safety distance (in meter) for a non-platooning truck on a German freeway
TRUCK_MIN_GAP = 50

# Time headway (in seconds) of a non-platooning truck (reaction time + desired time gap)
TRUCK_HEADWAY = 1.8

# Time that the platoon should drive on the original lane after returning from the overtaking lane before
# overtaking again
TIME_STAY_IN_ORIGINAL_LANE = 10

# The lateral offset threshold for a platoon member considered not following anymore (in meters)
MEMBER_MAX_OFFSET = 0.4

# ----- Platoon parameters ----- #

# Id of platoon leader
LEADER = 'Platoon_0'

# Prefix for platoon members
ID_PRE = 'Platoon'

# Platoon route
PLATOON_ROUTE = 'freeway'

# Platoon length (is overwritten by Platoon.build())
PLATOON_MEMBERS = 4

# Inter-vehicle distance
INTER_VEHICLE_DISTANCE = 5

# Damping ratio
XI = 1.0

# Bandwidth of the controller
OMEGA_N = 0.2

# Leader/front vehicle weighting factor
C1 = 0.5

# Cruise control speed (in m/s)
SPEED = 30.55

# ACC headway time in s
ACC_HEADWAY = 1.0

# Radar length (in m)
RADAR_FRONT = 160
RADAR_REAR = 80


from copy import deepcopy
import threading
import json
import logging
from datetime import datetime
import time
import uuid
from psycopg2 import pool as pgpool
import psycopg2
from kafka import KafkaConsumer

logger = logging.getLogger(__name__)

class KafkaConsumerWrapper:
    def __init__(self, connection_args, topic):
        self.topic = topic
        consumer_args = {
            'auto_offset_reset': "earliest",
            'group_id': 'httpmon',
            'client_id': uuid.uuid4(),
            'value_deserializer': lambda v: json.loads(v.decode('utf-8')),
        }
        connection_args.update(consumer_args)
        self.consumer = KafkaConsumer(**connection_args)
        self.consumer.subscribe([self.topic])

    def messages(self):
        raw_msgs = self.consumer.poll(timeout_ms=1000)
        for tp, msgs in raw_msgs.items():
            for msg in msgs:
                logger.info('got msg: %s' % str(msg))
                yield msg.value
        self.consumer.commit()

class PGExporter:
    def __init__(self, connection_args, pool_size=10):
        self.pool = pgpool.ThreadedConnectionPool(1, pool_size, connection_args)

    @staticmethod
    def worker(pool, sql, params):
        conn = None
        while not conn:
            try:
                conn = pool.getconn()
            except pgpool.PoolError:
                logger.warning("No free connection in pool")
                time.sleep(1)

        with conn.cursor() as curs:
            try:
                curs.execute(sql, params)
                conn.commit()
                logger.info("Put to DB: %s" % params)
            except psycopg2.Error as e:
                logger.error(e)
        pool.putconn(conn)

    def submit(self, message):
        sql = """INSERT INTO checks
        (url, timestamp, code, body_check_valid, time)
        VALUES
        (%(url)s, %(timestamp_dt)s, %(code)s, %(body_check_valid)s, %(time)s)
        """
        message = deepcopy(message)
        message['timestamp_dt'] = datetime.fromtimestamp(message['timestamp'])
        thread = threading.Thread(
            target=self.worker, args=(self.pool, sql, message))
        thread.start()

def consumer_loop(consumer, exporter):
    while True:
        for message in consumer.messages():
            exporter.submit(message)


import argparse
from heapq import heappush, heappop, heapify
import math

def valid_stream(stream: list[int], default_stream: list[int]) -> list[int]:
    if stream is None:
        return default_stream
    return stream

def get_args(default_args: dict):
    parser = argparse.ArgumentParser(description="Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.")

    parser.add_argument('--stream', nargs='*', type=int, metavar='list', default=default_args['stream'], help=f'The stream. By default his param is equal to "{default_args["stream"]}"')

    args = parser.parse_args()

    args.stream = valid_stream(args.stream, default_args['stream'])

    return args

def daily(stream):

    upper = []
    lower = []
    for e in stream:
        heappush(lower, -e)
        heappush(upper, -heappop(lower))

        if len(upper) > len(lower):
            heappush(lower, -heappop(upper))

        if len(upper) != len(lower):
            print(-lower[0])
        else:
            print((upper[0] - lower[0])/2)

if __name__ == "__main__":

    default_args = {
        "stream" : [2, 1, 5, 7, 2, 0, 5]
    }

    args = get_args(default_args)
    daily(args.stream)


nums=input()
lower=int(input())
upper=int(input())
count=0
for x in range(0,len(nums)):
    temp=0
    for j in range(x, len(nums)):
        temp+=nums[j]
        if temp >= lower and temp<= upper:
            count+=1
print(count)


Weight, Height = input().split()
Weight = eval(Weight)
Height = eval(Height)
BMI = Weight/Height**2
BMI = (round(BMI, 3));
BMI = (format(BMI,".3f"))
print(BMI)
BMI = eval(BMI)
if BMI<18.5:
    print ('Underweight')
elif BMI > 25.0 or BMI ==25.0:
    print('Obese')
elif BMI==18.5 or 18.5< BMI <23.0:
    print('Normal')
else:
    print('Overweight')


import asyncio
import os
import random
from discord.ext import commands
import dotenv

dotenv.load_dotenv()

TOKEN = os.environ.get('TOKEN')
bot = commands.Bot('>_ ', self_bot=True)
fish_channel = None

@bot.event
async def on_ready():
    print('ready >:)')

@bot.event
async def on_message(message):
    global fish_channel

    if message.content == 'fish':
        if message.author.id == bot.user.id:
            fish_channel = message.channel.id
            while True:
                await message.channel.send('p!fish')
                await asyncio.sleep(62)
    elif message.author.bot and message.author.name == 'Pancake' \
            and message.author.discriminator == '3691' and message.channel.id == fish_channel:

        print(message.content)

        await asyncio.sleep(1)

        if 'Your fishing rod broke!' in message.content:
            await asyncio.sleep(3)
            await message.channel.send('p!buy fishing rod')
        elif 'purchase' in message.content or 'sell' in message.content:
            if message.reactions:
                await message.add_reaction(message.reactions[0])
        elif 'casted out a line...' in message.content:
            await message.channel.send('p!sell all')
            await asyncio.sleep(random.randint(80, 120))
            await message.channel.send('p!give olive 100')

bot.run(TOKEN)


class fpdutility():

    def __init__(self, fusion_api):
        self.api = fusion_api

    def get_defined_boot_stages(self):
        boot_stages = []
        for boot_stage in self.api.product_definition.BootStages:
            boot_stages.append(boot_stage.StageName.replace('Stage',''))
        return boot_stage

    def get_marionette_serial_port(self):
        for boot_stage in self.api.product_definition.BootStages:
            if hasattr(boot_stage,'MarionetteTransport'):
                if hasattr(boot_stage.MarionetteTransport,'ComPortNumber'):
                    print("Found serial marionette transport configured to Com Port {}".format(boot_stage.MarionetteTransport.ComPortNumber))
                    return boot_stage.MarionetteTransport.ComPortNumber
        print("Could not find a serial port configured boot stage")
        return 0

    def get_environment_limits(self, condition_name):
        print("Extracting limits for environment condition {}".format(condition_name))
        for environment in self.api.product_definition.EnvironmentalConditionDescriptors:
            if environment.name in condition_name and hasattr(environment,'Max'):
                return {"Max":environment.Max, "Min":environment.Min,"Step": environment.Step}
            elif environment.name in condition_name and hasattr(environment,'DiscreteValues'):
                return {"DiscreteValues": environment.DiscreteValues}


#coding=utf-8
'''

'''
import pickle  #数据持久性模块  意思就是数据直接写入磁盘中

# 示例
# 写入 列表list
myList = [1,2,3,4,5,"Linuxcao is a good man"]
path = r"E:\study\untitled\file6.txt"
f = open(path,"wb")
pickle.dump(myList,f)
f.close()

# 读取 列表list
f1 = open(path,"rb")
tempList = pickle.load(f1)
print(tempList)
f1.close()