"""
Tools for using Mutant Standard emoji from ppb games.

Constants:
* MORPHS: Valid morph values
* TONES: Valid tone values
* TONES_HMN, TONES_PAW, TONES_CLW: Valid tone values for specific morphs
* TONES_ALL: Valid tone values for all morphs
"""
import ppb
from ppb.flags import DoNotRender
import os
import functools
import pathlib

__all__ = 'MutantSprite', 'SelectScene',

# The BY-NC-SA license requires software display this notice. Let's just do it
# for them.
print(
    "\n"
    "This game uses Mutant Standard emoji (https://mutant.tech), which are "
    "licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 "
    "International License (https://creativecommons.org/licenses/by-nc-sa/4.0/)."
    "\n"
)

MORPHS = ['hmn', 'paw', 'clw']

TONES_ALL = [
    None,
    # Standard
    'r1', 'r2', 'r3', 'd1', 'd2', 'd3', 'o1', 'o2', 'o3', 'y1', 'y2', 'y3',
    'l1', 'l2', 'l3', 'g1', 'g2', 'g3', 't1', 't2', 't3', 'c1', 'c2', 'c3',
    's1', 's2', 's3', 'b1', 'b2', 'b3', 'v1', 'v2', 'v3', 'm1', 'm2', 'm3',
    'p1', 'p2', 'p3', 'e1', 'e2', 'e3', 'k1', 'k2', 'k3',
]

TONES_HMN = ['h1', 'h2', 'h3', 'h4', 'h5']
TONES_PAW = ['fk1', 'ft1', 'fe1']
TONES_CLW = []

TONES = TONES_ALL + TONES_HMN + TONES_PAW + TONES_CLW

ASSETS_ROOT = pathlib.Path(__file__).absolute().parent / '_assets'

@functools.lru_cache()
def load_index():
    """
    Loads the index file, yielding (shortcode, original path, alias)
    """
    fn = ASSETS_ROOT / 'index.txt'
    if not os.path.exists(fn):
        # Does not exist yet
        return
    with open(fn, 'rt') as indexfile:
        for line in indexfile:
            line = line.rstrip('\n')
            if not line:
                continue
            bits = line.split('\t')
            code, path, alias = bits
            yield code, path, alias or None

@functools.lru_cache()
def load_aliases():
    """
    Loads the aliases file, yielding (alias, expansion)
    """
    fn = ASSETS_ROOT / 'aliases.txt'
    if not os.path.exists(fn):
        # Does not exist yet
        return
    with open(fn, 'rt') as indexfile:
        for line in indexfile:
            line = line.strip()
            if not line:
                continue
            bits = line.split('\t')
            alias, expansion = bits
            yield alias, expansion

def is_valid_morph_tone(morph, tone):
    """
    Returns True if this is a valid morph, a valid tone, and they are valid
    together.
    """
    if morph not in MORPHS:
        return False
    if tone in TONES_ALL:
        return True
    if morph == 'hmn' and tone in TONES_HMN:
        return True
    if morph == 'paw' and tone in TONES_PAW:
        return True
    if morph == 'clw' and tone in TONES_CLW:
        return True

    # Fall through
    return False

class MutantSprite(ppb.BaseSprite):
    """
    Replaces a Sprite's image with emoji, which is pulled from the Mutant
    Standard emoji.

    Morph and tone customization can be used via {}-format.

    Attributes (can be set at the class level):
    * emoji: the emoji to render (or DoNotRender)
    * morph: the hand shape to use (hmn, paw, or clw)
    * tone: the tone to color with
    """
    morph = 'hmn'
    tone = None
    emoji = 'no_entry'

    _aliases = dict(load_aliases())

    resource_path = ASSETS_ROOT

    @property
    def image(self):
        # print(self.emoji, self.morph, self.tone)
        if self.emoji is DoNotRender:
            return DoNotRender
        else:
            shortcode = os.path.basename(self.emoji)  # Transitional
            resolved = self._aliases.get(shortcode, shortcode)
            resolved = resolved.format(morph=self.morph, tone=self.tone or '')
            resolved = resolved.rstrip('_')
            # print("\t", resolved)
            return '{}.png'.format(resolved)

def _frange(x, y, jump):
  while x <= y:
    yield x
    x += jump

class SelectScene(ppb.BaseScene):
    """
    A base scene to provide mutant hand/character customization.

    Subclass and override do_morphtone().

    * morph: The current morph
    * tone: The current color tone
    * do_morphtone(): Called whenever the morph or tone changes

    SelectScene.Sprite can be overriden to change the sprite.
    """
    _morph = None
    _tone = None

    class Sprite(MutantSprite):
        """
        The sprite to use in the menu
        """

    def __init__(self, *p, morph='hmn', tone=None, **kw):
        super().__init__(*p, **kw)

        self.main_camera.position = ppb.Vector(
            0,
            self.main_camera.half_height - 2,
        )

        for s in self._get_samples():
            self.add(s, tags=['sample'])

        for s in self._get_morphs():
            self.add(s, tags=['morph'])

        for s in self._get_tones():
            self.add(s, tags=['tone'])

        self.morph = morph
        self.tone = tone

        ymin = min(s.position.y - 0.5 for s in self)
        ymax = max(s.position.y + 0.5 for s in self)

    def build_sprite(self, emoji, morph=None, tone=None, **kwargs):
        """
        Instantiates the sprite, with the given emoji, morph, tone, and args.
        """
        sprite = self.Sprite(**kwargs)
        sprite.emoji = emoji
        if morph:
            sprite.morph = morph
        if tone:
            sprite.tone = tone
        return sprite

    def _get_samples(self):
        left = self.main_camera.frame_left
        yield self.build_sprite(emoji='hand', pos=(left + 0.5, -1.5))
        yield self.build_sprite(emoji='raising_hand', pos=(left + 1.5, -1.5))

    def _get_morphs(self):
        right = self.main_camera.frame_right
        yield self.build_sprite(emoji='hand', morph='clw', tone=None, pos=(right - 0.5, -1.5))
        yield self.build_sprite(emoji='hand', morph='hmn', tone=None, pos=(right - 1.5, -1.5))
        yield self.build_sprite(emoji='hand', morph='paw', tone=None, pos=(right - 2.5, -1.5))

    def _grid(self):
        cam = self.main_camera

        for y in _frange(1, int(cam.frame_height - 2) - 0.5, 1.0):
            for x in _frange(int(cam.frame_left) + 0.5, int(cam.frame_right) - 0.5, 1.0):
                yield x, y

    def _get_tones(self):
        left = self.main_camera.frame_left
        right = self.main_camera.frame_right

        # TONES_HMN
        yield self.build_sprite(emoji='hand_hmn_{tone}', tone='h1', pos=(left + 0.5, 0))
        yield self.build_sprite(emoji='hand_hmn_{tone}', tone='h2', pos=(left + 1.5, 0))
        yield self.build_sprite(emoji='hand_hmn_{tone}', tone='h3', pos=(left + 2.5, 0))
        yield self.build_sprite(emoji='hand_hmn_{tone}', tone='h4', pos=(left + 3.5, 0))
        yield self.build_sprite(emoji='hand_hmn_{tone}', tone='h5', pos=(left + 4.5, 0))

        # Default tone
        yield self.build_sprite(emoji='color_modifier', tone=None, pos=((left + 4.5 + right - 2.5) / 2, 0))

        # TONES_PAW
        yield self.build_sprite(emoji='hand_paw_{tone}', tone='fk1', pos=(right - 0.5, 0))
        yield self.build_sprite(emoji='hand_paw_{tone}', tone='ft1', pos=(right - 1.5, 0))
        yield self.build_sprite(emoji='hand_paw_{tone}', tone='fe1', pos=(right - 2.5, 0))

        # TONES_ALL
        tones = (t for t in TONES_ALL if t is not None)
        for tone, pos in zip(tones, self._grid()):
            yield self.build_sprite(emoji='color_modifier', tone=tone, pos=pos)

    @property
    def morph(self):
        return self._morph

    @morph.setter
    def morph(self, value):
        self._morph = value
        for s in self.get(tag='sample'):
            s.morph = value
        self.do_update_morphtone()

    @property
    def tone(self):
        return self._tone

    @tone.setter
    def tone(self, value):
        self._tone = value
        for s in self.get(tag='sample'):
            s.tone = value
        self.do_update_morphtone()

    def _check_collision(self, sprite, point):
        return (
            sprite.left <= point.x <= sprite.right
            and
            sprite.bottom >= point.y >= sprite.top
        )

    def on_button_pressed(self, mouse, signal):
        for sprite in self.get(tag='morph'):
            if self._check_collision(sprite, mouse.position):
                if not is_valid_morph_tone(sprite.morph, self.tone):
                    self.tone = None
                self.morph = sprite.morph
                return

        for sprite in self.get(tag='tone'):
            if self._check_collision(sprite, mouse.position):
                if not is_valid_morph_tone(self.morph, sprite.tone):
                    if sprite.tone in TONES_PAW:
                        self.morph = 'paw'
                    elif sprite.tone in TONES_HMN:
                        self.morph = 'hmn'
                    elif sprite.tone in TONES_CLW:
                        self.morph = 'clw'
                self.tone = sprite.tone
                return

    def do_update_morphtone(self):
        """
        Called whenever the morph or tone is updated. Override with your own class.
        """


import logging
import operator
import os
import sqlite3
from functools import wraps
from pathlib import Path

from scrapy.utils.url import url_is_from_any_domain

from ..datastructures import labeled_sequence
from ..sql.db import db
from ..sql.functions import register_all

log = logging.getLogger('exporter.utils')

def subdomain(x, y):
    return x == y or x[-(len(y) + 1):] == f'.{y}'

filter_ops = {
    'is': operator.eq,
    'under': subdomain,
    'startswith': str.startswith,
    'endswith': str.endswith,
    'contains': operator.contains,
    'gt': operator.gt,
    'ge': operator.ge,
    'lt': operator.lt,
    'le': operator.le,
}
sql_ops = {
    ('is', 'None'): ('"%(column)s" IS NULL', '%s'),
    ('is', 'True'): ('"%(column)s" == 1', '%s'),
    ('is', 'False'): ('"%(column)s" == 0', '%s'),
    'is': ('"%(column)s" == :%(id)d', '%s'),
    'under': ('subdomain("%(column)s", :%(id)d)', '%s'),
    'startswith': ('"%(column)s" LIKE :%(id)d', '%s%%'),
    'endswith': ('"%(column)s" LIKE :%(id)d', '%%%s'),
    'contains': ('"%(column)s" LIKE :%(id)d', '%%%s%%'),
    'gt': ('"%(column)s" > :%(id)d', '%s'),
    'ge': ('"%(column)s" >= :%(id)d', '%s'),
    'lt': ('"%(column)s" < :%(id)d', '%s'),
    'le': ('"%(column)s" <= :%(id)d', '%s'),
}
equivalencies = [('==', 'is'), ('in', 'contains'), ('>', 'gt'), ('<', 'lt'), ('>=', 'ge'), ('<=', 'le')]
for k, v in equivalencies:
    filter_ops[k] = filter_ops[v]
    sql_ops[k] = sql_ops[v]

def build_where_clause(includes=None, excludes=None):
    if not includes and not excludes:
        return '1', (), set()
    values = []
    includes = includes or []
    excludes = excludes or []
    clauses = []
    required_columns = set()
    for prefix, criteria in (('', includes), ('NOT ', excludes)):
        for key, op, val in criteria:
            required_columns.add(key)
            op = sql_ops.get((op, val), sql_ops[op])
            values.append(op[1] % (val,))
            value_id = len(values)
            clauses.append(prefix + op[0] % {'column': key, 'id': value_id})
    clauses = ' AND '.join(clauses)
    values = labeled_sequence(values, start=1, as_str=True)
    return clauses, values, required_columns

class MappingFilter:
    def __init__(self):
        self.filters = []

    def includes(self, key, op, val):
        self.filters.append(lambda row, x=key, y=val, op=filter_ops[op]: op(row[x], y))

    def excludes(self, key, op, val):
        self.filters.append(lambda row, x=key, y=val, op=filter_ops[op]: not op(row[x], y))

    def __call__(self, item):
        return all(f(item) for f in self.filters)

def with_db(exporter):
    @wraps(exporter)
    def e(wd, *args, **kwargs):
        wd = Path(wd)
        output = wd / 'out'
        os.makedirs(output, exist_ok=True)

        db_path = wd / 'index.db'
        if not db_path.exists():
            raise FileNotFoundError(f'index.db not found in {wd}')

        conn = sqlite3.connect(db_path, isolation_level=None)
        if db.is_locked(conn):
            log.error('Database was left in a partially consistent state.')
            log.error('Run `python -m feedme check-db` to fix it first.')
            return 1

        conn.row_factory = sqlite3.Row
        db.verify_version(conn)
        register_all(conn)

        try:
            exporter(conn, wd, output, *args, **kwargs)
        finally:
            conn.close()
    return e

def filter_by_domains(ls, exclude=False):
    domains = []
    for key, op, val in ls:
        if key != 'domain' or op != 'under':
            log.warning(f'Unknown filter {key} {op}')
            continue
        domains.append(val)
    return lambda u: url_is_from_any_domain(u, domains) ^ exclude


import requests

def send_request(test_data):
    return requests.post(
        "http://localhost:8080/order",
        json=test_data)

def test(test_data, desired_output):
    got_output = send_request(test_data).json()
    if desired_output in got_output:
        print("PASS! -- " + str(got_output) + "\n")
    else:
        print("FAIL! -- " + str(got_output) + "\n")

try:
    print("Test: correct input fields")
    correct_data = {
        "cart_value": 790,
        "delivery_distance": 2235,
        "number_of_items": 4,
        "time": "2021-10-12T13:00:00Z"
    }
    test(correct_data, "delivery_fee")

    print("Test: correct input fields with extra fields")
    correct_data_unused_fields = {
        "cart_value": 790,
        "delivery_distance": 2235,
        "number_of_items": 4,
        "time": "2021-10-12T13:00:00Z",
        "something": 53,
        "unrelevant": "stringtype"
    }
    test(correct_data_unused_fields, "delivery_fee")

    print("Test: necessary fields missing")
    data_point_missing = {
        "delivery_distance": 2235,
        "number_of_items": 4,
        "time": "2021-10-12T13:00:00Z"
    }
    test(data_point_missing, "missing from request")

    print("Test: int value type incorrect")
    value_type_incorrect = {
        "cart_value": "string",
        "delivery_distance": 2235,
        "number_of_items": 4,
        "time": "2021-10-12T13:00:00Z"
    }
    test(value_type_incorrect, "invalid literal for int() with base 10:")

    print("Test: string value type incorrect")
    value_type_incorrect = {
        "cart_value": 790,
        "delivery_distance": 2235,
        "number_of_items": 4,
        "time": {"something": 8, "another": 9}
    }
    test(value_type_incorrect, "Error in time: strptime() argument 1 must be str")

    print("Test: time in wrong format")
    time_in_wrong_format = {
        "cart_value": 790,
        "delivery_distance": 2235,
        "number_of_items": 4,
        "time": "2021:10:12T13-00-00Z"  # ":" replaced with "-" and vice versa
    }
    test(time_in_wrong_format,
         "does not match format '%Y-%m-%dT%H:%M:%S%z'")

except Exception as error:
    print(f"Error occurred: ", error)


from urllib import response
import helper
from flask import Flask,request,Response
import json

# Flask Application Name
app=Flask(__name__)

# Home Route to tell what our application is
@app.route('/')
def hello_world():
    return 'Welcome to ToDo App'

# creating a route to add a new item to the list
@app.route('/item/new',methods=['POST','GET'])
def add_item():
    item=request.args.get('item') # we are getting the details related to item
    #item=req_data['item'] # accessing item from json document
    res_data=helper.add_to_list(item) # adding to the list

    if res_data is None:
        response=Response("{'error': 'Item not added -'}"+item, status=400,mimetype='application/json')
        return response

    response=Response(json.dumps(res_data),mimetype='application/json')
    return response

# Creating a route to display all the items
@app.route('/items/all')
def get_all_items():
    res_data=helper.get_all_items()
    response=Response(json.dumps(res_data),mimetype='application/json')
    return response

# Create a route to get a particular item
@app.route('/item/status',methods=['GET','POST'])
def get_item():

    item_name=request.args.get('item')
    status=helper.get_item(item_name)

    if status is None:
        response=Response("{'error': 'Item Not Found - '}"+ item_name,status=404,mimetype='application/json')
        return response

    res_data={'status':status}
    response=Response(json.dumps(res_data),status=200,mimetype='application/json')
    return response

# Create a route to update the status
@app.route('/item/update',methods=['GET'])
def update_status():
    #req_data=request.args.get('item')
    item=request.args.get('item')
    status=request.args.get('status')

    res_data=helper.update_status(item,status)
    if res_data is None:
        response=Response("{'error': 'Error Updating Item - '"+item+","+status+"}",status=400,mimetype='application/json')
        return response

    response=Response(json.dumps(res_data),mimetype='application/json')
    return response

# Create a route to delete the item
@app.route('/item/remove',methods=['GET'])
def delete_item():
    item=request.args.get('item')

    res_Data=helper.delete_item(item)
    if res_Data is None:
        response=Response("{'error': 'Error Deleting Item -'"+item+"}",status=400,mimetype='application/json')
        return response

    response=Response(json.dumps(res_Data),mimetype='application/json')
    return response

if __name__=='__main__':
    app.run(host='0.0.0.0',port=5000,debug=True)


import logging
log = logging.getLogger(__name__)

import os.path

import pkg_resources

import samuraix

class PluginError(Exception):
    """
        raised by :meth:`PluginLoader.require_key` if a
        required plugin key couldn't be found.
    """
    pass

class PluginLoader(dict):
    """
        A class loading all available plugins using setuptools entrypoints.
        First, all paths in the 'core.plugin_paths' configuration option
        are checked and all found setuptools distributions are added to the
        working set. These distributions usually are Python eggs - so, it is
        very easy to remove a plugin - you can just remove the egg from the
        plugin path.
        The plugin loader object is a dictionary subclass. You can access
        plugins by their keys, for example:

        ::

            print self.app.plugins['desktops']

        However, there is usually just one :class:`PluginLoader` per
        samurai-x instance, and it's loaded by the application. Internally.
    """
    def __init__(self, app):
        """
            :type app: :class:`samuraix.appl.App`
        """
        self.app = app

    def setup(self):
        """
            add the available distributions to the pkg_resources working set
            and load all plugins. That is called internally by the application.
        """
        self.add_entries()
        self.load_all()

    def add_entries(self):
        """
            iterate the plugin paths (the 'core.plugin_paths' option)
            and add all found distributions to the working set.
        """
        for path in map(os.path.expanduser,
                samuraix.config.get('core.plugin_paths', [])):
            map(pkg_resources.working_set.add,
                    pkg_resources.find_distributions(path, False))

    def require_key(self, key):
        """
            Call this to check if there is a plugin providing with the
            key *key*. If there is none, an :class:`PluginError` is raised.
        """
        if not key in self:
            raise PluginError('You have to install a plugin '
                              'implementing the "%s" key!' % key)

    def load_all(self):
        """
            load all plugins, warn if a plugin couldn't be loaded.
        """
        # get the names of all required plugins
        names = samuraix.config.get('core.plugins', [])
        log.debug('loading %s', names)
        # get all available entrypoints and create a dictionary mapping
        # an entrypoint's name to an entrypoint.
        entrypoints = list(pkg_resources.iter_entry_points('samuraix.plugin'))
        dct = dict((ep.name, ep) for ep in entrypoints)

        for name in names:
            try:
                ep = dct[name]
            except KeyError:
                log.error("The plugin '%s' couldn't be found!" % name)
            else:
                log.info("Loading plugin '%s'...", name)
                cls = ep.load()
                self[cls.key] = cls(self.app)


# baekjoon s3 스택 수열
# https://www.acmicpc.net/problem/1874
# 스택
# 1. 1~n까지 push를 수행하며 수열 출력
# 2. n까지 모두 push한 후에 stack 요소를 모두 pop한 결과가 수열의 나머지 결과와 같은지 확인
from collections import deque

N = int(input())
num_list = []
result = []
for i in range(N):
    num_list.append(int(input()))
stack = deque()
index = 0
flag = True
for n in num_list:
    if index < n:
        while index < n:
            index += 1
            stack.appendleft(index)
            result.append('+')
        stack.popleft()
        result.append('-')
    elif index > n:
        if n == stack.popleft():
            result.append('-')
        else:
            flag = False
            print("NO")
            break
if flag:
    for r in result:
        print(r)


import gc
from copy import deepcopy
import cv2
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
import matplotlib
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from PIL import Image
from model import myUnet
import cv2
import glob
import data
import math

Train_DIR = "E:\\Experiment data\\data-for-detection\\Landsat\\Train\\"
Val_DIR = "E:\\Experiment data\\data-for-detection\\Landsat\\Val\\"
Test_DIR = "E:\\Experiment data\\data-for-detection\\Landsat\\Test\\"
Result_DIR = "E:\\Experiment data\\data-for-detection\\Landsat\\Test\\maskMSCN-2sec\\"

model = myUnet()
model.load(r"E:\project\MSCN-1\log\weight-2\1000_weights_2018-10-18-20-48-29.h5")

imgsname = glob.glob(Test_DIR + "masked\\*.tif")
imgdatas = np.ndarray((1, 512, 512, 3), dtype=np.float32)
mask1datas = np.ndarray((1, 512, 512, 3), dtype=np.float32)
temporaldatas = np.ndarray((1, 512, 512, 3), dtype=np.float32)
predictiondatas = np.ndarray((1, 512, 512, 3), dtype=np.float32)

def label_binary(labelimg):
    labelimg /= 255
    labelimg[labelimg > 0.3] = 1
    labelimg[labelimg <= 0.3] = 0
    return labelimg

num = 0
for imgname in imgsname:
    name = imgname[imgname.rindex("\\") + 1:]
    img = cv2.imread(Test_DIR + "masked\\" + name)
    mask1 = cv2.imread(Test_DIR + "maskMSCN\\" + name,  cv2.IMREAD_GRAYSCALE)
    prediction = cv2.imread(Test_DIR + "prediction\\" + name)
    temporal = cv2.imread(Test_DIR + "temporal\\" + name)

    img = img_to_array(img).astype('float32')
    mask1 = img_to_array(mask1).astype('float32')
    prediction = img_to_array(prediction).astype('float32')
    temporal = img_to_array(temporal).astype('float32')

    imgdatas[0] = img / 255
    predictiondatas[0] = prediction / 255
    temporaldatas[0] = temporal / 255
    mask1datas[0] = label_binary(mask1)
    # mask = model.predict(imgdatas)
    mask = model.predict([imgdatas, temporaldatas, predictiondatas, mask1datas])

    # mask_fin = mask[3][0]
    # mask_fin[mask_fin > 0.3] = 1
    # mask_fin[mask_fin <= 0.3] = 0

    mask = mask[0, :, :, :]
    mask[mask > 0.3] = 1
    mask[mask <= 0.3] = 0

    mask_img = array_to_img(mask)
    mask_img.save(Result_DIR + "\\%s" % name)

    num = num + 1
    if num % 100 == 0:
        print("%d输出完毕！" % num)

    print("输出完毕！")


# 綜合損益表資料讀取
#
# 讀取公開觀測資訊站
# => 財務報表 => 採IFRSs後 => 合併/個別報表 => 合併/個別報表 => 綜合損益表
#
# last_modify: 2016/10/18
#

#import
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()
driver.get("http://mops.twse.com.tw/mops/web/t163sb04")

#網頁查詢條件輸入，並提交表單
elem = driver.find_element_by_name("year")
elem.send_keys("103")
elem = driver.find_element_by_name("season")
elem.find_element_by_xpath("//select[@name='season']/option[text()='2']").click()
driver.find_element_by_xpath("//input[@type='button'][@value=' 查詢 ']").click()

cnt = 0
delay = 10 # seconds

while True:
	try:
	    element_present = EC.presence_of_element_located((By.NAME, 'fm2'))
	    WebDriverWait(driver, delay).until(element_present)
	    print ("Page is ready!")
	    break
	except TimeoutException:
	    cnt += 1
	    print ("Load cnt=" + str(cnt))
	    if cnt >= 3:
	    	break

#計算有多少個符合條件特徵的表格個數
tables = driver.find_elements_by_xpath("//table[@class='hasBorder']")
tb_cnt = len(tables)
print("符合條件特徵的table個數=" + str(tb_cnt))

#網頁中符合條件的table資料都掃過一遍
i = 1
tb_cnt = 1
while i <= tb_cnt:
	print("i=" + str(i))

	#組合搜尋條件參數
	arg_str = "//table[@class='hasBorder'][" + str(i) + "]/tbody"

	#讀取表格資料內容
	table = elem.find_element_by_xpath(arg_str)
	for row in table.find_elements_by_xpath(".//tr"):
		print([td.text for td in row.find_elements_by_xpath(".//td[text()]")])

	i += 1

print ("end of prog...")


'''
* 2nd challenge (to be updated!):
    - Max video label length: 18
    - The number of files (train): 3,888,919
    - The number of files (valid): 1,112,356

* 3rd challenge:
    - Max video label length: 14
    - Max video-segment label length: 4
    - Max segment label length: 15
    - The number of files (valid): 47,087 -> 38,786
    - The number of files (test): 44,753 -> 44,739
'''

import os
import numpy as np
import glob
import shutil
import torch

# data_types = ['train', 'valid', 'test']
# challenge = '2nd_challenge' / '3rd_challenge'

data_types = ['train']
challenge = '2nd_challenge'

data_dir = '/run/media/hoosiki/WareHouse1/mtb/datasets/VU/pytorch_datasets/'

max_vid_label_len = 0
max_vid_seg_label_len = 0
max_seg_label_len = 0
for data_type in data_types:
    frame_dir = data_dir + '{}/{}/'.format(challenge, data_type)
    bad_frame_dir = '/run/media/hoosiki/WareHouse2/mtb/datasets/bad_datasets/{}/'.format(challenge, data_type)
    os.makedirs(bad_frame_dir, exist_ok=True)
    file_paths = glob.glob(frame_dir + '*.pt')

    print('The number of files:', len(file_paths))
    for i, file_path in enumerate (file_paths):
        if i % 10000 == 0:
            print(data_type, i)
        try :
            data = torch.load(file_path)
            frame_len = len(data['frame_rgb'])
            vid_label_len = len(data['video_labels'])
            if (challenge == '2nd_challenge'):
                assert(data_type == 'train' or data_type == 'valid')
                if (frame_len <= 10 or vid_label_len == 0):
                    shutil.move(file_path, bad_frame_dir)
                else:
                    if max_vid_label_len < vid_label_len:
                        max_vid_label_len = vid_label_len
            else:
                vid_seg_label_len = len(data['video_segment_labels'])
                seg_label_len = len(data['segment_labels'])
                assert(data_type == 'valid' or data_type == 'test')
                if (data_type == 'valid'):
                    max_seg_start_times = 0 if vid_seg_label_len == 0 else max(data['segment_times'] * 5)
                    if (frame_len <= 10 or vid_seg_label_len == 0 or frame_len < max_seg_start_times):
                        shutil.move(file_path, bad_frame_dir)
                    else:
                        if max_vid_label_len < vid_label_len:
                            max_vid_label_len = vid_label_len
                        if max_vid_seg_label_len < vid_seg_label_len:
                            max_vid_seg_label_len = vid_seg_label_len
                        if max_seg_label_len < seg_label_len:
                            max_seg_label_len = seg_label_len
                else:
                    if (frame_len <= 10):
                        shutil.move(file_path, bad_frame_dir)
        except:
            shutil.move(file_path, bad_frame_dir)

print("Max video label length:", max_vid_label_len)
print("Max video-segment label length:", max_vid_seg_label_len)
print("Max segment label length:", max_seg_label_len)
print("Done!")


###fxns to time and log

##imports
import pandas as pd
import numpy as np
import os
import time

def begin_session(path_to_csv,baseline,mean_fxn,var_fxn):
    if (os.path.isfile(path_to_csv)):
        history_df=pd.read_csv(path_to_csv)
        nr=history_df.shape[0]
    else:
        nr=0

    mu = mean_fxn(nr)
    sigma = var_fxn(nr,baseline)

    #sample from dist
    mins = baseline + max(-baseline+1,np.random.normal(mu,sigma))

    #Session
    os.system("say Begin Practice")
    print(mins)
    time.sleep(60*mins)
    os.system("say End Practice")

    #record stages
    stage = input("Which stage of meditation did you enter during this practice at its acme?")
    date = input("What is the date?")

    newrow = {"Date": [date], "Stage": [stage], "Duration": [mins]}
    if (nr==0):
        history_df = newrow
    else:
        history_df = history_df.append(newrow)

    pd.write_csv(history_df,path_to_csv)
    return

if __name__ == "__main__":
    path_to_csv = "~/documents/github/stoch-vipassana/data/session_record.csv"
    baseline=10
    def mean_fxn(x): return .5*x
    def var_fxn(x,y): return .33*(x+y)
    begin_session(path_to_csv,baseline,mean_fxn,var_fxn)


import random
import sys
import select
import tty
import termios

DECENDING = 0
ASCENDING = 1

def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
old_settings = termios.tcgetattr(sys.stdin)

def bubbleSortOptimized():
    return

def swap(x,y):
    # return y,x
    '''
       This is a test description
    '''
    x,y = y,x
    return x,y

def printList(a):
    for i,val in enumerate(a):
        print(str(i) + " " + str(val))
    print(dict.fromkeys(a))
    print(dict(enumerate(a)))

def reverseString(x):
    # return x[-1:-(len(x)+1):-1]
    return x[::-1]

def matrixMultiplication():
    print("This is matrixMultiplication ")

def binarySearchTree():
    print("This is Binary Search Tree")

def primeGenerator():
    print("This is primeGenerator ")
    print ("using list comprehension generate prime upto 100, using user input and output")

def bubbleSort(unsortedList,order):
    # order = 0 indicates assending, order = 1 indicates descending
    arraySize = len(unsortedList)
    print("arraySize " + str(arraySize) + "\n Unsorted List " + str(unsortedList))
    numberOfLoops = 0
    sorted = False
    for i in range(0,arraySize-1):
        if sorted:
            break
        else:
            sorted = True
        numberOfLoops = numberOfLoops + 1
        for j in range(0, arraySize-1-i):
            if (order == DECENDING):
                if (unsortedList[j] > unsortedList [j+1]):
                    temp = unsortedList [j+1]
                    unsortedList [j+1] = unsortedList[j]
                    unsortedList[j] = temp
                    sorted = False
            else:
                if (order == ASCENDING):
                    if (unsortedList[j] < unsortedList [j+1]):
                        temp = unsortedList [j+1]
                        unsortedList [j+1] = unsortedList[j]
                        unsortedList[j] = temp
                        sorted = False
    print("Sorted List " + str(unsortedList) + "\nnumberOfLoops = " + str(numberOfLoops))
    return unsortedList

def bubbleSortAutoTest():
    printString = "Not Sorted: Order =  {} \n {}"
    print("This is bubble sort")
    sorted = True
    numberOfElements = 100
    sortedList = []
    unsortedList = []
    for i in range(numberOfElements):
        # unsortedList.append(i)
        unsortedList.append(random.randint(0,999))
    order = DECENDING
    # order = ASCENDING
    sortedList = bubbleSort(unsortedList,order)
    if (order == ASCENDING):
        for i in range(numberOfElements-1):
            if sortedList[i] < sortedList[i+1]:
                print(printString.format(order, sortedList))
                sorted = False
                break
    else:
        for i in range(numberOfElements-1):
            if sortedList[i] > sortedList[i+1]:
                print(printString.format(order, sortedList))
                sorted = False
                break
    if sorted:
        print("List is sorted\n")

def binarySearch(sortedList, startIndex, endIndex, searchValue):
    print("Function Binary Search")
    printNotFound = "SerachValue {} not found"
    printFound = "SerachValue {} not found"
    printFound = "Found SearchValue {} at index {}"
    printStartEnd = "Start {} end {}"
    start = startIndex
    end = endIndex
    searchIndex = -1
    for i in range(start, end, 1):
        if start > end:
            # print("SerachValue " + str(searchValue) + "not found")
            print(printNotFound.format(searchValue))
            print(printStartEnd.format(start, end))
            # print("Start " + str(start) + "end" + str(end))
            exit()
        mid = (start + end)/2
        mid = int(mid)
        # print("Start " + str(start) + " end " + str(end) + "mid " + str(mid))
        if sortedList[mid] == searchValue:
            searchIndex = mid
            break
        elif sortedList[mid] < searchValue:
            start = mid + 1
        else:
            end = mid - 1
        print(printStartEnd.format(start, end))
        # print("Start " + str(start) + " end " + str(end))
    if searchIndex > -1:
        print(printStartEnd.format(start, end))
        # print("Start " + str(start) + "end" + str(end))
        print(printFound.format(searchValue,searchIndex))
        # print("Found SearchValue" + str(searchValue) + "at index" + str(searchIndex))
    else:
        # print("Start " + str(start) + "end" + str(end))
        print(printNotFound.format(searchValue))
        # print("SearchValue " + str(searchValue) + "not found")

def binarySearchAutoTest():
    print("BinarySearchProgramTest started")
    startVal = 1
    endVal = 100000
    sortedList = [1 * x for x in range (startVal,endVal+1)]
    startIndex = 0
    endIndex = endVal-1
    try:
        tty.setcbreak(sys.stdin.fileno())

        for x in range(startVal, endVal):
            # serachValue = 200
            # binarySearch(sortedList, startIndex, endIndex, serachValue)
            binarySearch(sortedList, startIndex, endIndex, x)

            if isData():
                c = sys.stdin.read(1)
                if c == '\x1b':         # x1b is ESC
                    break
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class llist:
    def __init__(self):
        self.next = None

    def push(self, data):
        newNode = Node(data)
        newNode.next = self.next
        self.next = newNode

    def printList(self):
        tempNode = self.next
        while (tempNode):
            print(tempNode.data)
            tempNode = tempNode.next
        print("Print over")

    def reverseList(self):
        Prev = None
        Curr = self.next
        while (Curr):
            Next = Curr.next
            Curr.next = Prev
            Prev = Curr
            Curr = Next
        self.next = Prev

print("Python Learning Started")

mylist = llist()
mylist.push(10)
mylist.push(20)
mylist.push(30)
mylist.push(40)
mylist.printList()
mylist.reverseList()
mylist.printList()

def binarySearchAutoTest():
# print(swap(8,9))
# printList(["a", "b", "hello",123])
# exit()
# binarySearchAutoTest()
# bubbleSortAutoTest()
# print(reverseString("eraH eraH amaR amaR amaR eraH amaR eraH \n eraH eraH anhsirK anhsirK anhsirK eraH anhsirK eraH"))
    exit()


class Emprestimo:
    def __init__(self, casa, salario, anos):
        self.casa = casa
        self.salario = salario
        self.anos = anos
        self.prestacao = casa / (anos * 12)
        self.minimo = salario * 30 / 100

    def validar_emprestimo(self):
        if self.prestacao <= self.minimo:
            print("Emprestimo concedido")
        else:
            print("Emprestimo não aprovado")

casa = float(input("Qual o valor da casa? R$"))
salario = float(input("Qual seu salario? R$"))
anos_a_pagar = int(input("Em quantos anos quer pagar? "))

prestacao = casa / (anos_a_pagar * 12)
minimo = salario * 30 / 100

emprestimo = Emprestimo(casa, salario, anos_a_pagar)
emprestimo.validar_emprestimo()

print("Para pagar a casa de R${:.2f} em {} anos".format(
    emprestimo.casa, emprestimo.anos))
print("o valor será de R${:.2f}".format(emprestimo.prestacao))


""" test scripts for app.epitopes.py """
import pytest
from app.epitope import Epitope
from app.common.utilities import flatten2set
import sys
print(sys.path)

@pytest.mark.parametrize('test_input, expected_output',
[
    ({'3C':'A*12:01', '25I':'A*12:01'}, {'A*12:01': set(['3C', '25I'])}),

])
def test_epvshla2hlavsep(test_input, expected_output):
    assert Epitope().epvshla2hlavsep(test_input) == expected_output

def test_min_hlavsep():
    epitopes = set(['105S', '113HN', '114H', '114Q', '116L', '131S', '144QL',
                    '44RME', '62EE', '62QE', '63NI', '65QIA', '66IS', '66IY',
                    '66NH', '70IAQ', '71TD', '74Y', '77D','99S', '9H'])
    epitope = Epitope()
    _min_hlavsep = epitope.min_hlavsep(epitopes)
    # print(epitope.path)
    print(_min_hlavsep)
    assert flatten2set(_min_hlavsep.values()).intersection(epitopes) == epitopes

test_min_hlavsep()


#Tic tac toe game helper script - v0.1
#Author: Fernando A. C. de Barros - ECA - UERGS
#This project is available on: https://github.com/fecaletti/mean-old-woman

import colorama

_EMPTY = " "
_X = "X"
_O = "O"

def check_cross_right(specValues):
    return (specValues[0].value == specValues[4].value) and (specValues[4].value == specValues[8].value) and (specValues[0].value != _EMPTY)

def check_cross_left(specValues):
    return (specValues[2].value == specValues[4].value) and (specValues[4].value == specValues[6].value) and (specValues[2].value != _EMPTY)

def check_row(specValues, offset = 0):
    return (specValues[offset].value == specValues[offset + 1].value == specValues[offset + 2].value) and (specValues[offset].value != _EMPTY)

def check_column(specValues, offset = 0):
    return (specValues[offset].value == specValues[offset + 3].value == specValues[offset + 6].value) and (specValues[offset].value != _EMPTY)

def is_valid_position(position):
    return position >= 0 and position < 9

def moveCursor(x, y):
    print("\033[%d;%dH" % (y, x), end="")

def draw_board(positions):
    print("   |   |   ")
    print(f" {positions[0].value} | {positions[1].value} | {positions[2].value} ")
    print("-----------")
    print(f" {positions[3].value} | {positions[4].value} | {positions[5].value} ")
    print("-----------")
    print(f" {positions[6].value} | {positions[7].value} | {positions[8].value} ")
    print("   |   |   ")

def draw_board_on_position(positions, startX, startY):
    moveCursor(startX, startY)
    print("   |   |   ")
    moveCursor(startX, startY + 1)
    print(f" {positions[0].value} | {positions[1].value} | {positions[2].value} ")
    moveCursor(startX, startY + 2)
    print("-----------")
    moveCursor(startX, startY + 3)
    print(f" {positions[3].value} | {positions[4].value} | {positions[5].value} ")
    moveCursor(startX, startY + 4)
    print("-----------")
    moveCursor(startX, startY + 5)
    print(f" {positions[6].value} | {positions[7].value} | {positions[8].value} ")
    moveCursor(startX, startY + 6)
    print("   |   |   ")

def receive_command(values, lastMove):
    cmd = input("Enter your move [Position,Character]: ")
    [pos, char] = cmd.split(",")
    convPos = int(pos)

    if(not is_valid_position(convPos)):
        print("Invalid position received!")
        return

    if(values[convPos] != _EMPTY):
        return

    if((lastMove != None) and (char.upper() == lastMove)):
        return

    values[convPos] = _X if char.upper() == _X else _O if char.upper() == _O else _EMPTY
    lastMove = values[convPos]

class GameEndException(Exception):
    pass

colorama.init()


import pandas as pd
from click_davisinteractive import evaluation
import glob

def read_my_csv(file_path):
    return pd.read_csv(file_path, index_col=0)

MAX_INTERACTIONS   = 8
MAX_TIME           = 30       # Official --> 8*30
SUBSET             = 'val'      #'train', 'val'
METRIC_TO_OPTIMIZE = 'J_AND_F'  #'J', 'F' or 'J_AND_F'
davis_path = '../DAVIS/2017'

path_2_csv_files = sorted(glob.glob('./csv_results/*.csv'))

for csv_file in path_2_csv_files:
    csv_table = read_my_csv(csv_file)

    Eval_report = evaluation.service.EvaluationService(davis_root=davis_path+'/trainval',
                                                       subset= SUBSET,
                                                       max_t = MAX_INTERACTIONS*MAX_TIME if MAX_TIME is not None else None,
                                                       max_i = MAX_INTERACTIONS,
                                                       metric_to_optimize=METRIC_TO_OPTIMIZE)

    output = Eval_report.summarize_report_vujas(csv_table, round_results = 2, use_time_axis=False)
    print(output)


import heapq
import bisect
N = int(input())
a = list(map(int, input().split()))

b = a[:N]
c = a[-N:]
L = [0]*(N+1)
R = [0]*(N+1)

L[0] = sum(b)

heapq.heapify(b)

R[-1] = sum(c)
c = list(map(lambda x: -x, c))
heapq.heapify(c)

for i in range(N):
    k = a[i+N]
    x = heapq.heappop(b)
    if x < k:
        L[i+1] = L[i] + k - x
        heapq.heappush(b, k)
    else:
        L[i+1] = L[i]
        heapq.heappush(b, x)

for i in range(N-1, -1, -1):
    k = a[i+N]
    x = heapq.heappop(c)
    if -x > k:
        heapq.heappush(c, -k)
        R[i] = R[i+1] + x + k
    else:
        R[i] = R[i+1]
        heapq.heappush(c, x)
ans = -10**14
for i in range(N+1):
    ans = max(ans, L[i]-R[i])
#print(L, R)
print(ans)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/2/27 上午11:44
# @Author  : simon
# @File    : bloomfilter

import math
import mmh3
from bitarray import bitarray

class BloomFilter(object):
    def __init__(self, item_count, fp_prob):
        self.fp_prob = fp_prob
        self.size = self._get_size(item_count, fp_prob)
        self.hash_count = self._get_hash_count(self.size, item_count)
        self.bit_array = bitarray(self.size)
        self.bit_array.setall(0)

    def add(self, data):
        for i in range(self.hash_count):
            digest = mmh3.hash(data, i) % self.size
            self.bit_array[digest] = True

    def check(self, data):
        for i in range(self.hash_count):
            digest = mmh3.hash(data, i) % self.size
            if not self.bit_array[digest]:
                return False
        return True

    @staticmethod
    def _get_size(n, p):
        """
        m = -(n * lg(p)) / (lg(2)^2)
        :param n:
        :param p:
        :return:
        """
        m = -(n * math.log(p)) / (math.log(2) ** 2)
        return int(m)

    @staticmethod
    def _get_hash_count(m, n):
        """
        k = (m/n) * lg(2)
        :param m:
        :param n:
        :return:
        """
        k = (m / n) * math.log(2)
        return int(k)


temp = []
princ = []
mai = men = 0

while True:
    temp.append(str(input('Nome: ')))
    temp.append(float(input('Peso: ')))
    if len(princ) == 0:
        mai = men = temp[1]
    else:
        if temp[1] > mai:
            mai = temp[1]
        if temp[1] < men:
            men = temp[1]

    princ.append(temp[:]) # Para copiar uma lista ou inserir uma na outra precisa-se usar assim: lista(:) sem os dois pontos não copia
    temp.clear()

    resp = str(input('Você quer continuar? [S/N] '))
    if resp in 'Nn':
        break

print("+-++-+"*10)
print(f'- Os dados foram {princ}')
print(f'- Ao todo, você cadastrou {len(princ)} pessoas.')
print(f'- O maior pesso foi de {mai}Kg. Peso de', end='')
for p in princ:
    if p[1] == mai:
        print(f' {p[0]}')
print(f'- O menor peso foi de {men}Kg. Peso de', end='')
for p in princ:
    if p[1] == men:
        print(f' {p[0]}', end='')
print("\n+-++-+"*10)

Curso de Python e outros/Exercicios Python Mundo 2 e 3/exercicios-estruturas-de-dados/2 - listas/ex07.py


import patientController, mysql.connector
from PyQt5 import QtCore, QtGui, QtWidgets
from mysql.connector import Error

class Ui_Dialog(object):
    def __init__(self):
        self.Dialog = QtWidgets.QDialog()
        self.Dialog.setObjectName("Dialog")
        self.Dialog.resize(457, 601)
        self.searchPID = QtWidgets.QLineEdit(self.Dialog)
        self.searchPID.setGeometry(QtCore.QRect(170, 30, 161, 22))
        self.searchPID.setObjectName("searchPID")
        self.label = QtWidgets.QLabel(self.Dialog)
        self.label.setGeometry(QtCore.QRect(60, 30, 121, 20))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.Dialog)
        self.label_2.setGeometry(QtCore.QRect(120, 90, 41, 20))
        self.label_2.setObjectName("label_2")
        self.female = QtWidgets.QRadioButton(self.Dialog)
        self.female.setGeometry(QtCore.QRect(290, 180, 95, 20))
        self.female.setObjectName("female")
        self.buttonGroup_2 = QtWidgets.QButtonGroup(self.Dialog)
        self.buttonGroup_2.setObjectName("buttonGroup_2")
        self.buttonGroup_2.addButton(self.female)
        self.nid = QtWidgets.QLineEdit(self.Dialog)
        self.nid.setGeometry(QtCore.QRect(170, 130, 171, 22))
        self.nid.setObjectName("nid")
        self.male = QtWidgets.QRadioButton(self.Dialog)
        self.male.setGeometry(QtCore.QRect(180, 180, 95, 20))
        self.male.setObjectName("male")
        self.buttonGroup_2.addButton(self.male)
        self.label_3 = QtWidgets.QLabel(self.Dialog)
        self.label_3.setGeometry(QtCore.QRect(90, 130, 81, 20))
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.Dialog)
        self.label_4.setGeometry(QtCore.QRect(110, 180, 51, 20))
        self.label_4.setObjectName("label_4")
        self.name = QtWidgets.QLineEdit(self.Dialog)
        self.name.setGeometry(QtCore.QRect(170, 90, 171, 22))
        self.name.setObjectName("name")
        self.edit = QtWidgets.QPushButton(self.Dialog)
        self.edit.setGeometry(QtCore.QRect(120, 550, 93, 28))
        self.edit.setObjectName("edit")
        self.cancel = QtWidgets.QPushButton(self.Dialog)
        self.cancel.setGeometry(QtCore.QRect(270, 550, 93, 28))
        self.cancel.setObjectName("cancel")
        self.label_10 = QtWidgets.QLabel(self.Dialog)
        self.label_10.setGeometry(QtCore.QRect(110, 240, 51, 20))
        self.label_10.setObjectName("label_10")
        self.unknownStatus = QtWidgets.QRadioButton(self.Dialog)
        self.unknownStatus.setGeometry(QtCore.QRect(180, 240, 81, 20))
        self.unknownStatus.setObjectName("unknownStatus")
        self.buttonGroup = QtWidgets.QButtonGroup(self.Dialog)
        self.buttonGroup.setObjectName("buttonGroup")
        self.buttonGroup.addButton(self.unknownStatus)
        self.dischargedStatus = QtWidgets.QRadioButton(self.Dialog)
        self.dischargedStatus.setGeometry(QtCore.QRect(290, 240, 95, 20))
        self.dischargedStatus.setObjectName("dischargedStatus")
        self.buttonGroup.addButton(self.dischargedStatus)
        self.admittedStatus = QtWidgets.QRadioButton(self.Dialog)
        self.admittedStatus.setGeometry(QtCore.QRect(180, 290, 81, 20))
        self.admittedStatus.setObjectName("admittedStatus")
        self.buttonGroup.addButton(self.admittedStatus)
        self.deceasedStatus = QtWidgets.QRadioButton(self.Dialog)
        self.deceasedStatus.setGeometry(QtCore.QRect(290, 290, 95, 20))
        self.deceasedStatus.setObjectName("deceasedStatus")
        self.buttonGroup.addButton(self.deceasedStatus)
        self.label_8 = QtWidgets.QLabel(self.Dialog)
        self.label_8.setGeometry(QtCore.QRect(103, 400, 61, 20))
        self.label_8.setObjectName("label_8")
        self.phone = QtWidgets.QLineEdit(self.Dialog)
        self.phone.setGeometry(QtCore.QRect(173, 440, 171, 22))
        self.phone.setObjectName("phone")
        self.label_7 = QtWidgets.QLabel(self.Dialog)
        self.label_7.setGeometry(QtCore.QRect(113, 440, 51, 20))
        self.label_7.setObjectName("label_7")
        self.allergic = QtWidgets.QLineEdit(self.Dialog)
        self.allergic.setGeometry(QtCore.QRect(173, 400, 171, 22))
        self.allergic.setObjectName("allergic")
        self.label_9 = QtWidgets.QLabel(self.Dialog)
        self.label_9.setGeometry(QtCore.QRect(217, 370, 61, 20))
        self.label_9.setObjectName("label_9")
        self.line = QtWidgets.QFrame(self.Dialog)
        self.line.setGeometry(QtCore.QRect(80, 380, 351, 20))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.medhistory = QtWidgets.QLineEdit(self.Dialog)
        self.medhistory.setGeometry(QtCore.QRect(170, 480, 171, 22))
        self.medhistory.setObjectName("medhistory")
        self.label_11 = QtWidgets.QLabel(self.Dialog)
        self.label_11.setGeometry(QtCore.QRect(60, 480, 101, 20))
        self.label_11.setObjectName("label_11")
        self.line_2 = QtWidgets.QFrame(self.Dialog)
        self.line_2.setGeometry(QtCore.QRect(60, 60, 351, 20))
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.fillButton = QtWidgets.QPushButton(self.Dialog)
        self.fillButton.setGeometry(QtCore.QRect(350, 30, 93, 28))
        self.fillButton.setObjectName("fillButton")

        self.retranslateUi(self.Dialog)
        QtCore.QMetaObject.connectSlotsByName(self.Dialog)

        self.edit.clicked.connect(self.editing)
        self.cancel.clicked.connect(self.back)
        self.fillButton.clicked.connect(self.fill)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Edit by Patient ID :"))
        self.label_2.setText(_translate("Dialog", "Name :"))
        self.female.setText(_translate("Dialog", "Female"))
        self.male.setText(_translate("Dialog", "Male"))
        self.label_3.setText(_translate("Dialog", "Personal ID :"))
        self.label_4.setText(_translate("Dialog", "Gender :"))
        self.edit.setText(_translate("Dialog", "Edit"))
        self.cancel.setText(_translate("Dialog", "Cancel"))
        self.label_10.setText(_translate("Dialog", "Status :"))
        self.unknownStatus.setText(_translate("Dialog", "Unknown"))
        self.dischargedStatus.setText(_translate("Dialog", "Discharged"))
        self.admittedStatus.setText(_translate("Dialog", "Admitted"))
        self.deceasedStatus.setText(_translate("Dialog", "Deceased"))
        self.label_8.setText(_translate("Dialog", "Allergic :"))
        self.label_7.setText(_translate("Dialog", "Phone :"))
        self.label_9.setText(_translate("Dialog", "Multivalue"))
        self.label_11.setText(_translate("Dialog", "Medical History :"))
        self.fillButton.setText(_translate("Dialog", "Fill"))

    def show(self):
        self.Dialog.show()

    def back(self):
        self.ui = patientController.Ui_Dialog()
        self.Dialog.hide()
        self.ui.show()

    def editing(self):
        patientID = self.searchPID.text()
        #TODO edit

    def fill(self):
        patientID = self.searchPID.text()
        #TODO fill data

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = Ui_Dialog()
    ui.show()
    sys.exit(app.exec_())


listaNumerosFlotantes = []
cantidadNumerosLista = int(input("¿De cuantos números quieres tu lista? "))
numeroMayor = float('-inf')
numeroMenor = float('inf')
sumaTotal = 0
promedio = 0

for _ in range(cantidadNumerosLista):
    numeroFlotante = float(input("Introduce tu número: "))
    listaNumerosFlotantes.append(numeroFlotante)

print(f"Tu lista es: {listaNumerosFlotantes}")

for numero in listaNumerosFlotantes:
    if numero > numeroMayor: numeroMayor = numero
    if numero < numeroMenor:numeroMenor = numero

print(f"""
El menor de tus números es: {numeroMenor}
El mayor de tus núemros es: {numeroMayor}
""")

for numero in listaNumerosFlotantes:
    sumaTotal += numero

promedio = sumaTotal/ len(listaNumerosFlotantes)

print(f"El promedio de tu lista {listaNumerosFlotantes} es: {promedio}")


import tweepy
import pdb
import random
import json

f = open('keys.json', 'r')
keys = json.load(f)

consumer_key = keys["consumer_key"]
consumer_secret = keys["consumer_secret"]
access_token = keys["access_token"]
access_token_secret = keys["access_token_secret"]

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

target = "@nekoneko_full"
status = api.user_timeline(target)
tweet_ids = status.ids()
num = random.randint(0, len(tweet_ids) - 1)
tweet_status = api.get_status(tweet_ids[num])
api.update_status(tweet_status.text)


from .common import *

DEBUG = True

ALLOWED_HOSTS = []

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

        'TEST': {
            'NAME': 'test.sqlite3',
            'MIRROR': 'default'
        },
    },
}

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'


import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
# 0.04mbar run, Scroll pump
file_dir = "C:\\Users\\Christian\\Documents\\StudiumPhD\\Measurements\\"
# file = file_dir + '2021-06-07_wire_3_post_300C_bakeout_fill.csv'
# data_frame = pd.read_csv(file)

# df = data_frame[6:64]

file = file_dir + '2021-05-10_test_vac_0.04_mbar_fill.csv'
data_frame = pd.read_csv(file)

df_bakeout = data_frame[119:164]
df_bakeout = data_frame[119:164]
#print(df_bakeout)

def make_datetime(data_frame):
    data_frame["date_time"] = [dt.datetime(1,1,1) for i in range(len(data_frame))]
    for index, row in data_frame.iterrows():
        date_list = data_frame["Date"][index].split("-")
        time_list = data_frame["Time"][index].split(":")
        date_time =dt.datetime(year = int(date_list[2]),
                               month = int(date_list[1]),
                               day = int(date_list[0]),
                               hour = int(time_list[0]),
                               minute = int(time_list[1])   )
        #print(date_time)
        data_frame["date_time"][index] = date_time

make_datetime(df_bakeout)
#print(df_bakeout)
# for i  in range(119,163):
#     a = df_bakeout["date_time"][i] - df_bakeout["date_time"][119]
#     print(a)
#     b = a.total_seconds()/60
#     print(b)
#     #print(b)
import matplotlib as mpl
font = {#'family' : 'normal','weight' : 'bold',
        'size'   : 16
        #,'serif':['Helvetica']
        }
mpl.rc('font', **font)

t_delta_list = [(df_bakeout["date_time"][i] - df_bakeout["date_time"][119]
                ).total_seconds()/60
                for i in range(119,164)]
print(t_delta_list)
fig = plt.figure(0, figsize=(8,6.5))
ax1=plt.gca()
ax1.errorbar(t_delta_list, df_bakeout["I meas (mA)"], df_bakeout["err I"],
             marker = ".", linestyle="None")
ax1.set_ylabel(r"I [mA]")
ax1.set_xlabel(r"t [min]")
plt.grid(True)
#plt.legend(shadow=True)

format_im = 'png' #'pdf' or png
dpi = 300
plt.savefig("bakeout_i_over_t"
            + '.{}'.format(format_im),
            format=format_im, dpi=dpi)
ax1.cla()

fig = plt.figure(0, figsize=(8,6.5))
ax1=plt.gca()
ax1.plot(t_delta_list, df_bakeout["T (°C)"],
             marker = ".", linestyle="None")
ax1.set_ylabel(r"T [°C]")
ax1.set_xlabel(r"t [min]")
plt.grid(True)
#plt.legend(shadow=True)

format_im = 'png' #'pdf' or png
dpi = 300
plt.savefig("bakeout_T_over_t"
            + '.{}'.format(format_im),
            format=format_im, dpi=dpi)
ax1.cla()

#stability after backkeout
df_after = data_frame[164:167]

make_datetime(df_after)

t_delta_list = [(df_after["date_time"][i] - df_after["date_time"][164]
                ).total_seconds()/60
                for i in range(164,166)]
print(t_delta_list)
fig = plt.figure(0, figsize=(8,6.5))
ax1=plt.gca()
ax1.errorbar(t_delta_list, df_after["I meas (mA)"], yerr = df_after["err I"],
             marker = ".", linestyle="None")
ax1.set_ylabel(r"I [mA]")
ax1.set_xlabel(r"t [min]")
plt.grid(True)
#plt.legend(shadow=True)

format_im = 'png' #'pdf' or png
dpi = 300
plt.savefig("test_after"
            + '.{}'.format(format_im),
            format=format_im, dpi=dpi)
ax1.cla()


from collections import deque
import sys

dr = (1, -1, 0, 0)
dc = (0, 0, 1, -1)

N, M = map(int, sys.stdin.readline().split())
matrix = [list(map(int, list(sys.stdin.readline().rstrip()))) for _ in range(N)]
visited = [[0]*M for _ in range(N)]  # 0: 방문안함, 1: 안 깬 상태로 방문됨, 2: 하나 깬 상태로 방문됨

q = deque([(0, 0, 1, True)])  # row, col, cnt, breakable
visited[0][0] = 1
result = -1

while (q):
    row, col, cnt, breakable = q.popleft()
    if ((row, col) == (N-1, M-1)):
        result = cnt
        break

    for i in range(4):
        n_row = row + dr[i]
        n_col = col + dc[i]

        # matrix 범위 안에 있으면서
        if (0 <= n_row < N and 0 <= n_col < M):
            # 아직 방문하지 않았거나 아직 벽을 깰 수 있는데 과거에 벽을 깬 상태로만 방문했을 경우
            if (not visited[n_row][n_col] or (breakable and visited[n_row][n_col] == 2)):
                # 빈 공간이면 그냥 큐에 추가
                if (matrix[n_row][n_col] == 0):
                    visited[n_row][n_col] = 1 if breakable else 2
                    q.append((n_row, n_col, cnt+1, breakable))
                # 벽이라면, breakable 여부를 확인하고, 가능한 경우에만 큐에 추가
                elif (matrix[n_row][n_col] == 1 and breakable):
                    visited[n_row][n_col] = 2
                    q.append((n_row, n_col, cnt+1, False))

print(result)


SECRET_KEY = 'aaa'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:'
    }
}

INSTALLED_APPS = (
    'django.contrib.contenttypes', 'django.contrib.sessions',
    'django.contrib.messages', 'django.contrib.staticfiles',
    'hvad', 'taggit',
    ### Bangoo core modules
    'bangoo.core', 'bangoo.admin', 'bangoo.content', 'bangoo.navigation', 'bangoo.theming', 'bangoo.media',
    ### Bangoo plugins
    'bangoo.blog',
    'tests',
)

MIDDLEWARE_CLASSES = ()

AUTH_USER_MODEL = 'core.User'


# Queries NPI Registry using their API and saves the results in an Excel File with provider information formatted and organized by use case. This program flattens the JSON data structure so that each nested value is represented as a separate column in the table.
#
# There will be one sheet with one row of Provider Information per unique provider. This list is intended to aid a user in visualizing and tracking providers to try calling.
#
# There will be one sheet with one row of Provider Information per unique provider+taxonomy combination. This is intended to allow a user to filter by the particular taxonomy they are looking for, e.g. "Counselor, Addiction (Substance Use Disorder)" and find all providers with that specialty.

# Import required libraries
import requests
import pandas as pd

# Import search criteria
search_df = pd.read_csv("input.csv")
search_df

# Create a DataFrame with only the search criteria
search_df2 = search_df.dropna(axis=1)
search_df2

# Convert the DataFrame to a dictionary
first_row_dict = search_df.to_dict()
print(first_row_dict)

#Convert the used search terms to a dictionary
searchTerms = {}

col_index = 0

while col_index < len(search_df2.columns):
    # get the name of the current column
    col_name = search_df2.columns[col_index]

    # get the value of the first row in the current column
    value = search_df2[col_name][0]

    # assign the value of the first row to a variable with the same name as the column
    searchTerms[col_name] = value

    # increment the column index counter
    col_index += 1

# print the resulting dictionary of variables
print(searchTerms)

# Use the search terms to append the api URL
searchTerms_input = {}

col_index = 0

npi_url_base = "https://npiregistry.cms.hhs.gov/api/?version=2.1&use_first_name_alias=True&pretty=TRUE&enumeration_type=NPI-1&limit=100"
npi_url = npi_url_base

while col_index < len(search_df2.columns):
    # get the name of the current column
    col_name = search_df2.columns[col_index]

    # get the value of the first row in the current column
    value = search_df2[col_name][0]

    # create the search term suffix
    term = "&"+col_name+"="+value
    print(term)

    npi_url = npi_url + term

    # increment the column index counter
    col_index += 1

print(npi_url)

# Open the csv with all the appropriate taxonomies. Used to filter only for mental health providers

taxonomies = pd.read_csv("NPI_Taxonomies.csv", usecols=['Taxonomies'])
taxonomies = taxonomies[taxonomies.columns[0]].values.tolist()
taxonomies = [x for x in taxonomies if not(pd.isnull(x)) == True]
print(taxonomies)

# Create a dictionary of URLs with one version per Taxonomy, to perform multiple API calls (since you cannot search for multiple taxonomies at once)

v = 1 # URL version number
url_versions = {} # empty dictionary to store different versions of the URLs based on taxonomy
for t in taxonomies:
    # create the search term suffix
    term = "&taxonomy_description="+t

    # create the URL
    url = npi_url+term

    # save the URL as a new dictionary item
    url_versions[v] = url

    # increase the counter
    v+= 1

    print(url)

print(url_versions)

# Search NPI registry and store results
i = 1
addresses_df = pd.DataFrame()
basic_info_df = pd.DataFrame()
taxonomies_df = pd.DataFrame()
result_df = pd.DataFrame()

for url_version in url_versions.values():
    # get the requests from the URL
    response = requests.get(url_version)

    # If there are no results for that taxonomy, it will make a successful request but with an error in the result.
    # Simply skip this search term
    if "Errors" in response.json():
        print("Version",i,": No Results")

    # Otherwise, response status code 200 means it has succeeded; will only continue if the API call is successful
    elif response.status_code == 200:
        print("Version",i,": Success")
        # convert addresses of result to DF
        addresses_df1 = pd.json_normalize(
            response.json()["results"],
            record_path=['addresses'], # Looks in the address path of the json
            meta=['number'], # Uses the NPI number column as metadata for each record
            errors='ignore') # Avoid raising a key error if key isn't present
        addresses_df = pd.concat([addresses_df, addresses_df1], ignore_index=True)
        #basic_info_df = pd.json_normalize(response.json()["basic"], errors='ignore')
        basic_info_df1 = pd.json_normalize(
            response.json(),['results'], # Looks in the basic_info path of the json
            errors='ignore')
        basic_info_df = pd.concat([basic_info_df, basic_info_df1], ignore_index=True)
        taxonomies_df1 = pd.json_normalize(
            response.json()["results"],
            record_path=['taxonomies'],
            meta=['number'], # Uses the NPI number column as metadata for each record
            errors='ignore')
        taxonomies_df = pd.concat([taxonomies_df, taxonomies_df1], ignore_index=True)
    # Otherwise, print the error code for troublelshooting
    else:
        print("Version",i,"Error: API request returned status code ",response.status_code)
    # increase the counter
    i+= 1

# Merge all of the DataFrames created in the API search above
result_df = addresses_df.merge(basic_info_df, on='number')
result_df = result_df.merge(taxonomies_df, on='number')
result_df

#Rename columns for easier readability

result_df.rename(columns={"number":"NPI_Number",
                          "basic.first_name": "First_Name",
                          "basic.last_name": "Last_Name",
                          "basic.middle_name": "Middle_Name",
                          "basic.gender": "Gender",
                          "basic.credential": "Credential",
                          "basic.sole_proprietor": "Sole_Proprietor",
                          "telephone_number": "Phone_Number",
                          "desc": "Taxonomy",
                          "state_x":"State",
                          "enumeration_type": "Enumeration_Type",
                          "city":"City",
                          "postal_code":"Zip"
                         }, inplace=True)
result_df.head()

# Select columns to keep (instead of drop, in case NPI adds columns later)
result_df = result_df[['NPI_Number','Enumeration_Type','address_purpose','City', 'State', 'Zip',
       'Phone_Number','First_Name', 'Last_Name', 'Middle_Name', 'Credential',
       'Sole_Proprietor', 'Gender','basic.status','Taxonomy']]
result_df.head()

# Clean the DataFrame
    #Keep only Mailing address lines, to remove duplicate entries and keep only Active NPIs. Remove columns no longer needed like status.
result_df_mail = result_df.loc[result_df['address_purpose'] == 'MAILING']
result_df_status = result_df_mail.loc[result_df_mail['basic.status'] == 'A']
result_df_2 = result_df_status.drop(columns=['Enumeration_Type', 'address_purpose','basic.status'])
result_df_2.head()

# Create dummy variables from the "Taxonomy" column
result_df_taxonomy_search = pd.get_dummies(result_df_2, columns=['Taxonomy'], prefix="Taxonomy")
result_df_taxonomy_search.head()

# Remove Duplicates (and the taxonomy column) to get a list of unique providers
result_df_unique = result_df_2.drop_duplicates(subset="NPI_Number", keep='first', inplace=False, ignore_index=False)
result_df_unique = result_df_unique.dropna(subset=['Phone_Number'])
result_df_unique

# Save the results to an Excel file with one sheet per DataFrame above.
with pd.ExcelWriter('NPI_Provider_Info.xlsx') as writer:
    result_df_unique.to_excel(writer, sheet_name='Unique_Provider_List')
    result_df_taxonomy_search.to_excel(writer, sheet_name='Providers_by_Taxonomy')


# Recebe duas listas e retorna uma lista com os elementos intercalados

def uniao(xs, ys):
    lista = []
    for x in xs:
        lista.append(x)
    for y in ys:
        if y not in lista:
            lista.append(y)
    return lista

def intercal(xs, ys):
    lista = [*sum(zip(xs,ys),())]
    tam = len(xs) + len(ys)
    if len(lista) < tam:
        if len(xs) > len(ys):
            lista = uniao(lista, xs)
        elif len(xs) < len(ys):
            lista = uniao(lista, ys)
    return lista

print(intercal([1,2,3], [7,8,9]) == [1,7,2,8,3,9]) #True
print(intercal([1,2,3,4], [8,9]) == [1,8,2,9,3,4]) #True
print(intercal([5], [1,2,6]) == [5,1,2,6]) #True


import os
import pandas as pd

from DataConstants import DataConstants

def dataCombine(data_dir, selectedStations, eTag):
    # This program is used to merge the single files data downloaded from the Internet
    list = ['date', 'hour', 'type']
    dataColumns = []
    for l in selectedStations:
        l1 = list + l
        dataColumns.append(l1)

    dc = DataConstants(eTag)
    cities, indicator, stations = dc.getPublicData()

    i = 0
    for city in cities:
        df=[]
        for file in os.listdir(data_dir):
            data  = pd.read_csv(data_dir+file)
            df_temp = data.loc[data['type'] == indicator]
            df2_temp = df_temp[dataColumns[i]]
            df.append(df2_temp)

        result = pd.concat(df)
        result.to_csv('data/'+eTag+'/'+city+'-'+indicator+'-raw.csv',index=0)
        i = i + 1


from configparser import ConfigParser
import copy
import flask
import pytest
import re
from pytest_mock import MockerFixture
import time

# Rewrites the path so the app can be imported like it normally is
import os
import sys

topdir = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(topdir)

os.environ['TESTING'] = "True"

from app import app, global_data
from webapp import models, topology, vos_data
from webapp.common import load_yaml_file
import stashcache

GRID_MAPPING_REGEX = re.compile(r'^"(/[^"]*CN=[^"]+")\s+([0-9a-f]{8}[.]0)$')
# ^^ the DN starts with a slash and will at least have a CN in it.
EMPTY_LINE_REGEX = re.compile(r'^\s*(#|$)')  # Empty or comment-only lines
I2_TEST_CACHE = "osg-sunnyvale-stashcache.nrp.internet2.edu"
# ^^ one of the Internet2 caches; these serve both public and LIGO data
# fake origins in our test data:
TEST_ITB_HELM_ORIGIN = "helm-origin.osgdev.test.io"
TEST_SC_ORIGIN = "sc-origin.test.wisc.edu"

# Some DNs I can use for testing and the hashes they map to.
# All of these were generated with osg-ca-generator on alma8
#   openssl x509 -in /etc/grid-security/hostcert.pem -noout -subject -nameopt compat
# I got the hashes from a previous run of the test.
MOCK_DNS_AND_HASHES = {
    "/DC=org/DC=opensciencegrid/C=US/O=OSG Software/OU=Services/CN=testhost1": "f7d78bab.0",
    "/DC=org/DC=opensciencegrid/C=US/O=OSG Software/OU=Services/CN=testhost2": "941f0a37.0",
    "/DC=org/DC=opensciencegrid/C=US/O=OSG Software/OU=Services/CN=testhost3": "77934f6c.0",
    "/DC=org/DC=opensciencegrid/C=US/O=OSG Software/OU=Services/CN=testhost4": "def5b9bc.0",
    "/DC=org/DC=opensciencegrid/C=US/O=OSG Software/OU=Services/CN=testhost5": "83a7951b.0",
}

MOCK_DN_LIST = list(MOCK_DNS_AND_HASHES.keys())

def get_test_global_data(global_data: models.GlobalData) -> models.GlobalData:
    """Get a copy of the global data with some entries created for testing"""
    new_global_data = copy.deepcopy(global_data)

    # Start with a fully populated set of topology data
    topo = new_global_data.get_topology()
    assert isinstance(topo, topology.Topology), "Unable to get Topology data"

    # Add our testing RG
    testrg = load_yaml_file(topdir + "/tests/data/testrg.yaml")
    topo.add_rg("University of Wisconsin", "CHTC", "testrg", testrg)

    # Put it back into global_data2 and make sure it doesn't get overwritten by future calls
    new_global_data.topology.data = topo
    new_global_data.topology.next_update = time.time() + 999999

    # Start with a fully populated set of VO data
    vos = new_global_data.get_vos_data()
    assert isinstance(vos, vos_data.VOsData), "Unable to get VO data"

    # Load our testing VO
    testvo = load_yaml_file(topdir + "/tests/data/testvo.yaml")
    vos.add_vo("testvo", testvo)

    # Put it back into global_data2 and make sure it doesn't get overwritten by future calls
    new_global_data.vos_data.data = vos
    new_global_data.vos_data.next_update = time.time() + 999999

    return new_global_data

@pytest.fixture
def client():
    with app.test_client() as client:
        yield client

class TestStashcache:

    def test_allowedVO_includes_ANY_for_ligo_inclusion(self, client: flask.Flask, mocker: MockerFixture):
        spy = mocker.spy(global_data, "get_ligo_dn_list")

        stashcache.generate_cache_authfile(global_data, "osg-sunnyvale-stashcache.nrp.internet2.edu")

        assert spy.call_count == 5

    def test_allowedVO_includes_LIGO_for_ligo_inclusion(self, client: flask.Flask, mocker: MockerFixture):
        spy = mocker.spy(global_data, "get_ligo_dn_list")

        stashcache.generate_cache_authfile(global_data, "stashcache.gwave.ics.psu.edu")

        assert spy.call_count == 5

    def test_allowedVO_excludes_LIGO_and_ANY_for_ligo_inclusion(self, client: flask.Flask, mocker: MockerFixture):
        spy = mocker.spy(global_data, "get_ligo_dn_list")

        stashcache.generate_cache_authfile(global_data, "rds-cache.sdsc.edu")

        assert spy.call_count == 0

    def test_scitokens_issuer_sections(self, client: flask.Flask):
        test_global_data = get_test_global_data(global_data)
        origin_scitokens_conf = stashcache.generate_origin_scitokens(
            test_global_data, TEST_ITB_HELM_ORIGIN)
        assert origin_scitokens_conf.strip(), "Generated scitokens.conf empty"

        cp = ConfigParser()
        cp.read_string(origin_scitokens_conf, "origin_scitokens.conf")

        try:
            assert "Global" in cp, "Missing Global section"
            assert "Issuer https://test.wisc.edu" in cp, \
                "Issuer missing"
            assert "Issuer https://test.wisc.edu/issuer2" in cp, \
                "Issuer 2 missing"
            assert "base_path" in cp["Issuer https://test.wisc.edu/issuer2"], \
                "Issuer 2 base_path missing"
            assert cp["Issuer https://test.wisc.edu/issuer2"]["base_path"] == "/testvo/issuer2test", \
                "Issuer 2 has wrong base path"
        except AssertionError:
            print(f"Generated origin scitokens.conf text:\n{origin_scitokens_conf}\n", file=sys.stderr)
            raise

    def test_scitokens_issuer_public_read_auth_write_namespaces_info(self, client: flask.Flask):
        test_global_data = get_test_global_data(global_data)

        namespaces_json = stashcache.get_namespaces_info(test_global_data)
        namespaces = namespaces_json["namespaces"]
        testvo_PUBLIC_namespace_list = [
            ns for ns in namespaces if ns.get("path") == "/testvo/PUBLIC"
        ]
        assert testvo_PUBLIC_namespace_list, "/testvo/PUBLIC namespace not found"
        ns = testvo_PUBLIC_namespace_list[0]
        assert ns["usetokenonread"] is False, \
            "usetokenonread is wrong for public namespace"
        assert ns["readhttps"] is False, \
            "readhttps is wrong for public namespace"
        assert ns["writebackhost"] == f"https://{TEST_SC_ORIGIN}:1095", \
            "writebackhost is wrong for namespace with auth write"

    def test_scitokens_issuer_public_read_auth_write_scitokens_conf(self, client: flask.Flask):
        test_global_data = get_test_global_data(global_data)

        origin_scitokens_conf = stashcache.generate_origin_scitokens(
            test_global_data, TEST_SC_ORIGIN)
        assert origin_scitokens_conf.strip(), "Generated scitokens.conf empty"

        cp = ConfigParser()
        cp.read_string(origin_scitokens_conf, "origin_scitokens.conf")
        try:
            assert "Global" in cp, "Missing Global section"
            assert "Issuer https://test.wisc.edu" in cp, \
                "Expected issuer missing"
            assert "base_path" in cp["Issuer https://test.wisc.edu"], \
                "'Issuer https://test.wisc.edu' section missing expected attribute"
            assert cp["Issuer https://test.wisc.edu"]["base_path"] == "/testvo", \
                "'Issuer https://test.wisc.edu' section has wrong base path"
        except AssertionError:
            print(f"Generated origin scitokens.conf text:\n{origin_scitokens_conf}\n", file=sys.stderr)
            raise

    def test_None_fdqn_isnt_error(self, client: flask.Flask):
        stashcache.generate_cache_authfile(global_data, None)

    def test_origin_grid_mapfile_nohost(self, client: flask.Flask):
        text = stashcache.generate_origin_grid_mapfile(global_data, "", suppress_errors=False)
        for line in text.split("\n"):
            assert EMPTY_LINE_REGEX.match(line), f'Unexpected text "{line}".\nFull text:\n{text}\n'

    def test_origin_grid_mapfile_with_host(self, client: flask.Flask):
        text = stashcache.generate_origin_grid_mapfile(global_data, "origin-auth2001.chtc.wisc.edu",
                                                       suppress_errors=False)
        num_mappings = 0
        for line in text.split("\n"):
            if EMPTY_LINE_REGEX.match(line):
                continue
            elif GRID_MAPPING_REGEX.match(line):
                num_mappings += 1
            else:
                assert False, f'Unexpected text "{line}".\nFull text:\n{text}\n'
        assert num_mappings > 5, f"Too few mappings found.\nFull text:\n{text}\n"

    def test_cache_grid_mapfile_nohost(self, client: flask.Flask):
        text = stashcache.generate_cache_grid_mapfile(global_data, "", legacy=False, suppress_errors=False)

        for line in text.split("\n"):
            if EMPTY_LINE_REGEX.match(line):
                continue
            mm = GRID_MAPPING_REGEX.match(line)
            if mm:
                dn = mm.group(1)
                if "CN=Brian Paul Bockelman" in dn or "CN=Matyas Selmeci A148276" in dn or "CN=Judith Lorraine Stephen" in dn:
                    # HACK: these three have their FQANs explicitly allowed in some namespaces so it's OK
                    # for them to show up in grid-mapfiles even without an FQDN
                    continue
                else:
                    assert False, f'Unexpected text "{line}".\nFull text:\n{text}\n'
            else:
                assert False, f'Unexpected text "{line}".\nFull text:\n{text}\n'

    def test_cache_grid_mapfile_i2_cache(self, client: flask.Flask, mocker: MockerFixture):
        mocker.patch.object(global_data, "get_ligo_dn_list", return_value=MOCK_DN_LIST, autospec=True)
        text = stashcache.generate_cache_grid_mapfile(global_data,
                                                      I2_TEST_CACHE,
                                                      legacy=True,
                                                      suppress_errors=False)
        num_mappings = 0
        for line in text.split("\n"):
            if EMPTY_LINE_REGEX.match(line):
                continue
            elif GRID_MAPPING_REGEX.match(line):
                num_mappings += 1
            else:
                assert False, f'Unexpected text "{line}".\nFull text:\n{text}\n'
        assert num_mappings > 5, f"Too few mappings found.\nFull text:\n{text}\n"

if __name__ == '__main__':
    pytest.main()


from PyQt5.QtWidgets import (
    QWidget, QFormLayout,
    QLabel, QLineEdit, QComboBox, QPushButton, QButtonGroup
)
from PyQt5.QtCore import Qt

class LayoutEditorForm(QWidget):
    '''
    Parametrs defining part
    '''
    def __init__(self, display) -> None:
        super().__init__()

        self.display = display

        self.initUI()

    def initUI(self):
        '''
        Creating form view
        '''
        # Defining layout
        self.layout = QFormLayout()
        self.setLayout(self.layout)

        # adding content
        layer_search = QLineEdit()
        self.layout.addRow(layer_search)
        layer_search.textChanged[str].connect(self.update_layer_btns_list)

        self.btns = {}
        self.btn_grp = QButtonGroup()
        self.btn_grp.buttonClicked[int].connect(self.layer_selected)
        id = 0
        for layer in self.display.get_layers():
            btn = QPushButton(layer)
            self.btn_grp.addButton(btn, id)
            id += 1
            self.btns[layer] = btn
            self.layout.addRow(btn)
            pass

    def update_layer_btns_list(self, text):
        ''''''
        for btn_name in self.btns.keys():
            if btn_name.startswith(text):
                self.btns[btn_name].show()
            else:
                self.btns[btn_name].hide()

    def layer_selected(self, text):
        ''''''
        for btn in self.btn_grp.buttons():
            if btn is self.btn_grp.button(text):
                self.display.set_draw_layer(btn.text())
        pass

    def updateDisplayView(self):
        ''''''
        print('clicked', self.w_inp.text())
        txt = self.w_inp.text()
        try:
            w = int(txt)
            self.display.r.setWidth(w)
            self.display.update()
        except:
            print(txt, 'not num')
            for atr in dir(Qt):
                if atr.endswith(txt):
                    print(atr)
            print('*'*50)


from typing import List

class Solution:
    #Two Pointer
    #Runtime: 200 ms, faster than 11.67% of Python3 online submissions for Container With Most Water.
    #Memory Usage: 15.2 MB, less than 89.53% of Python3 online submissions for Container With Most Water.
    def maxArea(self, height: List[int]) -> int:
        maxArea, l, r = 0, 0, len(height)-1
        while l < r:
            maxArea = max(min(height[l], height[r]) * (r-l), maxArea )
            if height[l] < height[r]:
                l+=1
            else:
                r -=1
        return maxArea

#n^2 Time limit exceeded
class Solution2:
    def maxArea(self, height: List[int]) -> int:
        maxArea = 0
        for i in range(len(height)):
            for j in range(len(height)):
                dist = abs(j - i)
                area = min(height[i], height[j]) * dist
                maxArea = max(maxArea, area)
        return maxArea

s = Solution()
#49
print(s.maxArea([1,8,6,2,5,4,8,3,7]))


"""
Task 3

Задайте последовательность чисел. Напишите программу,
которая выведет список неповторяющихся элементов исходной последовательности.

"""

def sing_num_list(i):
    result = list(set(i[:]))

    return f'Уникальные значения {result}\nCписка: {i}'

number_list = [1, 5, 3, 5, 8, 7, 6, 4, 6, 12, 20, 3]

print(sing_num_list(number_list))


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
        secondmin = float("inf")
        stack = [root]
        while stack:
            node = stack.pop()
            # If node.val> secondmin, then so do child nodes.
            if node.val < secondmin and node.left:
                stack.append(node.left)
                stack.append(node.right)
            if root.val < node.val < secondmin:
                secondmin = node.val
        return secondmin if secondmin != float("inf") else -1


# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import os
import sys

def extract_from_csv(csv_file):
    fp = open(csv_file, 'r')
    print('opened', csv_file)
    nh = []
    acc = []
    for line in fp:
        line = line.strip().split(',')
        nh.append(int(line[0]))
        acc.append(float(line[1]))
    return nh, acc

def plot_accuracy(csv_files, out_name):
    fig, ax1 = plt.subplots()
    ax1.set_xlabel('Number of human decisions')
    ax1.set_ylabel('Number of correct clusters')

    # combined_pairs = []
    for fn in csv_files:
        nh, acc = extract_from_csv(fn)
        _, tail = os.path.split(fn)
        prefix = tail.split('.')[0]
        ax1.plot(nh, acc, label=prefix)
    ax1.legend()

    if out_name is None:
        plt.show()
    else:
        plt.savefig(out_name)
        print('Saved plot to %s' % out_name)
        plt.close()

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('Usage: %s out_name csv1 [csv2 .... csvn]' % sys.argv[0])
        sys.exit()

    plot_accuracy(sys.argv[2:], sys.argv[1])


from __future__ import print_function, division

from keras.layers import Activation, Dropout
from keras.layers import Dense, Reshape, Flatten, MaxPooling2D, Embedding, BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.models import Sequential, Model

from neural_networks.nn_implementations.keras_TextNNBase import TextNN_Keras

class TextCNN_Keras(TextNN_Keras):

    def __init__(self, settings: dict):
        super().__init__(settings)

    def build(self):
        model = Sequential()
        model.add(
            Embedding(input_dim=self.vocab_size, output_dim=self.settings["embedding_dim"],
                      input_shape=(self.sequence_length,)))
        model.add(Reshape((self.sequence_length, self.settings["embedding_dim"], 1)))
        for i in range(self.settings["convolution_layers"]):
            model.add(Conv2D(self.settings["num_filters"], 4))
            model.add(Dropout(self.settings["dropout_keep_prob"]))
            model.add(Activation(activation="relu"))
            if self.settings["use_bn"]:
                model.add(BatchNormalization())
        if self.settings["use_max_pooling"]:
            model.add(MaxPooling2D())
        model.add(Flatten())
        model.add(Dense(self.num_classes, activation="softmax"))

        model.summary()

        result = model(self.input_x)

        return Model(self.input_x, result)


#!/usr/bin/env python

import RS485Ext
from pymodbus.client.sync import ModbusSerialClient
from influxdb import InfluxDBClient
from datetime import datetime, time
import time
from threading import Thread

client = ModbusSerialClient(method='rtu', port='/dev/ttyUSB0', stopbits = 1, bytesize = 8, parity = 'N' , baudrate= 9600)
client.connect()
rr = client.read_holding_registers(0, unit=32)
rr = client.read_holding_registers(10, unit=32)
print ("Reading 10 value " + str(rr.registers[0]))

print ("Load modbus map")
modmap_file = "s100-map"
modmap = __import__(modmap_file)
flux_client = InfluxDBClient('nick.lan', 8086, 'grafana', 'grafana', 'metrics', ssl=False, verify_ssl=False)

def publish_influx(inverter):
  metrics = {}
  tags = {}
  metrics['measurement'] = "S100"
  tags['location'] = "Home"
  metrics['tags'] = tags
  metrics['fields'] = inverter
  flux_client.write_points([metrics])
  print ("Sent to InfluxDB")

while True:
  print ("Waiting")
  time.sleep(15)
  inverter = {}
  client = ModbusSerialClient(method='rtu', port='/dev/ttyUSB0', stopbits = 1, bytesize = 8, parity = 'N' , baudrate= 9600)
  client.connect()
  for addr in modmap.read_register:
    rr = client.read_holding_registers(int(addr), unit=32)

    if ("Exception" not in str(rr)) and ("Error" not in str(rr) and ("ModbusIOException" not in str(rr))):
      inverter[str(addr)] = rr.registers[0]
    else:
      print(str(rr))
    print ("Reading "+ addr + " value " + str(rr.registers[0]))

  if flux_client is not None:
    t = Thread(target=publish_influx, args=(inverter,))
    t.start()
  print ("----------------------------------------------------------")


# coding: utf-8

# In[277]:

import pandas as pd
import matplotlib.pyplot as plt
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')

# In[248]:

#Edward J Smith - The captain goes doen with the ship
#we are trying to predict whether a passanger would survive using the train test
#then test it on the testing set

# In[280]:

test.head()
X = train
train.head() #feature matrix

# In[281]:

X.isnull().sum().astype(float) /X.shape[0]#check feature matrix for nas
#I have nas so I need to either fill them in with sume value or remove them from the dataset
X = X.drop(['Cabin'], axis = 1)#because there is so much missing data from cabin just remove it

# In[282]:

X['Embarked'].value_counts() #only 2 values from embarked are missing, options are S,C or Q so can just use S, most common
X['Embarked'] = X['Embarked'].fillna('S') #so can just replace with the most common value which is S

# In[283]:

import matplotlib.pyplot as plt
X.isnull().sum().astype(float) /X.shape[0] #only column with nas now is Age
 #get distribution of Age
X['Age'].hist()
X['Age'].mean() #one option is to fill in the nas with the mean (29)
X['Age'].median() #(28) so data is slightly skewed to the right

# In[284]:

#compare age versus pclass too see how age an pclass fit together
import seaborn as sns
for pclass in X['Pclass'].unique(): #for every unique pclass
    sns.kdeplot(X[X['Pclass'] == pclass]['Age'], label = pclass)#groupy pclass and density plot for age
    #we see a trend of the older the person the higher the class (1 = highest)

# In[285]:

#so to replace missing age nas values we might group by pclass and assign mean age for each class
X.groupby('Pclass')['Age'].mean()

for pclass in X['Pclass'].unique(): #for every unique pclass, locate the age column value, match to groupe by Pclass means
    X.loc[(X['Pclass'] == pclass) & (X['Age'].isnull()),'Age'] = X.groupby('Pclass')['Age'].mean().loc[pclass]

# In[287]:

X.isnull().sum() # wehave finally got rid of all the missing data
#X.head() #all age values are now means grouped by Pclass
#now we can assess which variables are important when considering passenger survival.
# [Feature Engineering and transformations]

# In[157]:

#visual on survival and Pclass to determine if Pclass is a good predictor
plt.figure(figsize= [16,8])
plt.subplot(121)
plt.hist(train[X['Survived'] == 0]['Pclass'])
plt.title("Perished")
plt.xlabel("Ticket Class")
plt.subplot(122)
plt.hist(train[X['Survived'] == 1]['Pclass'])
plt.title("Survived")
plt.xlabel("Ticket Class")

# In[158]:

#to get better understanding you might want the mean as well
X.groupby('Pclass')['Survived'].mean()
#so this is obviously going to be a pretty good predictor features of who would survive, PClass

# In[145]:

#visual on Age and Pclass to determine if Pclass is a good predictor
#turns out Age is not a great predictor of survival, although there is the spike for infants among survivors
#versus perished so knowing whether or not they are an infant would be helpful
print (X.groupby('Survived')['Age'].mean())
plt.figure(figsize= [8,4])
plt.subplot(121)
plt.hist(train[X['Survived'] == 0]['Age'])
plt.title("Perished")
plt.xlabel("Age of Passenger")
plt.subplot(122)
plt.hist(train[X['Survived'] == 1]['Age'])
plt.title("Survived")
plt.xlabel("Age of Passenger")

# In[129]:

#create an infant variable to use as a predictor
#an idea to try later, distribution if age older than 10 for survivor and perish groups looks quite similar
X['Infant'] = X['Age'] < 10
X.head()

# In[288]:

# How to do consider string data and categorical data
#you could make categorical data numeric, e.g Sex could be 1,0 or Embarked could be 1,2,3 but numerical data could interpret
# embarked 3 being much more different to 1 than it is from 2, the ML estimator will interpret these that way
#as feature matrix only can have numerical values for scikit learn then they must be changed

X['Sex'].replace({'male': 0, 'female':1}, inplace = True) #create dictionary to replace sex data

# In[289]:

#Ticket data appears random and not useful for any predictions so remove it
X.drop(['Ticket'], axis = 1, inplace = True)

# In[303]:

#consider embarked feature with one hot encoding
#this means that instead of having 1 embarked column we would have 3
X['Embarked_S'] = 0
X['Embarked_C'] = 0
X['Embarked_Q'] = 0
X.loc[X['Embarked'] == 'S', 'Embarked_S'] = 1
X.loc[X['Embarked'] == 'C', 'Embarked_C'] = 1
X.loc[X['Embarked'] == 'Q', 'Embarked_Q'] = 1
X.drop(['Embarked'], axis = 1, inplace = True)

# In[291]:

#Now to consider the name column
#Mrs,ms,Masters etc...is it a predictor versus Mr
#take name feature, split on , and get 1st value, split again on . and get 0th value, then get all unique values
X['Name'].str.split(',').apply(lambda x: x[1]).str.split('.').apply(lambda x: x[0]).unique()
#an idea for later to see if it is a good predictor when having a royal title etc

#for now
X.drop(['Name'], axis = 1, inplace = True)

# In[292]:

X.drop(['PassengerId'], axis = 1, inplace = True) #dont need passengerid as it is random
#so not a good predictor

# In[304]:

#y = X.pop('Survived') #this is my target label data
X.head() #is my feature matrix
#y.head()

# In[293]:

#building the model
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression

# In[305]:

model = Pipeline([
    ('scaler', StandardScaler()),
    ('logreg', LogisticRegression()),
    ])

#gridsearch for feature engineering, look at hyper-parameters of Logistic Regression
gs = GridSearchCV(
    model,
    {'logreg__penalty':['l1','l2'],
    'logreg__C':[0.01, 0.1, 1, 10, 100]},
    cv = 5,
    n_jobs = 4
)

# In[306]:

gs.fit(X,y)

# In[307]:

gs.best_params_ #tells us which hyper-paramters performed best
#so I can go back and just enter these parameters into the hyper parameters under logistic regression model(penalty = etc)

# In[308]:

test.head()

# In[309]:

#now need to do the same data munging to our test data (target label data)
test = test.drop(['Cabin'], axis = 1)#because there is so much missing data from cabin just remove it
test.drop(['Name'], axis = 1, inplace = True)
test.drop(['Ticket'], axis = 1, inplace = True)
passengertestID = test.pop('PassengerId') #pop passenger ID to add bacl into test df later, for predict probabilitys
#need the shape of test and train data to be the same

# In[310]:

test['Embarked'] = test['Embarked'].fillna('S')
for pclass in test['Pclass'].unique(): #for evertest unique pclass, locate the age column value, match to groupe btest Pclass means
    test.loc[(test['Pclass'] == pclass) & (test['Age'].isnull()),'Age'] = test.groupby('Pclass')['Age'].mean().loc[pclass]
test['Sex'].replace({'male': 0, 'female':1}, inplace = True) #create dictionartest to replace setest data

test['Embarked_S'] = 0
test['Embarked_C'] = 0
test['Embarked_Q'] = 0
test.loc[test['Embarked'] == 'S', 'Embarked_S'] = 1
test.loc[test['Embarked'] == 'C', 'Embarked_C'] = 1
test.loc[test['Embarked'] == 'Q', 'Embarked_Q'] = 1
test.drop(['Embarked'], axis = 1, inplace = True)

# In[313]:

test['Fare'] = test['Fare'].fillna('9.0')
test.isnull().sum().astype(float) /test.shape[0] #clear test nans

# In[314]:

score = gs.score(X, y)
print('Logistic Regression pipeline test accuracy: %.3f' % score)

# In[315]:

predictions = gs.predict_proba(test)
default_prob = [i[1] for i in predictions] #Probability for survival

# In[316]:

#create dataframe for predicitons
#dont have the correct passenger ids
prediction = gs.predict(test)
survived = pd.DataFrame({'Survived': prediction}) #prediction of survival generated by model for each test passenger row
survived['PassengerID'] = passengertestID #add correct passenger ids back from test

# In[318]:

survived.head()
survived.to_csv('results.csv', encoding='utf-8', index=False)


from functools import partial
import optparse
from optparse import Option

from pipsqueak.pip.index import PyPI
from pipsqueak.exceptions import RequirementsFileParseError

def constraints():
    return Option(
        '-c', '--constraint',
        dest='constraints',
        action='append',
        default=[],
        metavar='file',
        help='Constrain versions using the given constraints file. '
        'This option can be used multiple times.'
    )

def requirements():
    return Option(
        '-r', '--requirement',
        dest='requirements',
        action='append',
        default=[],
        metavar='file',
        help='Install from the given requirements file. '
        'This option can be used multiple times.'
    )

def editable():
    return Option(
        '-e', '--editable',
        dest='editables',
        action='append',
        default=[],
        metavar='path/url',
        help=('Install a project in editable mode (i.e. setuptools '
              '"develop mode") from a local project path or a VCS url.'),
    )

no_index = partial(
    Option,
    '--no-index',
    dest='no_index',
    action='store_true',
    default=False,
    help='Ignore package index (only looking at --find-links URLs instead).',
)

def find_links():
    return Option(
        '-f', '--find-links',
        dest='find_links',
        action='append',
        default=[],
        metavar='url',
        help="If a url or path to an html file, then parse for links to "
             "archives. If a local path or file:// url that's a directory, "
             "then look for archives in the directory listing.",
    )

def trusted_host():
    return Option(
        "--trusted-host",
        dest="trusted_hosts",
        action="append",
        metavar="HOSTNAME",
        default=[],
        help="Mark this host as trusted, even though it does not have valid "
             "or any HTTPS.",
    )

index_url = partial(
    Option,
    '-i', '--index-url', '--pypi-url',
    dest='index_url',
    metavar='URL',
    default=PyPI.simple_url,
    help="Base URL of Python Package Index (default %default). "
         "This should point to a repository compliant with PEP 503 "
         "(the simple repository API) or a local directory laid out "
         "in the same format.",
)

def extra_index_url():
    return Option(
        '--extra-index-url',
        dest='extra_index_urls',
        metavar='URL',
        action='append',
        default=[],
        help="Extra URLs of package indexes to use in addition to "
             "--index-url. Should follow the same rules as "
             "--index-url.",
    )

require_hashes = partial(
    Option,
    '--require-hashes',
    dest='require_hashes',
    action='store_true',
    default=False,
    help='Require a hash to check each requirement against, for '
         'repeatable installs. This option is implied when any package in a '
         'requirements file has a --hash option.',
)

SUPPORTED_OPTIONS = [
    constraints,
    editable,
    requirements,
    no_index,
    index_url,
    find_links,
    extra_index_url,
    trusted_host,
    require_hashes,
]

def break_args_options(line):
    """Break up the line into an args and options string.  We only want to shlex
    (and then optparse) the options, not the args.  args can contain markers
    which are corrupted by shlex.
    """
    tokens = line.split(' ')
    args = []
    options = tokens[:]
    for token in tokens:
        if token.startswith('-') or token.startswith('--'):
            break
        else:
            args.append(token)
            options.pop(0)
    return ' '.join(args), ' '.join(options)

def build_parser(line):
    """
    Return a parser for parsing requirement lines
    """
    parser = optparse.OptionParser(add_help_option=False)

    option_factories = SUPPORTED_OPTIONS
    for option_factory in option_factories:
        option = option_factory()
        parser.add_option(option)

    # By default optparse sys.exits on parsing errors. We want to wrap
    # that in our own exception.
    def parser_exit(_, msg):
        # add offending line
        msg = 'Invalid requirement: %s\n%s' % (line, msg)
        raise RequirementsFileParseError(msg)
    parser.exit = parser_exit
    parser.exit = parser_exit

    return parser