import sqlite3

# ------------------------------------------------

# /add_item: add one new record to table
def add_item(item_id, category, type, description, vendor, cost, purchase_date):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    try:
        cursor.execute("INSERT INTO inventory (item_id, category, type, description, vendor, cost, purchase_date) VALUES (?,?,?,?,?,?,?)",(item_id, category, type, description, vendor, cost, purchase_date))
        print("Alert: item_id " + item_id + " added to inventory table")
        conn.commit()

    except sqlite3.Error as e:
        print("SQLite Exception: " + str(e))

    conn.close()

# /use_item:
def use_item(item_id, use_date):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    try:
        cursor.execute("INSERT INTO uses (item_id, use_date) VALUES (?, ?)", (item_id, use_date))
        print("Alert: date " + use_date + " logged in uses table for item_id " + item_id)
        conn.commit()

    except sqlite3.Error as e:
        print("SQLite Exception: " + str(e))

    conn.close()

# ------------------------------------------------

# /get_item/{item_id}: query database for one item_id
def get_item(item_id):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    try:
        cursor.execute(("SELECT * FROM inventory WHERE item_id=?"), (item_id,))
        rows = cursor.fetchall()
        for row in rows:
            print(row)
        print("Alert: item_id " + item_id + " record found in inventory table")
        # TODO: return item
    except sqlite3.Error as e:
        print("SQLite Exception: " + str(e))

    conn.close()

# /get_all_items: query database and return all records
def get_all_items():
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    try:
        cursor.execute(("SELECT * FROM inventory"))
        items = cursor.fetchall()
        for item in items:
            print(item)
        print("*get_all_items request complete, end of item inventory *")
        # TODO: return all items
    except sqlite3.Error as e:
        print("SQLite Exception: " + str(e))

    conn.close()

# /get_categories:
def get_categories(category):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    categories = []

    try:
        if category == None:
            cursor.execute("SELECT * FROM inventory")
        else:
            cursor.execute(("SELECT * FROM inventory WHERE category=?"), (category,))

        items = cursor.fetchall()

        for item in items:
            (item_id, category, type, description, vendor, cost, purchase_date) = item
            if category not in categories:
                categories.append(category)
            print(item)
        print("Alert: end of items from category request")

    except sqlite3.Error as e:
        print("SQLite Exception: " + str(e))
        raise Exception("category request failure")

    conn.close()
    return categories

# ------------------------------------------------

# update record
def update_item(item_id, category, type, description, vendor, cost, purchase_date):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    try:
        # get old data for item
        cursor.execute("BEGIN TRANSACTION")
        cursor.execute("SELECT * FROM inventory WHERE item_id=?", (item_id,))
        old_data = cursor.fetchone()
        if old_data == None:
            conn.rollback()
            raise Exception("item_id " + item_id + " does not exist")

        # update data for item
        cursor.execute("UPDATE inventory SET category=?, type=?, description=?, vendor=?, cost=?, purchase_date=? WHERE item_id=?", (category, type, description, vendor, cost, purchase_date, item_id))

        # get newly updated data for item
        cursor.execute("SELECT * FROM inventory WHERE item_id=?", (item_id,))
        new_data = cursor.fetchone()
        if new_data == None:
            conn.rollback()
            raise Exception("item_id " + item_id + " does not exist")
        conn.commit()

        print("Previous data item_id " + item_id + ": " + str(old_data))
        print("Updated data item_id " + item_id + ": " + str(new_data))

    except sqlite3.Error as e:
        conn.rollback()
        print("SQLite Exception: " + str(e))

    conn.close()

# delete record from table
def delete_item(item_id):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    try:
        # get item from inventory
        cursor.execute("BEGIN TRANSACTION")
        cursor.execute("SELECT * FROM inventory WHERE item_id=?", (item_id,))
        item = cursor.fetchone()
        if item == None:
            conn.rollback()
            raise Exception("item_id " + item_id + " does not exist")

        cursor.execute(("DELETE FROM inventory WHERE item_id=?"), (item_id,))
        print("Alert: successfully deleted from inventory table item_id " + item_id + ": " + str(item))

        cursor.execute("SELECT * FROM inventory WHERE item_id=?", (item_id,))
        item = cursor.fetchone()
        if item != None:
            conn.rollback()
            raise Exception("item_id " + item_id + " did not delete")

        conn.commit()

    except sqlite3.Error as e:
        conn.rollback()
        print("SQLite Exception: " + str(e))

    conn.close()


import hashlib
import hmac
import re
from urllib.parse import quote

from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils.http import _urlparse as django_urlparse
from django.utils.translation.trans_real import parse_accept_lang_header

import bleach
import markupsafe

from olympia import amo

class Prefixer:
    def __init__(self, request):
        self.request = request
        split = self.split_path(request.path_info)
        self.locale, self.app, self.shortened_path = split

    @staticmethod
    def split_path(path_):
        """
        Split the requested path into (locale, app, remainder).

        locale and app will be empty strings if they're not found.
        """
        path = path_.lstrip('/')

        # Use partition instead of split since it always returns 3 parts.
        first, _, first_rest = path.partition('/')
        second, _, rest = first_rest.partition('/')

        first_lower = first.lower()
        lang, dash, territory = first_lower.partition('-')

        # Check language-territory first.
        if first_lower in settings.LANGUAGE_URL_MAP:
            if second in amo.APPS:
                return first, second, rest
            else:
                return first, '', first_rest
        # And check just language next.
        elif dash and lang in settings.LANGUAGE_URL_MAP:
            first = lang
            if second in amo.APPS:
                return first, second, rest
            else:
                return first, '', first_rest
        elif first in amo.APPS:
            return '', first, first_rest
        else:
            if second in amo.APPS:
                return '', second, rest
            else:
                return '', '', path

    def get_app(self):
        """
        Return a valid application string based on the `app` query parameter or
        the User Agent. Falls back to settings.DEFAULT_APP.
        """
        if 'app' in self.request.GET:
            app = self.request.GET['app'].lower()
            if app in amo.APPS.keys():
                return app

        ua = self.request.META.get('HTTP_USER_AGENT')
        if ua:
            for app in amo.APP_DETECT:
                if app.matches_user_agent(ua):
                    return app.short

        return settings.DEFAULT_APP

    def get_language(self):
        """
        Return a locale code that we support on the site using `lang` from GET,
        falling back to the user's Accept Language header if necessary (mostly
        following the RFCs but read bug 439568 for details).
        """
        if 'lang' in self.request.GET:
            lang = self.request.GET['lang'].lower()
            if lang in settings.LANGUAGE_URL_MAP:
                return settings.LANGUAGE_URL_MAP[lang]
            prefix = lang.split('-')[0]
            if prefix in settings.LANGUAGE_URL_MAP:
                return settings.LANGUAGE_URL_MAP[prefix]

        accept = self.request.META.get('HTTP_ACCEPT_LANGUAGE', '')
        return lang_from_accept_header(accept)

    def fix(self, path):
        path = path.lstrip('/')
        url_parts = [self.request.META['SCRIPT_NAME']]

        if not re.match(settings.SUPPORTED_NONAPPS_NONLOCALES_REGEX, path):
            if path.partition('/')[0] not in settings.SUPPORTED_NONLOCALES:
                url_parts.append(self.locale or self.get_language())

            if path.partition('/')[0] not in settings.SUPPORTED_NONAPPS:
                url_parts.append(self.app or self.get_app())

        url_parts.append(path)
        return '/'.join(url_parts)

def get_outgoing_url(url):
    """
    Bounce a URL off an outgoing URL redirector, such as
    outgoing.prod.mozaws.net.
    """
    if not settings.REDIRECT_URL:
        return url

    # django.utils.http._urlparse is a copy of python's urlparse()
    # "but uses fixed urlsplit() function".
    parsed_url = django_urlparse(url)
    url_netloc = parsed_url.netloc

    # This prevents a link like javascript://addons.mozilla.org...
    # being returned unchanged since the netloc matches the
    # safe list see bug 1251023
    if parsed_url.scheme not in ['http', 'https']:
        return '/'

    # No double-escaping, and some domain names are excluded.
    allowed = settings.REDIRECT_URL_ALLOW_LIST + [
        django_urlparse(settings.EXTERNAL_SITE_URL).netloc
    ]
    if (
        url_netloc == django_urlparse(settings.REDIRECT_URL).netloc
        or url_netloc in allowed
    ):
        return url

    url = force_bytes(markupsafe.Markup(url).unescape())
    sig = hmac.new(
        force_bytes(settings.REDIRECT_SECRET_KEY), msg=url, digestmod=hashlib.sha256
    ).hexdigest()
    # Let '&=' through so query params aren't escaped.  We probably shouldn't
    # bother to quote the query part at all.
    return '/'.join([settings.REDIRECT_URL.rstrip('/'), sig, quote(url, safe='/&=')])

def linkify_bounce_url_callback(attrs, new=False):
    """Linkify callback that uses get_outgoing_url."""
    HREF_KEY = (None, 'href')
    if HREF_KEY in attrs.keys():
        attrs[HREF_KEY] = get_outgoing_url(attrs[HREF_KEY])
    return attrs

def linkify_only_full_urls(attrs, new=False):
    """Linkify only full links, containing the scheme."""
    if not new:  # This is an existing <a> tag, leave it be.
        return attrs

    # If the original text doesn't contain the scheme, don't linkify.
    if not attrs['_text'].startswith(('http:', 'https:')):
        return None

    return attrs

def linkify_with_outgoing(text):
    """Wrapper around bleach.linkify: uses get_outgoing_url."""
    callbacks = [linkify_bounce_url_callback, bleach.callbacks.nofollow]
    return bleach.linkify(str(text), callbacks=callbacks)

def linkify_and_clean(text):
    callbacks = [linkify_only_full_urls, bleach.callbacks.nofollow]
    return bleach.linkify(bleach.clean(str(text)), callbacks=callbacks)

def lang_from_accept_header(header):
    # Map all our lang codes and any prefixes to the locale code.
    langs = settings.LANGUAGE_URL_MAP

    # If we have a lang or a prefix of the lang, return the locale code.
    for lang, _ in parse_accept_lang_header(header.lower()):
        if lang in langs:
            return langs[lang]

        prefix = lang.split('-')[0]
        # Downgrade a longer prefix to a shorter one if needed (es-PE > es)
        if prefix in langs:
            return langs[prefix]
        # Upgrade to a longer one, if present (zh > zh-CN)
        lookup = settings.SHORTER_LANGUAGES.get(prefix, '').lower()
        if lookup and lookup in langs:
            return langs[lookup]

    return settings.LANGUAGE_CODE


import numpy as np, pandas as pd

arr1 = np.arange(10)
s1 = pd.Series(arr1)

dic1 = {'a':10,'b':20,'c':30,'d':40,'e':50}
s2 = pd.Series(dic1)

arr2 = np.array(np.arange(12)).reshape(4,3)
df1 = pd.DataFrame(arr2)

dic2 = {'a':[1,2,3,4],'b':[5,6,7,8],
        'c':[9,10,11,12],'d':[13,14,15,16]}
df2 = pd.DataFrame(dic2)
dic3 = {'one':{'a':1,'b':2,'c':3,'d':4},
        'two':{'a':5,'b':6,'c':7,'d':8},
        'three':{'a':9,'b':10,'c':11,'d':12}}
df3 = pd.DataFrame(dic3)

df4 = df3[['one','three']]
s3 = df3['one']

s4 = pd.Series(np.array([1,1,2,3,5,8]))
s4.index = ['a','b','c','d','e','f']
# s4[3]
# s4['e']
# s4[[1,3,5]]
# s4[['a','b','d','f']]
# s4[:4]
# s4['c':]
# s4['b':'e']

s5 = pd.Series(np.array([10,15,20,30,55,80]),
               index = ['a','b','c','d','e','f'])
s6 = pd.Series(np.array([12,11,13,15,14,16]),
               index = ['a','c','g','b','d','f'])
s5 + s6
s5/s6

np.random.seed(1234)
d1 = pd.Series(2*np.random.normal(size = 100)+3)
d2 = np.random.f(2,4,size = 100)
d3 = np.random.randint(1,100,size = 100)
d1.count()  #非空元素计算
d1.min()    #最小值
d1.max()    #最大值
d1.idxmin() #最小值的位置，类似于R中的which.min函数
d1.idxmax() #最大值的位置，类似于R中的which.max函数
d1.quantile(0.1)    #10%分位数
d1.sum()    #求和
d1.mean()   #均值
d1.median() #中位数
d1.mode()   #众数
d1.var()    #方差
d1.std()    #标准差
d1.mad()    #平均绝对偏差
d1.skew()   #偏度
d1.kurt()   #峰度
d1.describe()   #一次性输出多个描述性统计指标

def stats(x):
    return pd.Series([x.count(),x.min(),x.idxmin(),
               x.quantile(.25),x.median(),
               x.quantile(.75),x.mean(),
               x.max(),x.idxmax(),
               x.mad(),x.var(),
               x.std(),x.skew(),x.kurt()],
              index = ['Count','Min','Whicn_Min',
                       'Q1','Median','Q3','Mean',
                       'Max','Which_Max','Mad',
                       'Var','Std','Skew','Kurt'])
stats(d1)

df = pd.DataFrame(np.array([d1,d2,d3]).T,columns=['x1','x2','x3'])
df.head()
df.apply(stats)

from pandas import Series,DataFrame
a=[['刘玄德','男','语文',98.],['刘玄德','男','体育',60.],['关云长','男','数学',60.],['关云长','男','语文',100.]]
af=DataFrame(a,columns=['name','sex','course','score'])
af.set_index(['name','sex','course'],inplace=True)
t1=af.unstack(level=2)
t2=t1.mean(axis=1,skipna=True)
t1['平均分']=t2
t1.fillna(0)

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0, 100, 100), columns=['score'])
# 以所在区间作为标签。如 x=5，返回：'[0-10]'
def make_label(x, step=10):
    m = x // step
    return '[{}-{}]'.format(m * step, (m + 1) * step)
# df['level'] = df['score'].map(make_label)
df['level'] = df['score'].map(lambda x: make_label(x, step=10))  # 改变区间长度为15
res = df.groupby('level').size()
print(df.head())
print(res)

# 遍历

for index,row in df.iterrows():
    for a in row:
        print (a)
    print (index) #获取行的索引
    print (row.a) #根据列名获取字段
    print (row[0])#根据列的序号（从0开始）获取字段

import pandas as pd
dict=[[1,2,3,4,5,6],[2,3,4,5,6,7],[3,4,5,6,7,8],[4,5,6,7,8,9],[5,6,7,8,9,10]]
data=pd.DataFrame(dict)
print(data)
for indexs in data.index:
    print(data.loc[indexs].values[0:-1])


import time
import pyspark
import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

spark = SparkSession.builder.appName('Q2_SQL').getOrCreate()

#Create Dataframe for tripdata
df_trips = spark.read.parquet('hdfs://master:9000/project_data/*.parquet')

#Create Dataframe for zones
df_zones = spark.read.csv('hdfs://master:9000/project_data/taxi+_zone_lookup.csv', header=True)

#Join Zones with Tripdata
df_trips = df_trips.join(df_zones, df_trips['DOLocationID'] ==  df_zones['LocationID'],"inner")

#Change pickup date timestamp
df_trips = df_trips.withColumn('pickup_date', to_date(df_trips.tpep_pickup_datetime,'YYYY-MM-DD'))

#Create Sql View
df_trips.createOrReplaceTempView("tripdata")

start_time = time.time()

#Q2
sql2 = spark.sql("SELECT t1.*\
    FROM tripdata t1\
    JOIN\
    (SELECT MAX(tolls_amount) AS tolls,\
    MONTH(pickup_date) AS pickup\
    FROM tripdata\
    WHERE MONTH(pickup_date) < 7\
    GROUP BY MONTH(pickup_date)\
    ORDER BY MAX(tolls_amount) DESC) t2\
    ON t1.tolls_amount = t2.tolls")

#sql2.show()

sql2.write.mode("overwrite").option("header",True).csv("hdfs://master:9000/out_data/sql2_out/")

time = time.time() - start_time

print('Execution time: ', time)


#BOJ 11054
#344ms, 30864KB
num = int(input())
seq = list(map(int, input().split()))

inc = [0]*(num)

#increase
for i in range(num):
    if i == 0:
        inc[i] = 1
    else:
        j = 0
        tmp = 1
        while i > j:
            if seq[i] > seq[j]:
                tmp = inc[j]+1
            if inc[i] < tmp:
                inc[i] = tmp
            j += 1
dec = [0]*(num)
for i in range(num-1, -1, -1):
    if i == num-1:
        dec[i] = 1
    else:
        j = num-1
        tmp = 1
        while i < j:
            if seq[i]>seq[j]:
                tmp = dec[j]+1
            if dec[i]<tmp:
                dec[i] = tmp
            j -= 1
res = 0
for i in range(num):
    if res < inc[i]+dec[i]-1:
        res = inc[i]+dec[i]-1
print(res)


from flask import Flask, render_template, Markup
import markdown
import glob

# Setup flask, include Jade processing
app = Flask(__name__)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

# Retrieve info on .md posts
def get_posts():
    posts = []
    allPosts = glob.glob('./posts/*.md')
    for thisPost in allPosts:
        f = open(thisPost, 'r')
        file_contents = f.read()

        meta_ind = file_contents.index('\n')
        meta = file_contents[0:meta_ind].split(', ')
        contents = file_contents[meta_ind+2:len(file_contents)]
        url = meta[0].lower().replace(' ', '-')

        print(url)

        posts.append({
            'dir': thisPost,
            'title': meta[0],
            'url': url,
            'author': meta[1],
            'contents': contents
        })
    return posts

# store this for the app to use
posts = get_posts();

# Route index
@app.route('/')
def hello_world():
    return 'Hello, World!'

# Route post index
@app.route('/posts/')
def jade(someString=None):
    return render_template('postIndex.jade', posts=posts)

# Route post
@app.route('/posts/<post_url>')
def render_post(post_url=None):
    i = -1
    for index in range(len(posts)):
        if (posts[index]['url'] == post_url):
            i = index
    if i != -1:
        thisPost = posts[i]
        title = thisPost['title']
        text = Markup(markdown.markdown(thisPost['contents']))
        return render_template('post.jade', text=text, title=title)
    else:
        return 'Post not found'

# Force app to run on specific port?
app.run(debug=True, host='0.0.0.0', port=5001)


"""How to algorithmically identify whether graph does contains cycles or acycles. For this,
we need to create some sort of tree from the given graph. Post that we need to check whether
there are some edge left in the graph while creating the tree. If this is the case, then graph
does have cycles. Otherwise graph does not have cyclers.  For this, we can either use BFS or DFS.
"""

""" How to algorithmically indentify whether graph is connected or not. Here component
number represents the maximum subsets of vertices that are connected. """

import CommonGraph

gComponentNumber        = {}
gCurrentComponentNumber = 0
gNonTreeEdgesList       = []

def bfs_startegy_for_adjacencyMatrix_connectivitycheck_helper(fvAMatrix, fV):
    """Helper method for the main implementation."""

    global gComponentNumber
    global gCurrentComponentNumber
    global gNonTreeEdgesList

    tvQueue = CommonGraph.Queue()

    # start the proceedings with the given input vertix. The initial value would be 0.
    gComponentNumber[fV] = gCurrentComponentNumber
    tvQueue.addq(fV)

    while(not tvQueue.isEmpty()):
        tvCurrProcessing = tvQueue.delq()
        tvNeighboursList = CommonGraph.neighbours(fvAMatrix, tvCurrProcessing)
        for k in tvNeighboursList:
            if(gComponentNumber[k] == -1):
                gComponentNumber[k] = gCurrentComponentNumber
                tvQueue.addq(k)
            else:
                # store these edges as they would not be part of tree as they got skipped.
                gNonTreeEdgesList.append((tvCurrProcessing, k))

def bfs_startegy_for_adjacencyMatrix_connectivitycheck(fvAMatrix):
    """" Assign each vertex a component number & start BFS/DFS from vertex 0.
        Initialize component number to 0. Now as usual BFS/DFS starts executing. Post
        that see if we have got any unvisited vertex and if there is pick the smallest
        and run BFS/DFS on that particular vertex. This time increment component number
        by 1. This way we need to run the BFS/DFS until there is no unvisited vertex left.
        Post that there would be component number for each vertex and based on that we can
        determine whether graph is connected or disconnected one. If there is only one component
        number for all vertix then graph is connected and if there is more that one component
        number then graph is disconnected. With this we can also identify number of connecte

        This is what we need to implement in this alogrithm. """

    global gComponentNumber
    global gCurrentComponentNumber

    (tvRows, tvCols) = fvAMatrix.shape

    # initialization of data structure
    for rowIndex in range(tvCols):
        gComponentNumber[rowIndex] = -1

    tvStartIndex = 0
    while True:
        bfs_startegy_for_adjacencyMatrix_connectivitycheck_helper(tvAdjecenyMatrix, tvStartIndex)
        # reset to 0 as we would be rely upon this value to find out whether to proceed or not.
        tvStartIndex = 0
        tvSortedKeyList = sorted(gComponentNumber.keys())
        for aKey in tvSortedKeyList[1:]:
            if ( gComponentNumber[aKey] == -1 ):
                tvStartIndex = aKey
                gCurrentComponentNumber += 1
                break

        if(tvStartIndex == 0):
            break

def check_whether_graph_acyclic():
    """In case there is non tree edge present while exploring the graph,
    those are the reason of cycle in the graph. In case there is none, then
    graph does not not have any cycle. """

    global gNonTreeEdgesList

    tvLen = len(gNonTreeEdgesList)
    if(tvLen == 0):
        print("Current graph does not have any cycle")
    else:
        print("Current graph seems to have " + str(tvLen) + " cycle")

###########################################################################################
######################################__main__#############################################
###########################################################################################
tvAdjecenyMatrix  = CommonGraph.create_graph_into_adjacency_matrix(5)
bfs_startegy_for_adjacencyMatrix_connectivitycheck(tvAdjecenyMatrix)

# check out in case graph does have cycles and whats the sequence of that cycle.
check_whether_graph_acyclic()

print("Completed Successfully")


import numpy as np

class PeakDetector():
    """ A peak detect object base on local maximum and local minimum.

    This module will analyse extrema (local maximum and local minimum) from
    input data, you can apply filters by give vaild argument.

    Args:
        *args   - for data, a 1D array/list (Only use args[0] for data).
        pd      - Peak Distance. The minimum distance of same type extrema (eg.
                max with max). The unit is data number, so it's integer.
        ph      - Peak Height relatively. It's difference height of neighboring
                opposite extrema (eg. max with min).
                Ignore or set to False to turn off this option.
        th      - Threshold. It's absolute height of peak. Can be a number,
                2 element array/list or 2D array/list with 4 element.
                Ignore or set to False to turn off this option.

    Args, didn't finish(for developer):
        adp     - Adaptive, Adapt pd, ph ,etc.

    Attributes (public):
        analyseTime - log time of peak detection with filters consumption.

    Attributes (private):
        flt_*   - * can be pd, ph, th, etc. record all filter.

    """
    time = 0

    def __init__(self, *args, pd = 2, ph = False, th= False, adp = False ,
        measureTime = False ):

        #self.time = []     # a narray
        self.data = np.array(args[0]) if len(args) > 0 else np.array([])

        self.extr = {'min': [] , 'max': []} # index of data for extrema
        self.extr_rm = {'min':[] ,'max':[]} # index of data for removed extrema

        self.analyseTime = 0  # analyse() consume time.
        self.measureTime = measureTime

        self.adp = adp

        # filter - pd - Peak Distance (minimum)
        self.flt_pd = int(pd) if pd > 0 else 1

        # Filter - ph - relative Peak Height
        try :
            if not ph :
                self.flt_ph = False
            if np.ndim(ph) == 0 :
                self.flt_ph = [ph, 0]
            elif np.ndim(ph) == 1 and len(ph) == 2 :
                self.flt_ph = [ph[0], ph[1]]
        except :
            self.flt_ph = False
            print("Relatively height setting error!")

        # Filter - th - Threshold
        try :
            if not th :
                self.flt_th = False
            elif np.ndim(th) == 0 :
                # only one number, so min of all extrema
                self.flt_th = [
                    [th, np.Inf],
                    [th, np.Inf]]
            elif np.ndim(th) == 1:
                # min and max of all extrema
                self.flt_th = [
                    [th[0], th[1]],
                    [th[0], th[1]]]
            elif np.ndim(th) == 2:
                # min and max of each type extrema
                self.flt_th = [
                    [th[0][0], th[0][1]],
                    [th[0][1], th[1][1]]]
        except:
            self.flt_th = False
            print("Threshold dimension error!")

        # logs
        self.log_flt_pd = []
        self.log_flt_ph = []
        self.log_rs = [[],[]]
        self.log_std=[[],[]]

        self.loop_count=0

        if self.measureTime :
            __class__.time = __import__('time')
            print('hi',__class__.time.monotonic())

        if len(self.data) >= 3 :
            self.analyse()

    def analyse(self, n=0):
        """ Peak detect function. only call from class members.

        Args:
            n   - Start scan location of .data .
        """

        if self.measureTime :
            self.analyseTime = __class__.time.monotonic()
        if self.adp :
            self.flt_ph = 1
            self.log_flt_pd = []
            self.log_flt_ph = []

        preExtr = { 'i': 0, 'v': 0}
        blkExtr = { 'i': 0, 'v': 0}

        # Determine first is max or min
        dataBlock = self.data[0:self.flt_pd]  # should check boundary in other language.
        find_max = True if np.argmax(dataBlock) > np.argmin(dataBlock) else False

        lastExtr = {'min': 0, 'max' : 0}

        dataLen = len(self.data)
        #find_max = True    # find min first may ignore code for first max and flt_ph
        while n < dataLen -1 :
            self.loop_count += 1
            #print('loop count = ', loop_count,
                #'\tn = ' ,n, '\tmax' if find_max else '\tmin',
                #)
            # record flt_pd when adp
            if self.adp :
                self.log_flt_pd.append(self.flt_pd)
                self.log_flt_ph.append(self.flt_ph)

            # Load a part data to find extrema
            if n + self.flt_pd > dataLen :
                dataBlock = self.data[n:]
            else :
                dataBlock = self.data[n: n + self.flt_pd ]

            self.log_std[0].append(n)
            self.log_std[1].append(np.std(self.data[n: n +10]))

            # Get extrema
            blkExtr['i'] = np.argmax(dataBlock) if find_max else np.argmin(dataBlock)
            blkExtr['v'] = dataBlock[blkExtr['i']]

            # Compare last block, move on or save extrema then find opposite extrema.
            if (blkExtr['v'] >= preExtr['v'] if find_max else
                blkExtr['v'] <= preExtr['v'] ):
                preExtr['i'] = blkExtr['i'] + n
                preExtr['v'] = blkExtr['v']
                n += self.flt_pd
            elif preExtr['i'] - lastExtr['max' if find_max else 'min'] < self.flt_pd :
                # If extrema near last opposite extrema may case two opposite
                # extrema short then min distance (flt_pd), so check it.
                preExtr['i'] = blkExtr['i'] + n
                preExtr['v'] = blkExtr['v']
                n += self.flt_pd
            else :
                self.extr['max' if find_max else 'min'].append(preExtr['i'])
                n = preExtr['i']
                lastExtr['max' if find_max else 'min'] = preExtr['i']

                #if loop_count > 5000 :
                    #break

                if self.adp :
                    self.adaptive(find_max,n)

                find_max = not find_max
        # while data seq
        #self.extr['max' if find_max else 'min'].append(preExtr['i'])

        # filters
        extrLen = {
            'max' : len(self.extr['max']),
            'min' : len(self.extr['min'])
        }

        # filter for flt_ph (relatively height of peak and around local minimum)
        if self.flt_ph :
            flt_ph_lower = True if self.flt_ph[0] > 0 else False
            flt_ph_upper = True if self.flt_ph[1] > 0 else False

            #self.flt_ph.sort()  # make sure [0] < [1]

            # 2nd extrema type should start from 2nd data
            if self.extr['max'][0] > self.extr['min'][0] :
                shift = {'max': 0, 'min': 1}
            else :
                shift = {'max': 1, 'min': 0}

            for mm in ['max', 'min'] :
                if mm == 'max' :    # current extrema
                    mmo = 'min'     # opposite extrema
                    tmp_sign = 1
                else :
                    mmo = 'max'
                    tmp_sign = -1

                # compare extrema with surround opposite extrema
                for n in range(extrLen[mm]-shift[mm]) :
                    tmp_targetPV = self.data[self.extr[mm][n+shift[mm]]]
                    tmp_surrPV = self.data[self.extr[mmo][n:n+2]]
                    if len(tmp_surrPV) == 2 :
                        # lower limit of relative peak height.
                        if ( flt_ph_lower and
                            (tmp_sign * (tmp_targetPV - tmp_surrPV[0]) < self.flt_ph[0] or
                            tmp_sign * (tmp_targetPV - tmp_surrPV[1]) < self.flt_ph[0]
                        )):
                            self.extr_rm[mm].append(self.extr[mm][n+shift[mm]])

                        # upper limit of relative peak height.
                        # difference is ">" and "and" because it's for noise.
                        if (flt_ph_upper and
                            tmp_sign * (tmp_targetPV - tmp_surrPV[0]) > self.flt_ph[1] and
                            tmp_sign * (tmp_targetPV - tmp_surrPV[1]) > self.flt_ph[1]
                        ):
                            self.extr_rm[mm].append(self.extr[mm][n+shift[mm]])

        # filter for threshold
        if self.flt_th :
            # flt_th should be 2D array: [[min_low,min_up], [min_low,min_up]] .
            for extrType in range(2) :
                extrTypeStr = 'max' if extrType else 'min'
                extr = np.array(self.extr[extrTypeStr])
                extr_rm = np.array(self.extr_rm[extrTypeStr],
                    np.int32)
                extrData = np.array( self.data[extr] )
                th_extr_rm = extr[ np.flatnonzero( np.logical_or(
                    extrData < self.flt_th[extrType][0],
                    extrData > self.flt_th[extrType][1])
                )]
                self.extr_rm[extrTypeStr] = (
                    np.unique(np.concatenate((extr_rm,th_extr_rm)))  )

        # the last line of analyse(), record used time
        if self.measureTime :
            self.analyseTime = __class__.time.monotonic() - self.analyseTime

    def adaptive(self, find_max,n) :
        """ adapt pd, ph ,etc. """

        return # didn't finish

    def update(self, data) :
        """ Renew data and call analyse. """

        # check data type
        if len(data) > 0 :
            self.data = np.array(data)
            self.analyse()

    def append(self, data) :
        """ Append new data to original data.

        This method didn't finish, so disibled.
        """
        if len(data) > 0 :
            pass

    def clear(self) :
        """ clear data in object.

        Actually, it's reinitialize object to default setting,
        include .data and filters.
        """
        self.__init__()

    # -----------------------
    # Read attribute or information of extrema.
    # -----------------------

    # i,v == max.i , max.v
    @property
    def i(self) :
        return np.setdiff1d(self.extr['max'], self.extr_rm['max'])
    @property
    def v(self) :
        return self.data[np.setdiff1d(self.extr['max'], self.extr_rm['max'])]

    # max i,v
    @property
    def max_i(self) :
        return np.setdiff1d(self.extr['max'], self.extr_rm['max'])
    @property
    def max_v(self) :
        return self.data[np.setdiff1d(self.extr['max'], self.extr_rm['max'])]

    # min i,v
    @property
    def min_i(self) :
        return np.setdiff1d(self.extr['min'], self.extr_rm['min'])
    @property
    def min_v(self) :
        return self.data[np.setdiff1d(self.extr['min'], self.extr_rm['min'])]

    # orig i for min, max
    @property
    def orig_max_i(self) :
        return self.extr['max']
    @property
    def orig_min_i(self) :
        return self.extr['min']

    # rm_max i,v
    @property
    def rm_max_i(self) :
        return self.extr_rm['max']
    @property
    def rm_max_v(self) :
        return self.data[self.extr_rm['max']]

    # rm_min i,v
    @property
    def rm_min_i(self) :
        return self.extr_rm['min']
    @property
    def rm_min_v(self) :
        return self.data[self.extr_rm['min']]

    # Read flt_*


import pandas as pd
import matplotlib.pyplot as plt

# 读取Excel文件
df = pd.read_excel("D:\data.xlsx")

# 提取时间和降水量列
time = df['time']
precipitation = df['precipitation']

point_size = 1
# 1. 折线图
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1)
plt.plot(time, precipitation, marker='o', markersize=point_size, linestyle='-', color='b')
plt.xlabel('time')
plt.ylabel('precipitation/mm')
plt.title('Line Plot')

# 2. 散点图
plt.subplot(1, 3, 2)
plt.scatter(time, precipitation, s=point_size, color='green')
plt.xlabel('time')
plt.ylabel('precipitation/mm')
plt.title('Scatter Plot')

# 3. 柱状图
plt.subplot(1, 3, 3)
plt.bar(time, precipitation, color='orange', alpha=0.7)
plt.xlabel('time')
plt.ylabel('precipitation/mm')
plt.title('Bar Chart')
plt.ylim(0, 200)  # 设置y轴范围，最大值为300

# 调整布局并显示图形
plt.tight_layout()
plt.show()


#
# @lc app=leetcode id=150 lang=python3
#
# [150] Evaluate Reverse Polish Notation
#
# https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
#
# algorithms
# Medium (31.87%)
# Likes:    574
# Dislikes: 368
# Total Accepted:    172.4K
# Total Submissions: 523.8K
# Testcase Example:  '["2","1","+","3","*"]'
#
# Evaluate the value of an arithmetic expression in Reverse Polish Notation.
#
# Valid operators are +, -, *, /. Each operand may be an integer or another
# expression.
#
# Note:
#
#
# Division between two integers should truncate toward zero.
# The given RPN expression is always valid. That means the expression would
# always evaluate to a result and there won't be any divide by zero
# operation.
#
#
# Example 1:
#
#
# Input: ["2", "1", "+", "3", "*"]
# Output: 9
# Explanation: ((2 + 1) * 3) = 9
#
#
# Example 2:
#
#
# Input: ["4", "13", "5", "/", "+"]
# Output: 6
# Explanation: (4 + (13 / 5)) = 6
#
#
# Example 3:
#
#
# Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
# Output: 22
# Explanation:
#  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
# = ((10 * (6 / (12 * -11))) + 17) + 5
# = ((10 * (6 / -132)) + 17) + 5
# = ((10 * 0) + 17) + 5
# = (0 + 17) + 5
# = 17 + 5
# = 22
#
#
#

from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = list()
        for token in tokens:
            if token in "+-*/":
                b = stack.pop()
                a = stack.pop()
                if token == '+':
                    stack.append(a + b)
                elif token == '-':
                    stack.append(a - b)
                elif token == '*':
                    stack.append(a * b)
                elif token == '/':
                    res = a // b
                    if res < 0 and a % b != 0:
                        res += 1
                    stack.append(res)
            else:
                stack.append(int(token))
        return stack.pop()

def main():
    solu = Solution()
    print(solu.evalRPN(["10", "6", "9", "3", "+",
                        "-11", "*", "/", "*", "17", "+", "5", "+"]))

if __name__ == "__main__":
    main()


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="Esme",
    version="0.0.1",
    author="Chen Cai",
    author_email="cai.507@osu.edu",
    description="Library for topological data analysis of graphs",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/pypa/sampleproject",
    packages=setuptools.find_packages(),
    install_requires=[
        "networkx",
        "dionysus",
        "sklearn",
        "joblib",
        'cvxpy',
        'torch_geometric',
        'torch_sparse',
        'gensim',
        'pygsp'
    ],
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
)


from typing import Callable, Dict, List, NoReturn, Optional, Tuple

import torch
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data import Dataset

from .info_data import (
    DICT_CLASS,
    get_image_name,
    get_particule_class,
    get_particule_energy,
    get_image_leaderboard,
)

class IdaoDataset(Dataset):
    def __init__(
        self, list_path: List[str], transform: Optional[Callable] = None
    ) -> NoReturn:
        self.list_path = list_path
        if transform is None:
            self.transform = transforms.ToTensor()
        else:
            self.transform = transform

    def __len__(self) -> int:
        return len(self.list_path)

    def __getitem__(self, index: int) -> Tuple[torch.Tensor, int, float]:
        image_path = self.list_path[index]
        image = Image.open(image_path).convert("RGB")
        tensor_image = self.transform(image)
        particule_class = get_particule_class(path=image_path)
        # particule_angle = self.get_particule_angle(path=image_path)
        particule_energy = get_particule_energy(path=image_path)
        return (
            tensor_image,
            torch.tensor(particule_class, dtype=torch.float32).unsqueeze(dim=-1),
            # torch.tensor(particule_angle).unsqueeze(dim=-1),
            torch.tensor(particule_energy).unsqueeze(dim=-1),
        )

class IdaoInferenceDataset(IdaoDataset):
    def __getitem__(self, index: int) -> Tuple[torch.Tensor, str, str]:
        image_path = self.list_path[index]
        image = Image.open(image_path).convert("RGB")
        tensor_image = self.transform(image)
        image_name = get_image_name(path=image_path)
        image_leaderboard = get_image_leaderboard(path=image_path)
        return tensor_image, image_name, image_leaderboard


#!/usr/bin/env python3
"""defines the coruotine wait_n"""
import asyncio
from typing import List
wait_random = __import__('0-basic_async_syntax').wait_random

async def wait_n(n: int, max_delay: int) -> List[float]:
    """takes two arguments n, maxdelay, and
    calls wait_random n types with max_delay
    then returns of delays in ascending order."""

    tasks = []
    for i in range(n):
        tasks.append(wait_random(max_delay))

    asc_times = []
    for coroutine in asyncio.as_completed(tasks):
        asc_times.append(await coroutine)

    return asc_times


from flask_wtf import FlaskForm
from wtforms import (StringField, TextAreaField, IntegerField, BooleanField,
           RadioField, FloatField)
from wtforms.validators import InputRequired, Length

class ProductForm(FlaskForm):
  name = StringField('Name')
  price = FloatField('Price')
  brand = StringField('Brand')
  description = TextAreaField('Description')
  images = StringField('Images')
  # weight = FloatField('Weight(kg)')
  # length = FloatField('Length(cm)')
  # width = FloatField('Width(cm)')
  # height = FloatField('Height(cm)')


"""
URL configuration for config project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

#Global

from django.conf.urls.static import static
from django.conf import settings

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      # terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="asadbekoffical1202@gmail.com"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

#Local
from song.views import SongViewSet, ArtistViewSet, AlbumViewSet
from django.contrib import admin
from django.urls import path, include

# Routers

from rest_framework.routers import DefaultRouter

home_router = DefaultRouter()
home_router.register('song', SongViewSet, basename='song')
home_router.register('artist', ArtistViewSet, basename='artist')
home_router.register('album', AlbumViewSet, basename='album')

## End Routers

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('auth/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('auth/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('', include(home_router.urls)),
    path('doc/api/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/api/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import random
import sys
import math
import numpy as np
from PyQt6.QtCore import QPoint, QRectF, Qt, pyqtSignal
from PyQt6.QtGui import QBrush, QColor, QPainter, QPen, QMouseEvent
from PyQt6.QtWidgets import QApplication, QGraphicsScene, QGraphicsView, QWidget

from alphaBetaPlayer import BLACK, WHITE, AlphaBetaPlayer
from board import Board, WALL, EMPTY
from ninukiGui import Ui_Form

linePen = QPen(QColor("#000000"), 2)
backgroundColor = QColor("#fcecbb")

blackColor = QBrush(QColor("#2b2820"))
whiteColor = QBrush(QColor("#dedede"))

class NinukiWindow(QWidget):
    def __init__(
        self,
    ):

        super().__init__()

        self.ui = Ui_Form()
        self.ui.setupUi(self)

        # arr = np.zeros((7, 7))
        # for i in range(len(arr)):
        #     for j in range(len(arr[i])):
        #         arr[i][j] = 1 if random.random() > 0.5 else 2

        self.board = Board(7, )

        self.player = AlphaBetaPlayer(self.board)

        self.scene = QGraphicsScene()
        self.ui.graphicsView.setScene(self.scene)
        self.ui.graphicsView.setRenderHint(QPainter.RenderHint.Antialiasing)
        self.ui.graphicsView.mousePressEvent = self.onClick
        self.screenSize = 0

    def showEvent(self, a0) -> None:
        self.screenSize = 800
        self.render()

    def onClick(self, event : QMouseEvent):
        point =  self.roundToNearestPoint(event.pos())

        if self.board.data[point] == WALL:
            return

        self.board.play(*point, self.board.currentColor)

    def roundToNearestPoint(self, point : QPoint):

        gap = self.scene.width() / (self.board.size + 1)
        return (
            math.floor((point.y() + gap/2) / gap),
            math.floor((point.x() + gap/2) / gap),
        )

    def render(
        self,
    ):
        self.scene.clear()

        # background
        self.scene.addRect(0, 0, 800, 800, backgroundColor, backgroundColor)

        # draw grid
        size = self.board.size
        width = self.scene.width()
        height = self.scene.height()
        gap = width / (size + 1)
        pieceSize = gap * 0.7
        half = pieceSize / 2

        for i in range(1, size + 1):
            self.scene.addLine(i * gap, gap - 1, i * gap, height - gap, linePen)

        for i in range(1, size + 1):
            self.scene.addLine(gap, i * gap, width - gap, i * gap, linePen)

        self.ui.graphicsView.fitInView(self.scene.sceneRect())

        # draw pieces

        for r in range(1, size + 1):
            for c in range(1, size + 1):
                color = self.board.data[r][c]
                if color != EMPTY:
                    self.scene.addEllipse(
                        r * gap - half,
                        c * gap - half,
                        pieceSize,
                        pieceSize,
                        brush=(blackColor if color == BLACK else whiteColor),
                    )

if __name__ == "__main__":

    a = QApplication(sys.argv)
    w = NinukiWindow()
    w.show()
    sys.exit(a.exec())


# -*- coding: utf-8 -*-
"""
Created on Wed Aug  7 20:25:06 2019

@author: annameng
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime?
You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]
"""

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        nums_set = set(nums)
        length = len(nums)
        result = []

        for i in range(1,length + 1):
            if i not in nums_set:
                result.append(i)
        return result


from operator import matmul
import os
import yaml
#import cv2
from yaml.loader import SafeLoader
import numpy as np
from shutil import copyfile
from enum import Enum
import pandas as pd
import sys

cache_dir_path = r"C:/workspace/ubuntu/cache/"
yaml_template_path = r"C:\workspace\ubuntu\DefSLAM\scripts\stereo0_template.yaml"
execution_path = r"C:\workspace\ubuntu\DefSLAM\Apps\Release\DefSLAMGT.exe"
orb_voc_path = r"C:\workspace\ubuntu\DefSLAM\Vocabulary\ORBvoc.txt"
input_sequence_path =r"C:\workspace\ubuntu\MandalaDataset\Mandala1"

def getYAML(iternumber, K):
    input_yml_path = yaml_template_path
    output_dir = os.path.join(cache_dir_path, "Iter"+str(iternumber))
    os.makedirs(output_dir, exist_ok =True)
    output_yml_path = os.path.join(output_dir,"temp.yaml")
    #input file
    fin = open(input_yml_path, "rt")
    #output file to write the result to
    fout = open(output_yml_path, "wt")
    data= fin.read()
    data = data.replace('%PATH_TO_SAVE%', "\""+output_dir+"\"")
    for i in range(K.shape[0]):
        print('%PARAMETER_'+str(i)+'%')
        data = data.replace('%PARAMETER_'+str(i)+'%', str(K[i]))
    fout.write(data)
    fin.close()
    fout.close()
    return output_dir, output_yml_path

def rms_per_sequence (base_dir):

  # rms, rms_std -> rms and standard deviation
  # angIso_mean, angIso_std -> for the angIso
  # angSfN_mean, angSfN_std -> for the anfSfN
  # fraction_of_matches -> inliers / possible matches (from Matches.txt)

  user_input = base_dir
  directory = os.listdir(user_input)

  #searchstring = input('ErrorGTs')
  df_names = []
  df_names_AngIso = []
  df_names_AngSfN = []
  for file in directory:

      if file.startswith("ErrorGTs"):
          if df_names == []:
              if not os.stat(user_input+"/"+file).st_size == 0:
                  df = pd.read_csv(user_input+"/"+file, header=None).transpose()
                  file = file.strip('ErrorGTs')
                  file = file.strip('.txt')
                  df_names.append(file)
          else:
              if not os.stat(user_input+"/"+file).st_size == 0:
                  df_aux = pd.read_csv(user_input+"/"+file, header=None).transpose()
                  file = file.strip('ErrorGTs')
                  file = file.strip('.txt')
                  df_names.append(file)
                  df = pd.concat([df, df_aux])

      elif file.startswith("ErrorAngIso"):
          if df_names_AngIso == []:
              if not os.stat(user_input+"/"+file).st_size == 0:
                  df_AngIso = pd.read_csv(user_input+"/"+file, header=None).transpose()
                  file = file.strip('ErrorAngIso')
                  file = file.split("-")[0]
                  df_names_AngIso.append(file)
          else:
              if not os.stat(user_input+"/"+file).st_size == 0:
                  df_aux = pd.read_csv(user_input+"/"+file, header=None).transpose()
                  file = file.strip('ErrorAngIso')
                  file = file.split("-")[0]
                  df_names_AngIso.append(file)
                  df_AngIso = pd.concat([df_AngIso, df_aux])

      elif file.startswith("ErrorAngSfN"):
          if df_names_AngSfN == []:
              if not os.stat(user_input+"/"+file).st_size == 0:
                  df_AngSfN = pd.read_csv(user_input+"/"+file, header=None).transpose()
                  file = file.strip('ErrorAngSfN')
                  file = file.split("-")[0]
                  df_names_AngSfN.append(file)
          else:
              if not os.stat(user_input+"/"+file).st_size == 0:
                  df_aux = pd.read_csv(user_input+"/"+file, header=None).transpose()
                  file = file.strip('ErrorAngSfN')
                  file = file.split("-")[0]
                  df_names_AngSfN.append(file)
                  df_AngSfN = pd.concat([df_AngSfN, df_aux])

  df['frame'] = df_names
  df['frame'] = df['frame'].astype('int32')
  df = df.sort_values(by='frame', ascending=True)
  df.iloc[:,0:-1] = df.iloc[:,0:-1]*1000
  n_matches = df.count(axis=1)-1

  #df_AngIso['frame'] = df_names_AngIso
  #df_AngIso['frame'] = df_AngIso['frame'].astype('int32')
  #df_AngIso = df_AngIso.sort_values(by='frame', ascending=True)

  #df_AngSfN['frame'] = df_names_AngSfN
  #df_AngSfN['frame'] = df_AngSfN['frame'].astype('int32')
  #df_AngSfN = df_AngSfN.sort_values(by='frame', ascending=True)

  df_matches = pd.read_csv(user_input+"/Matches.txt", sep = ' ', header=None, names=['frame', 'inliers', 'outliers', 'possibleMatches'])
  df_matches['frame'] = df_matches['frame'].astype('int32')
  df_matches = df_matches.sort_values(by='frame', ascending=True)

  rms = np.nanmean(df.iloc[:,0:-1])
  rms_std = np.nanstd(df.iloc[:,0:-1])

  angIso_mean =0 # np.nanmean(df_AngIso.iloc[:,0:-1])
  angIso_std = 0#np.nanstd(df_AngIso.iloc[:,0:-1])

  angSfN_mean =0# np.nanmean(df_AngSfN.iloc[:,0:-1])
  angSfN_std =0# np.nanstd(df_AngSfN.iloc[:,0:-1])

  fraction_of_matches = df_matches['inliers'].sum().sum()/df_matches['possibleMatches'].sum().sum()

  return rms, rms_std, angIso_mean, angIso_std, angSfN_mean, angSfN_std, fraction_of_matches

def runDefSLAM(iternumber, params):
    input_path =input_sequence_path
    output_dir, input_yml_path = getYAML(iternumber, K=params)
    os.chdir(output_dir)
    input_path_image = os.path.join(input_path , r"images")
    input_path_time = os.path.join(input_path, r"timestamps", "timestamps.txt")
    exe_str = execution_path
    exe_str +=" " + orb_voc_path
    exe_str +=" " + input_yml_path
    exe_str +=" " + input_path_image
    exe_str +=" " + input_path_image
    exe_str +=" " + input_path_time
    print(exe_str)
    os.system(exe_str)
    rms, rms_std, angIso_mean, angIso_std, angSfN_mean, angSfN_std, fraction_of_matches = rms_per_sequence(output_dir)
    return rms
#runDefSLAM(1, np.array([1.0]))

class TwiddleState(Enum):
    change = 0
    start = 1

def twiddle(eval, K, dK, path=""):
    max_it = 100
    opt_dim = 0
    sizeParam = K.shape[0]
    twiddle_state = TwiddleState.start
    iter_number = 0
    optimization_value_best = eval(iter_number, K)
    weights = np.diag(1.0/dK)
    K_best = K
    K[opt_dim] = K[opt_dim] + dK[opt_dim]

    stop_norm = 0.01

    while (np.linalg.norm(np.matmul(weights,dK)) > stop_norm and iter_number<max_it ):
        iter_number = iter_number+1
        optimization_value = eval(iter_number, K)
        if(path==""):
            print("Iteration:" , iter_number, ", ")
            print("Current state vector : ", K.T ,", ")
            print("Current search space size : ", np.linalg.norm(np.matmul(weights,dK)) ," Stop at ",stop_norm)
            print("Current derivative: " , dK.T, ", ")
            print("Current best:" , optimization_value_best, ", current: ", optimization_value)

        else:
            original_stdout = sys.stdout
            with open(path, 'a') as f:
                sys.stdout = f
                print("Iteration:" , iter_number, ", ")
                print("Current state vector : ", K.T ,", ")
                print("Current derivative: " , dK.T, ", ")
                print("Current search space size : ", np.linalg.norm(np.matmul(weights,dK)) ," Stop at ",stop_norm)
                print("Current best:" , optimization_value_best, ", current: ", optimization_value)

                sys.stdout = original_stdout

        if twiddle_state ==  TwiddleState.start:
            if (optimization_value < optimization_value_best):
                K_best = K
                optimization_value_best = optimization_value
                dK[opt_dim] = dK[opt_dim] * 1.5
                opt_dim = (opt_dim+1)  % sizeParam
                K[opt_dim] = K[opt_dim] + dK[opt_dim]
            else:
                K[opt_dim] = K[opt_dim] - 2.0*dK[opt_dim]
                twiddle_state = TwiddleState.change
        elif twiddle_state== TwiddleState.change:
            if optimization_value < optimization_value_best:
                K_best = K
                optimization_value_best = optimization_value
                dK[opt_dim] = -dK[opt_dim]
            else:
                K[opt_dim] = K[opt_dim] + dK[opt_dim]
                dK[opt_dim] = dK[opt_dim] / 2.0
            opt_dim =  (opt_dim + 1)  % sizeParam
            twiddle_state = TwiddleState.start
            K[opt_dim] = K[opt_dim] + dK[opt_dim]
    return K_best
def testTwiddle():
    def testEvalFunction( iter, K):
        return np.linalg.norm(K)
    K=np.array([1.0,2.0,3.0])
    dK = K * 0.1

    k_best = twiddle(testEvalFunction, K, dK)
    print(testEvalFunction(-1, k_best))
    assert (abs(testEvalFunction(-1, k_best))<1e-2)
testTwiddle()

def runTwiddleDefSLAM():
    K = np.array([0.05, 0.7, 0.1])
    dK = K * 0.05
    k_best = twiddle(runDefSLAM, K, dK,os.path.join(cache_dir_path,"twiddleOutput.txt"))
    runDefSLAM(-1, k_best)
runTwiddleDefSLAM()
#rint(os.path.join(r"C:/workspace/ubuntu/cache/", "Iter"+str(1)))


import sqlite3

connect = sqlite3.connect('notes_database.db')
cursor = connect.cursor()

cursor.execute("DROP TABLE IF EXISTS note")
connect.commit()
# exit()
cursor.execute("""
CREATE TABLE IF NOT EXISTS note(
              note_id INTEGER DEFAULT 0 PRIMARY KEY AUTOINCREMENT,
              user_id INTEGER,
              description TEXT,
              date TEXT
)
""")
connect.commit()

def new_note(text: str, user_id: (str, int), cursor: sqlite3.Cursor, connect: sqlite3.Connection) -> None:
    data = {
        "user_id": user_id,
        "description": text
    }
    cursor.execute("INSERT INTO note (user_id, description, date) VALUES(:user_id, :description, CURRENT_TIMESTAMP)", data)
    connect.commit()

def edit_note(note_id: (str, int), text: str, cursor: sqlite3.Cursor, connect: sqlite3.Connection) -> None:
    """В следующей версии бота будет..."""
    pass

def del_note(user_id: (str, int), note_id: (str, int), cursor: sqlite3.Cursor, connect: sqlite3.Connection) -> bool:
    """return True if note deleted, False if note didn't delete"""

    data = {
        "user_id": user_id,
        "note_id": note_id,
    }

    exist = bool(cursor.execute("SELECT * FROM note WHERE user_id = (:user_id) AND note_id = (:note_id)", data).fetchone())
    if exist:
        cursor.execute("DELETE FROM note WHERE note_id = (:note_id)", data)
        connect.commit()
        return True
    return False

def get_notes(id: (str, int), cursor: sqlite3.Cursor, count = 0) -> list|bool:
    """count 1 = one message, count 0 = all message"""
    data = {"id": id,}
    if not count:
        who_id = "user"
    else:
        who_id = "note"

    notes = cursor.execute(f"SELECT note_id, description, date FROM note WHERE {who_id}_id = (:id)", data).fetchall()

    if bool(notes):
        return notes
    return False


import logging
import re

from prometheus_client.core import GaugeMetricFamily

LOG = logging.getLogger(__name__)
re_invalid_chars = re.compile(r'[^\w]+')

class KeystoneCollector(object):
    def __init__(self, cloud):
        self.cloud = cloud

    def get_domains(self):
        LOG.info('start collecting keystone domains')
        m = GaugeMetricFamily('keystone_domain',
                              'Information about a keystone domain',
                              labels=['os_domain_uuid', 'os_domain_name'])

        for dom in self.cloud.list_domains():
            m.add_metric([dom.id, dom.name], 1.0)

        LOG.info('done collecting keystone domains')
        yield m

    def get_projects(self):
        LOG.info('start collecting keystone projects')
        m = GaugeMetricFamily('keystone_project',
                              'Information about a keystone project',
                              labels=['os_project_uuid', 'os_project_name'])

        for proj in self.cloud.list_projects():
            m.add_metric([proj.id, proj.name], 1.0)

        LOG.info('done collecting keystone projects')
        yield m

    def get_users(self):
        LOG.info('start collecting keystone users')
        m = GaugeMetricFamily('keystone_user',
                              'Information about a keystone user',
                              labels=['os_user_uuid', 'os_user_name',
                                      'os_user_email'])

        for user in self.cloud.list_users():
            m.add_metric([user.id, user.name,
                          user.email if user.email else ''], 1.0)

        LOG.info('done collecting keystone users')
        yield m

    def describe(self):
        return []

    def collect(self):
        LOG.info('start collecting keystone information')
        yield from self.get_domains()
        yield from self.get_projects()
        yield from self.get_users()
        LOG.info('done collecting keystone information')


from random import randint

computador = randint(0,5)
print('Pensei =', computador)
print('Qual é o numero que pensei')
n = int(input())
while computador != n:
    print('ERROU, qual é o numero que pensei')

    n = int(input())
if n == computador:
    print('BOA')


import os
import glob

xml_root = r'E:\蒸浏记\分割\原数据\单类别\xml'
pic_root = r'E:\蒸浏记\分割\原数据\单类别\pic'

xml_files = os.listdir(xml_root)
pic_files = os.listdir(pic_root)
for e in xml_files:
    if e[:-4]+'.jpg' in pic_files:
        continue
    else:
        os.remove(os.path.join(xml_root,e))
for ex in pic_files:
    if ex[:-4]+'.xml' in xml_files:
        continue
    else:
        os.remove(os.path.join(pic_root,ex))


import cv2 as cv
import numpy as np
blank=np.zeros((500,500,3), dtype='uint8')  #uint8 is a data type of an image
cv.imshow('Blank',blank)
#cv.imshow('Lion',img)
#img=cv.imread('photos/lion.jpg')

#1.Paint The image
#blank[:]=0,0,255
#cv.imshow('Green',blank)

#draw a rectangle
#cv.rectangle(blank,(0,0),(250,250),(0,255,0),thickness=-1)  #to fill the rectangle use cv.FILLED or -1
#cv.imshow('Reactangle',blank)

#draw a circle
#cv.circle(blank,(250,250),40,(0,0,255),thickness=-1)
#cv.imshow('Circle',blank)

#draw a line
#cv.line(blank,(0,0),(250,250),(255,255,255),thickness=3)
#cv.imshow('Line',blank)

#write text in an image
cv.putText(blank,'Hello everyone',(130,250),cv.FONT_HERSHEY_TRIPLEX,1.0,(0,255,0),thickness=2)
cv.imshow('Text',blank)

cv.waitKey(0)


import statistics

from algo.tests.test_select import all_select_funcs
from algo.tests.utils import gen_special_sort_case, get_func_name, timed_test, print_matrix

def test_nth_small_perf():
    matrix = []
    cases = gen_special_sort_case(2000)

    for entry in all_select_funcs:
        func = entry['func']
        func_name = entry.get('name', get_func_name(func))
        if entry.get('is_random', False):
            times = 10
        else:
            times = 2

        matrix.append([func_name, []])
        print('BEGIN', func_name)

        for case, arr in cases.items():
            durations = []
            for n in range(times):
                desc = '{func_name}(_{case}_) #{n}'.format_map(locals())
                with timed_test(desc, 'performance') as get_duration:
                    func(arr.copy(), len(arr) // 3)
                durations.append(get_duration())

            matrix[-1][1].append((case, statistics.mean(durations)))

        print('END', func_name)
        print()

    print_matrix(matrix)


import pytest
from Registry.Registry import RegSZ

from regrippy.plugins.rdphint import Plugin as plugin

from .reg_mock import LoggerMock, RegistryKeyMock, RegistryMock, RegistryValueMock

@pytest.fixture
def mock_reg():
    key = RegistryKeyMock.build("Software\\Microsoft\\Terminal Server Client\\Servers")
    reg = RegistryMock("NTUSER.DAT", "ntuser.dat", key.root())

    srv1 = RegistryKeyMock("server1.com", key)
    srv2 = RegistryKeyMock("server2.com", key)

    key.add_child(srv1)
    key.add_child(srv2)

    srv1username = RegistryValueMock("UsernameHint", "root", RegSZ)
    srv1.add_value(srv1username)

    return reg

def test_rdphint(mock_reg):
    p = plugin(mock_reg, LoggerMock(), "NTUSER.DAT", "-")

    results = list(p.run())

    assert len(results) == 2, "There should only be 2 results"
    assert results[0].key_name == "server1.com", "First server should be server1.com"
    assert results[0].custom["username"] == "root", "First server should have user hint"
    assert results[1].key_name == "server2.com", "Second server should be server2.com"
    assert results[1].custom["username"] == "", "Second server should not have username"


import cv2
from subprocess import Popen

def auto_mask(filedir):
    # Remove Background
    last_slash = filedir.rindex('/')
    filename = filedir[last_slash+1:]
    nobg_filedir = filedir[:last_slash+1] + 'nobg_' + filename

    Popen(['backgroundremover', '-i', filedir, '-o', nobg_filedir]).wait()

    # Get mask
    input_image = cv2.imread(filedir)
    nobg_image = cv2.imread(nobg_filedir)

    pre_mask = cv2.cvtColor(input_image - nobg_image, cv2.COLOR_BGR2GRAY)

    _, mask = cv2.threshold(pre_mask, 5, 255, cv2.THRESH_BINARY)

    mask_file_name = filedir[:last_slash+1] + 'masked_' + filename
    cv2.imwrite(mask_file_name, mask)

    Popen(['rm', nobg_filedir]).wait()

    return mask_file_name


import unittest

import numpy as np
from scipy import constants
from spdm.data.Expression import Expression, Variable
from spdm.data.Function import Function
from spdm.utils.logger import logger

TWOPI = constants.pi*2.0

class TestFunction(unittest.TestCase):

    def test_expression(self):
        x = np.linspace(0, 1.0, 128)
        y = np.sin(x*TWOPI)

        fun = Function(y, x)
        expr = fun*2.0
        self.assertTrue(type(expr) is Expression)

    def test_operator(self):
        x = np.linspace(0, 1, 128)
        y = np.linspace(0, 2, 128)
        fun = Function(y, x)

        self.assertTrue(np.all(-fun == -y))
        self.assertTrue(np.all(fun + 2 == y + 2))
        self.assertTrue(np.all(fun - 2 == y - 2))
        self.assertTrue(np.all(fun * 2 == y * 2))
        self.assertTrue(np.all(fun / 2 == y / 2))
        self.assertTrue(np.all(fun ** 2 == y ** 2))
        # self.assertTrue(np.all(fun @ fun == y)

    def test_construct_from_expression(self):
        x = np.linspace(0, 1, 128)
        y = np.linspace(0, 2, 128)
        fun = Function(y*2, x)

        self.assertTrue(np.allclose(fun, y * 2))

    def test_np_fun(self):
        x = np.linspace(0, 1, 128)
        y = np.linspace(0, 2, 128)

        fun = Function(y, x)

        self.assertTrue(type(fun+1) is Expression)
        self.assertTrue(type(fun*2) is Expression)
        self.assertTrue(type(np.sin(fun)) is Expression)

    def test_constant_fun(self):
        value = 1.2345
        xmin = 0.0
        xmax = 1.0
        ymin = 2.0
        ymax = 3.0

        dims_a = np.linspace(xmin, xmax, 5),  np.linspace(ymin, ymax, 5)

        fun1 = Function(value)

        xa, ya = np.meshgrid(*dims_a)

        self.assertTrue(np.allclose(fun1(xa, ya), value))

        fun2 = Function(value, *dims_a)

        dims_b = np.linspace(xmin-0.5, xmax+0.5, 10), np.linspace(ymin-0.5, ymax+0.5, 10)

        xb, yb = np.meshgrid(*dims_b)
        marker = (xb >= xmin) & (xb <= xmax) & (yb >= ymin) & (yb <= ymax)

        e_a = np.full_like(xa, value, dtype=float)

        e_b = np.full_like(xb, value, dtype=float)

        e_b[~marker] = np.nan

        self.assertTrue(np.allclose(fun2(xa, ya), e_a))

        self.assertTrue(np.allclose(fun2(xb, yb), e_b, equal_nan=True))

    def test_spl(self):
        x = np.linspace(0, 1.0, 128)
        y = np.sin(x*TWOPI)

        fun = Function(y, x)

        x2 = np.linspace(0, 1.0, 64)

        y2 = np.sin(x2*TWOPI)

        self.assertTrue(np.allclose(y2, fun(x2)))

    def test_delta_fun(self):

        p = 0.5
        value = 1.2345

        fun0 = Function(value, p)

        self.assertTrue(np.isclose(fun0(p), value))

        fun1 = Function([value], [p])

        self.assertTrue(np.isclose(fun1(p), value))

        x = np.linspace(0, 1, 11)

        mark = np.isclose(x, p)

        # logger.debug(fun1(x))
        self.assertTrue(np.allclose(fun1(x)[mark], value))
        self.assertTrue(np.all(np.isnan(fun1(x)[~mark])))

    def test_delta_nd(self):

        p = [0.5, 0.4]
        value = 1.2345

        fun0 = Function(value, *p)

        self.assertTrue(np.isclose(fun0(*p), value))

        dimx = np.linspace(0, 1, 11)
        dimy = np.linspace(0, 1, 11)

        x, y = np.meshgrid(dimx, dimy)

        mark = np.isclose(x, p[0]) & np.isclose(y, p[1])

        self.assertTrue(np.allclose(fun0(x, y)[mark], value))
        self.assertTrue(np.all(np.isnan(fun0(x, y)[~mark])))

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


from flask import Flask, render_template, request, redirect, url_for, jsonify
import sqlite3

def veriEkle(product_name, product_type, product_price, history, user, kalanpara):
    with sqlite3.connect("product.db") as con:
        cur = con.cursor()
        cur.execute(
            "insert into tblproduct (product_name, product_type, product_price,history,user,kalanpara) values (?, ?, ?, ?, ?,?)", (product_name, product_type, product_price, history, user, kalanpara))
        con.commit()
    print("veriler eklendi")

data = []

def veriAl():
    global data
    with sqlite3.connect("product.db") as con:
        cur = con.cursor()
        cur.execute("select * from tblproduct order by id desc ")
        data = cur.fetchall()
        for i in data:
            print(i)

def veriSil(id):
    with sqlite3.connect("product.db") as con:
        cur = con.cursor()
        cur.execute("delete from tblproduct where id=?", (id,))

def veriGuncelle(id, product_name, product_type, product_price, history, user, kalanpara):
    with sqlite3.connect("product.db") as con:
        cur = con.cursor()
        cur.execute("update tblproduct set product_name = ?, product_type = ?, product_price = ?, history = ?, user = ?, kalanpara = ? where id = ?",
                    (product_name, product_type, product_price, history, user, kalanpara, id,))
        con.commit()
    print("Veriler Guncellendi...")

veriAl()
app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/product/<string:id>")
def urundetay(id):
    detayveri = []
    for d in data:
        if str(d[0]) == id:
            detayveri = list(d)
    return render_template("urundetay.html", veri=detayveri)

@app.route("/productedit/<string:id>", methods=["GET", "POST"])
def productedit(id):
    if request.method == "POST":
        id = request.form["id"]
        product_name = request.form["product_name"]
        product_type = request.form["product_type"]
        product_price = request.form["product_price"]
        history = request.form["history"]
        user = request.form["user"]
        kalanpara = request.form["kalanpara"]
        print("Guncellenecek Veriler : ", product_name,
              product_type, product_price, history, user, kalanpara)
        veriGuncelle(id, product_name, product_type,
                     product_price, history, user, kalanpara)
        return redirect(url_for("gelirgider"))
    else:
        guncellenecekveri = []
        for d in data:
            if str(d[0]) == id:
                guncellenecekveri = list(d)
        return render_template("productedit.html", veri=guncellenecekveri)

@app.route("/productadd", methods=["POST", "GET"])
def productadd():
    if request.method == "POST":
        product_name = request.form["product_name"]
        product_type = request.form["product_type"]
        product_price = request.form["product_price"]
        history = request.form["history"]
        user = request.form["user"]
        kalanpara = request.form["kalanpara"]

        print("Eklenecek Veriler : ", product_name,
              product_type, product_price, history)
        veriEkle(product_name, product_type,
                 product_price, history, user, kalanpara)

    return render_template("productadd.html")

@app.route("/gelirgider")
def gelirgider():
    veriAl()
    return render_template("gelirgider.html", veri=data)

@app.route("/productdelete/<string:id>")
def productdelete(id):
    veriSil(id)
    return redirect(url_for("gelirgider"))

@app.route("/api", methods=["GET"])
def api():
    veriAl()
    print(data)
    veri = [{'id': str(row[0]), 'product_name': row[1],
             'product_type': row[2], 'product_price': row[3], 'history': row[4], 'user': row[5], 'kalanpara': row[6]} for row in data]
    return jsonify(veri)

@app.route("/api/add", methods=["POST"])
def apiAdd():
    product_name = request.form['product_name']
    product_type = request.form['product_type']
    product_price = request.form['product_price']
    history = request.form['history']
    user = request.form['user']
    kalanpara = request.form['kalanpara']

    veriEkle(product_name, product_type,
             product_price, history, user, kalanpara)

    message = 'The product has been successfully saved.'

    return jsonify({'status': 'success', 'result': message})

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


import boto3
import configparser
# import os

config = configparser.ConfigParser()
config.read('config.ini')

IAMAccessKey = config['DEFAULT']["IAMAccessKey"]
IAMSecretKey = config['DEFAULT']["IAMSecretKey"]
s3_region = config['DEFAULT']["s3_region"]

s3_bucket = config['DEFAULT']["s3_bucket"]

s3 = boto3.client(
    's3',
    aws_access_key_id=IAMAccessKey,
    aws_secret_access_key=IAMSecretKey,
    region_name=s3_region
    )

image_direc = "dogs/static/Images"

url = s3.generate_presigned_url('get_object',
                                Params={
                                    'Bucket': s3_bucket,
                                    'Key': 'African_hunting_dog/n02116738_10169.jpg', # noqa
                                },
                                ExpiresIn=3600)
print(url)


config = {
    "branch": "jamun",
    "nightly_build": True,
    "update_channel": "beta-dev",

    # l10n
    "hg_l10n_base": "https://hg.mozilla.org/releases/l10n/mozilla-beta",

    # repositories
    # staging beta dev releases use jamun repo for now
    "mozilla_dir": "jamun",
    "repos": [{
        "vcs": "hg",
        "repo": "https://hg.mozilla.org/build/tools",
        "branch": "default",
        "dest": "tools",
    }, {
        "vcs": "hg",
        "repo": "https://hg.mozilla.org/projects/jamun",
        "branch": "%(revision)s",
        "dest": "jamun",
        "clone_upstream_url": "https://hg.mozilla.org/projects/jamun",
    }],
    # purge options
    'is_automation': True,
    'purge_minsize': 12,
    'default_actions': [
        "clobber",
        "pull",
        "clone-locales",
        "list-locales",
        "setup",
        "repack",
        "taskcluster-upload",
        "summary",
    ],
}


import numpy as np
import matplotlib.pyplot as plt
import imutils
import cv2

class Stitcher(object):
	"""Stitcher class forms a panorama from images"""
	def __init__(self):
		pass

	def stitch(self, images, showMatches = True):
		(imageA, imageB) = images

		(kpsA, ftsA) = self.detectAndDescribe(imageA)
		(kpsB, ftsB) = self.detectAndDescribe(imageB)

		M = self.matchKeypoints(kpsA, kpsB, ftsA, ftsB)

		if M == None:
			return None

		# otherwise, apply a perspective warp to stitch the images
		# together
		(matches, H, status) = M
		result = cv2.warpPerspective(imageA, H,
			(imageA.shape[1] + imageB.shape[1], imageA.shape[0]))
		result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB

		# check to see if the keypoint matches should be visualized
		if showMatches:
			vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches,
				status)

			# return a tuple of the stitched image and the
			# visualization
			return (result, vis)

		# return the stitched image
		return result

	def detectAndDescribe(self, image):
		gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

		# detect keypoints in the image
		detector = cv2.FeatureDetector_create("SIFT")
		kps = detector.detect(gray)

		# extract features from the image
		extractor = cv2.DescriptorExtractor_create("SIFT")
		(kps, features) = extractor.compute(gray, kps)

		# convert the keypoints from KeyPoint objects to NumPy
		# arrays
		kps = np.float32([kp.pt for kp in kps])

 		# return a tuple of keypoints and features
		return (kps, features)

	def matchKeypoints(self, kpsA, kpsB, featuresA, featuresB,
		ratio = 0.75, reprojThresh = 4.0):
		# compute the raw matches and initialize the list of actual
		# matches
		matcher = cv2.DescriptorMatcher_create("BruteForce")
		rawMatches = matcher.knnMatch(featuresA, featuresB, 2)
		matches = []

		# loop over the raw matches
		for m in rawMatches:
			# ensure the distance is within a certain ratio of each
			# other (i.e. Lowe's ratio test)
			if len(m) == 2 and m[0].distance < m[1].distance * ratio:
				matches.append((m[0].trainIdx, m[0].queryIdx))

		# computing a homography requires at least 4 matches
		if len(matches) > 4:
			# construct the two sets of points
			ptsA = np.float32([kpsA[i] for (_, i) in matches])
			ptsB = np.float32([kpsB[i] for (i, _) in matches])

			# compute the homography between the two sets of points
			(H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC,
				reprojThresh)

			# return the matches along with the homograpy matrix
			# and status of each matched point
			return (matches, H, status)

		# otherwise, no homograpy could be computed
		return None

	def drawMatches(self, imageA, imageB, kpsA, kpsB, matches, status):
		# initialize the output visualization image
		(hA, wA) = imageA.shape[:2]
		(hB, wB) = imageB.shape[:2]
		vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
		vis[0:hA, 0:wA] = imageA
		vis[0:hB, wA:] = imageB

		# loop over the matches
		for ((trainIdx, queryIdx), s) in zip(matches, status):
			# only process the match if the keypoint was successfully
			# matched
			if s == 1:
				# draw the match
				ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
				ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
				cv2.line(vis, ptA, ptB, (0, 255, 0), 1)

		# return the visualization
		return vis

if __name__ == "__main__":
	stitcher = Stitcher()

	images = [cv2.imread('shot1.jpg'), cv2.imread('shot2.jpg')]
	images = [imutils.resize(image, width=1000) for image in images]
	images.reverse()

	stitcher = Stitcher()
	(result, vis) = stitcher.stitch(images, showMatches=True)

	# show the images
	# cv2.imshow("Image A", images[0])
	# cv2.imshow("Image B", images[1])
	cv2.imshow("Keypoint Matches", vis)
	cv2.imshow("Result", result)
	cv2.waitKey(0)

# gray1 = cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
# gray2 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)

# cv2.imshow('gray', gray1)
# if cv2.waitKey(0) & 0xff == 27:
# 	cv2.destroyAllWindows()

# dst = cv2.cornerHarris(gray1,2,3,0.04)
# dst = cv2.dilate(dst,None)
# img1[dst>0.01*dst.max()]=[0,0,255]

# # cv2.imshow('dst',img1)

# sift = cv2.xfeatures2d.SIFT_create()
# kp = sift.detect(gray1,None)

# img=cv2.drawKeypoints(gray,kp)

# cv2.imwrite('sift_keypoints.jpg',img)

# if cv2.waitKey(0) & 0xff == 27:
# 	cv2.destroyAllWindows()

# # plt.imshow(img1)
# # plt.show()


import argparse
from evalboolarg import evalBoolArg
from readcurve import readCurve
from writecurve import saveLightCurve
from convert2decicoords import convertCoords2Deci
from phase import phaseLightCurve
from plotCurve import plotPhaseCurve
from pickleplot import makePickledPlot
from matplotlib.pyplot import show

def main(file, rightAscension, declination, period, epoch, save, plot, plotlc, picklePlot, hjd, verbose):
    rightAscension, declination = convertCoords2Deci(rightAscension, declination)
    lightCurve = readCurve(file, rightAscension, declination)
    phasedLightCurve = phaseLightCurve(lightCurve, period, epoch)
    if verbose:
        for x in phasedLightCurve:
            print(*x)
    if save:
        saveLightCurve(phasedLightCurve, f'phasedlightcurve_ra{rightAscension:.5f}+dec{declination:.5f}.dat')
    if plot or picklePlot:
        if plotlc:
            fig, ax = plotPhaseCurve(phasedLightCurve, lightCurve, rightAscension, declination, period, epoch, hjd)
        else:
            fig, ax = plotPhaseCurve(phasedLightCurve, None, rightAscension, declination, period, epoch, hjd)
        if picklePlot:
            makePickledPlot(fig, f'fig_ra{rightAscension:.5f}+dec{declination:.5f}')
        if plot:
            show()

parser = argparse.ArgumentParser()
parser.add_argument('file', type = str, help = 'Path to target\'s phased light curve file')
parser.add_argument('rightAscension', type = str, help = 'Target\'s right ascension')
parser.add_argument('declination', type = str, help = 'Target\'s declination')
parser.add_argument('period', type = float, help = 'Period to phase light curve using')
parser.add_argument('--epoch', '-e', type = float, default = 0, help = 'Epoch to use as zeropoint (optional)')
parser.add_argument('--save', '-s', type = str, default = True, help = 'Save phased light curve to .dat file')
parser.add_argument('--plot', '-p', type = str, default = True, help = 'Show interactive phased light curve plot')
parser.add_argument('--plotlc', '-plc', type = str, default = False, help = 'Plot target\'s light curve')
parser.add_argument('--picklePlot', '-pkl', type = str, default = False, help = 'Save interactive figure as a .pkl file')
parser.add_argument('--hjd', type = str, default = False, help = 'Epochs are in HJD')
parser.add_argument('--verbose', '-v', type = str, default = False, help = 'Print light curve to terminal')
args = parser.parse_args()
file = args.file
rightAscension = args.rightAscension
declination = args.declination
period = args.period
epoch = args.epoch
save = evalBoolArg(args.save, True)
plot = evalBoolArg(args.plot, True)
plotlc = evalBoolArg(args.plotlc, False)
picklePlot = evalBoolArg(args.picklePlot, False)
hjd = evalBoolArg(args.hjd, False)
verbose = evalBoolArg(args.verbose, False)
main(file, rightAscension, declination, period, epoch, save, plot, plotlc, picklePlot, hjd, verbose)


import binascii
from itertools import cycle

def hex_xor(string1, string2):
    if not len(string1) == len(string2):
        raise Exception
    string1_bytes = bytes.fromhex(string1)
    string2_bytes = bytes.fromhex(string2)
    xored_bytes = bytes([b1 ^ b2 for b1, b2 in zip(string1_bytes, cycle(string2_bytes))])
    xored_hex = binascii.b2a_hex(xored_bytes).decode()
    return xored_hex

def main():
    print(hex_xor('1c0111001f010100061a024b53535009181c', '686974207468652062756c6c277320657965'))

if __name__ == "__main__":
    main()