import clr

clr.AddReference('System.Windows.Forms')
import System.Windows.Forms as WinForms

clr.AddReference("BaseForm")
import BaseForm

import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *

import frmuser
import frmdbsetup

from frmlogon import frmLogon

class MainForm(BaseForm.frmMyBaseForm):
        def __init__(self):
                self.InitializeComponent()

        def InitializeComponent(self):
                self._statusStrip1 = System.Windows.Forms.StatusStrip()
                self._label1 = System.Windows.Forms.Label()
                self._panel1 = System.Windows.Forms.Panel()
                self._menuStrip1 = System.Windows.Forms.MenuStrip()
                self._toolStripMenuItem1 = System.Windows.Forms.ToolStripMenuItem()
                self._tsDepartment = System.Windows.Forms.ToolStripMenuItem()
                self._companyToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._employeeMasterToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._toolStripSeparator1 = System.Windows.Forms.ToolStripSeparator()
                self._ratesToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._deductionCategoryToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._toolStripSeparator2 = System.Windows.Forms.ToolStripSeparator()
                self._ratesTableToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._deductionSetupToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._toolStripSeparator3 = System.Windows.Forms.ToolStripSeparator()
                self._dailyTimesheetEntryToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._toolStripSeparator4 = System.Windows.Forms.ToolStripSeparator()
                self._quitToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._reportToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._payrollListingToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._payrollSummaryToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._toolsToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._databaseSetupToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._userManagementToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._accessConfigToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._helpToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._aboutToolStripMenuItem = System.Windows.Forms.ToolStripMenuItem()
                self._statusStrip1.SuspendLayout()
                self._panel1.SuspendLayout()
                self._menuStrip1.SuspendLayout()
                self.SuspendLayout()
                #
                # statusStrip1
                #
                #
                # label1
                #
                #self._label1.Dock = System.Windows.Forms.DockStyle.Top
                #self._label1.Font = System.Drawing.Font("Comic Sans MS", 18, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0)
                #self._label1.Location = System.Drawing.Point(0, 0)
                #self._label1.Name = "label1"
                #self._label1.ForeColor = System.Drawing.Color.Firebrick
                #self._label1.Size = System.Drawing.Size(409, 52)
                #self._label1.TabIndex = 0
                #self._label1.Text = "gemsoft payroll system"
                #self._label1.TextAlign = System.Drawing.ContentAlignment.TopCenter
                #
                # panel1
                #
               # self._panel1.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left
               # self._panel1.Controls.Add(self._menuStrip1)
               # self._panel1.Location = System.Drawing.Point(0, 52)
	#	self._panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
               # self._panel1.Name = "panel1"
               # self._panel1.Size = System.Drawing.Size(73, 262)
               # self._panel1.TabIndex = 6
                #
                # menuStrip1
                #
                self._menuStrip1.Dock = System.Windows.Forms.DockStyle.Top
                self._menuStrip1.Items.AddRange(System.Array[System.Windows.Forms.ToolStripItem](
                        [self._toolStripMenuItem1,
                        self._reportToolStripMenuItem,
                        self._toolsToolStripMenuItem,
                        self._helpToolStripMenuItem]))
                self._menuStrip1.Location = System.Drawing.Point(0, 0)
                self._menuStrip1.Name = "menuStrip1"
                self._menuStrip1.Size = System.Drawing.Size(60, 262)
                self._menuStrip1.Stretch = False
                self._menuStrip1.TabIndex = 3
                self._menuStrip1.Text = "menuStrip1"
                #
                # toolStripMenuItem1
                #
                self._toolStripMenuItem1.DropDownItems.AddRange(System.Array[System.Windows.Forms.ToolStripItem](
                        [self._tsDepartment,
                        self._companyToolStripMenuItem,
                        self._employeeMasterToolStripMenuItem,
                        self._toolStripSeparator1,
                        self._ratesToolStripMenuItem,
                        self._deductionCategoryToolStripMenuItem,
                        self._toolStripSeparator2,
                        self._ratesTableToolStripMenuItem,
                        self._deductionSetupToolStripMenuItem,
                        self._toolStripSeparator3,
                        self._dailyTimesheetEntryToolStripMenuItem,
                        self._toolStripSeparator4,
                        self._quitToolStripMenuItem]))
                self._toolStripMenuItem1.Name = "toolStripMenuItem1"
                self._toolStripMenuItem1.Size = System.Drawing.Size(47, 19)
                self._toolStripMenuItem1.Text = "File"
                #
                # tsDepartment
                #
                self._tsDepartment.Name = "tsDepartment"
                self._tsDepartment.Size = System.Drawing.Size(188, 22)
                self._tsDepartment.Text = "Department"
                #
                # companyToolStripMenuItem
                #
                self._companyToolStripMenuItem.Name = "companyToolStripMenuItem"
                self._companyToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._companyToolStripMenuItem.Text = "Company"
                #
                # employeeMasterToolStripMenuItem
                #
                self._employeeMasterToolStripMenuItem.Name = "employeeMasterToolStripMenuItem"
                self._employeeMasterToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._employeeMasterToolStripMenuItem.Text = "Employee Master"
                #
                # toolStripSeparator1
                #
                #
                # ratesToolStripMenuItem
                #
                self._ratesToolStripMenuItem.Name = "ratesToolStripMenuItem"
                self._ratesToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._ratesToolStripMenuItem.Text = "Rates"
                #
                # deductionCategoryToolStripMenuItem
                #
                self._deductionCategoryToolStripMenuItem.Name = "deductionCategoryToolStripMenuItem"
                self._deductionCategoryToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._deductionCategoryToolStripMenuItem.Text = "Deduction Category"
                #
                # toolStripSeparator2
                #
                self._toolStripSeparator2.Size = System.Drawing.Size(185, 6)
                #
                # ratesTableToolStripMenuItem
                #
                self._ratesTableToolStripMenuItem.Name = "ratesTableToolStripMenuItem"
                self._ratesTableToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._ratesTableToolStripMenuItem.Text = "Rates Table"
                #
                # deductionSetupToolStripMenuItem
                #
                self._deductionSetupToolStripMenuItem.Name = "deductionSetupToolStripMenuItem"
                self._deductionSetupToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._deductionSetupToolStripMenuItem.Text = "Deduction Setup"
                #
                # toolStripSeparator3
                #
                self._toolStripSeparator3.Name = "toolStripSeparator3"
                self._toolStripSeparator3.Size = System.Drawing.Size(185, 6)
                #
                # dailyTimesheetEntryToolStripMenuItem
                #
                self._dailyTimesheetEntryToolStripMenuItem.Name = "dailyTimesheetEntryToolStripMenuItem"
                self._dailyTimesheetEntryToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._dailyTimesheetEntryToolStripMenuItem.Text = "Daily Timesheet Entry"
                #
                # toolStripSeparator4
                #
                self._toolStripSeparator4.Name = "toolStripSeparator4"
                self._toolStripSeparator4.Size = System.Drawing.Size(185, 6)
                #
                # quitToolStripMenuItem
                #
                self._quitToolStripMenuItem.Name = "quitToolStripMenuItem"
                self._quitToolStripMenuItem.Size = System.Drawing.Size(188, 22)
                self._quitToolStripMenuItem.Text = "Quit"
                self._quitToolStripMenuItem.Click += self.QuitToolStripMenuItemClick
                #
                # reportToolStripMenuItem
                #
                self._reportToolStripMenuItem.DropDownItems.AddRange(System.Array[System.Windows.Forms.ToolStripItem](
                        [self._payrollListingToolStripMenuItem,
                        self._payrollSummaryToolStripMenuItem]))
                self._reportToolStripMenuItem.Name = "reportToolStripMenuItem"
                self._reportToolStripMenuItem.Size = System.Drawing.Size(47, 19)
                self._reportToolStripMenuItem.Text = "Report"
                #
                # payrollListingToolStripMenuItem
                #
                self._payrollListingToolStripMenuItem.Name = "payrollListingToolStripMenuItem"
                self._payrollListingToolStripMenuItem.Size = System.Drawing.Size(164, 22)
                self._payrollListingToolStripMenuItem.Text = "Payroll Listing"
                #
                # payrollSummaryToolStripMenuItem
                #
                self._payrollSummaryToolStripMenuItem.Name = "payrollSummaryToolStripMenuItem"
                self._payrollSummaryToolStripMenuItem.Size = System.Drawing.Size(164, 22)
                self._payrollSummaryToolStripMenuItem.Text = "Payroll Summary"
                #
                # toolsToolStripMenuItem
                #
                self._toolsToolStripMenuItem.DropDownItems.AddRange(System.Array[System.Windows.Forms.ToolStripItem](
                        [self._databaseSetupToolStripMenuItem,
                        self._userManagementToolStripMenuItem,
                        self._accessConfigToolStripMenuItem]))
                self._toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"
                self._toolsToolStripMenuItem.Size = System.Drawing.Size(47, 19)
                self._toolsToolStripMenuItem.Text = "Tools"
                #
                # databaseSetupToolStripMenuItem
                #
                self._databaseSetupToolStripMenuItem.Name = "databaseSetupToolStripMenuItem"
                self._databaseSetupToolStripMenuItem.Size = System.Drawing.Size(171, 22)
                self._databaseSetupToolStripMenuItem.Text = "Database Setup"
                self._databaseSetupToolStripMenuItem.Click += self.LoadDBSetup
                #
                # userManagementToolStripMenuItem
                #
                self._userManagementToolStripMenuItem.Name = "userManagementToolStripMenuItem"
                self._userManagementToolStripMenuItem.Size = System.Drawing.Size(171, 22)
                self._userManagementToolStripMenuItem.Text = "User Management"
                self._userManagementToolStripMenuItem.Click += self._Load

                #
                # accessConfigToolStripMenuItem
                #
                self._accessConfigToolStripMenuItem.Name = "accessConfigToolStripMenuItem"
                self._accessConfigToolStripMenuItem.Size = System.Drawing.Size(171, 22)
                self._accessConfigToolStripMenuItem.Text = "Access Config"
                #
                # helpToolStripMenuItem
                #
                self._helpToolStripMenuItem.DropDownItems.AddRange(System.Array[System.Windows.Forms.ToolStripItem](
                        [self._aboutToolStripMenuItem]))
                self._helpToolStripMenuItem.Name = "helpToolStripMenuItem"
                self._helpToolStripMenuItem.Size = System.Drawing.Size(47, 19)
                self._helpToolStripMenuItem.Text = "Help"
                #
                # aboutToolStripMenuItem
                #
                self._aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"
                self._aboutToolStripMenuItem.Size = System.Drawing.Size(107, 22)
                self._aboutToolStripMenuItem.Text = "About"
                #
                # MainForm
                #
                self.ClientSize = System.Drawing.Size(409, 341)
                #self.Controls.Add(self._panel1)
                #self.Controls.Add(self._label1)
                self.Controls.Add(self._menuStrip1)
                self.Controls.Add(self._statusStrip1)
                self.IsMdiContainer = True
                self.Name = "MainForm"
                self.Text = "Payroll System"

                self._statusStrip1.ResumeLayout(False)
                self._statusStrip1.PerformLayout()
                self._panel1.ResumeLayout(False)
                self._panel1.PerformLayout()
                self._menuStrip1.ResumeLayout(False)
                self._menuStrip1.PerformLayout()
                self.ResumeLayout(False)
                self.PerformLayout()

                self.WindowState = WinForms.FormWindowState.Maximized #Windows is Maximized by default

                self.AppTitle = "GemSoft Systems" #Application title
                self.LowerColor = System.Drawing.Color.Green
                self.Load += self._Load

        def ToolStripMenuItem1Click(self, sender, e):
                pass

        def ToolStripMenuItem2Click(self, sender, e):
                pass

        def QuitToolStripMenuItemClick(self, sender, e):
                self.Close()

        def _Load(self,sender, e):
                #frmLogon_ = frmLogon()
                #frmLogon_.ShowDialog(self)
                frmuser_ = frmuser.frmUser()
                frmuser_.MdiParent = self
                frmuser_.Show()

        def LoadDBSetup(self,sender,e):
                frmdbsetup_ = frmdbsetup.frmDBSetup()
                frmdbsetup_.Owner = self
                #frmdbsetup_.MdiParent = self
                frmdbsetup_.ShowDialog()

        def run(self):
                WinForms.Application.Run(self)

def main():
    MainForm().run()

if __name__ == '__main__':
    main()


n = int(input())
h = list(map(int, input().split()))
ans_index = [0]

for i in range(1, n):
    if h[i] >= max(h[:i]):
        ans_index.append(i)

print(len(ans_index))
# if h[1] < h[0]:
#     h.pop(1)
#     n -= 1
# if h[2] < max(h[:2]):
#     h.pop(2)
#     n -= 1
# if h[3] < max(h[:3]):
#     h.pop(3)
#     n -= 1
# if h[4] < max(h[:4]):
#     h.pop(4)
# print(h)
# print(len(h))


import numpy as np
from flask import Flask, make_response,Response,request,jsonify,render_template,session
import cv2
import base64
import sqlite3
from keras.models import load_model

#先预测一次防止keras报错
global img
model = load_model('static/mnist.h5')
img = cv2.imread('static/img/2.png', 0)
img = cv2.resize(img, (28, 28))
img = (1 - np.array(img) / 255.0).reshape([-1, 28, 28, 1])
model.predict(img)

app = Flask(__name__)
app.config['SECRET_KEY'] = '\xf1\x92Y\xdf\x8ejY\x04\x96\xb4V\x88\xfb\xfc\xb5\x18F\xa3\xee\xb9\xb9t\x01\xf0\x96'
conn = sqlite3.connect('py.db', check_same_thread=False)
cur = conn.cursor()

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

@app.route("/register", methods=['POST'])
def register():
    data=request.get_json('data')
    name = data["name"]
    id1 = data["id"]
    password1 = data["password1"]
    password2 = data["password2"]
    major = data["major1"]
    line2="{\"result\":\""
    if name=="" or id1=="" or password1=="" or password2==""or major=="":
        line2=line2+"注册信息不完整，请重新输入"
        return line2+"\"}"
    if password1!= password2:
        line2=line2+"两次密码不一致，请重新输入"
        return line2+"\"}"
    if len(password1)<6:
        line2=line2+"密码长度至少6位"
        return line2+"\"}"
    sql = "SELECT id FROM student where id= "+id1
    cur.execute(sql)
    if cur.fetchone() is not None:
        return line2+"学号已经注册，请登陆\"}"
    sql = "insert into student (id,name,password,major) values ('%s','%s','%s','%s')"%(id1,name,password1,major)
    # sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
    # sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
    cur.execute(sql)
    conn.commit()
    return line2+"注册成功！\"}"

@app.route('/login', methods=['POST'])
def login():
    data=request.get_json('data')
    sql = "SELECT * FROM student where id= "+data['user']

    cur.execute(sql)
    result = cur.fetchone() # cursor.fetchall()
    if result[2] == data['pass']:
        session['username']=result[1]
        session['id']=result[0]
        session['major']=result[3]
       # session['time']='2019.01.01'
        return jsonify({'name': 'xmr', 'age': 's'})
    else:
        return 'error'

@app.route("/logout")
def logout():
    session.pop('username',None)
    session.pop('password',None)
    return render_template('index.html')

@app.route('/home')
def home():
    if session.get('username') is not None:
        context={
            'name':session.get('username'),
            'id': session.get('id'),
            'major': session.get('major'),
            'time': session.get('time'),
            'renwu': "s",
        }
        return render_template('home.html', **context)
    else:
        return render_template('index.html')

@app.route("/listpeople")
def listpeople():
    if session.get('username') is not None:
        return render_template('listpeople.html',name=session.get('username'))
    else:
        return render_template('index.html')

@app.route("/study_basics")
def study_basics():
    if session.get('username') is not None:
        return render_template('study_basics.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/study_imgprc")
def study_imgprc():
    if session.get('username') is not None:
        return render_template('study_imgprc.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/study_objdec")
def study_objdec():
    if session.get('username') is not None:
        return render_template('study_objdec.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/study_3d")
def study_3d():
    if session.get('username') is not None:
        return render_template('study_3d.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/imgProc")
def imgProc():
    if session.get('username') is not None:
        return render_template('imgProc.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/objdec")
def objdec():
    if session.get('username') is not None:
        return render_template('objdec.html',name=session.get('username'))
    else:
        return render_template('index.html')

@app.route("/calibration")
def calibration():
    if session.get('username') is not None:
        return render_template('calibration1.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/measure")
def measure():
    if session.get('username') is not None:
        return render_template('measure.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/down")
def down():
    if session.get('username') is not None:
        return render_template('down.html',name=session.get('username'))
    else:
        return render_template('index.html')
@app.route("/mnist1")
def mnist1():
    if session.get('username') is not None:
        return render_template('mnist.html',name=session.get('username'))
    else:
        return render_template('index.html')

@app.route('/paper')
def paper():
    context=(
        ('name1','201622362013271','name','07','name','name','5','1'),
        ('name2','201622362013271','name','07','name','name','5','2'),
    )
    return render_template('paper.html', u=context)

@app.route('/api/mnist', methods=['POST'])
def mnist():
    X = (1- np.array(request.json, dtype=np.uint8)/ 255.0).reshape([-1, 28, 28, 1])
    output=model.predict(X)[0].tolist()
    return jsonify(results=[output])

@app.route("/upload",methods=['POST'])
def uploa2d():
    global img
    arr = np.asarray(bytearray(request.files['file'].read()), dtype=np.uint8)
    img = cv2.imdecode(arr, -1)
    img=cv2.resize(img,(100,100))
    ret, jpeg = cv2.imencode('.jpg', img)
    return base64.b64encode(jpeg.tobytes())

@app.route("/gray")
def gray():
    global img
    img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret, jpeg = cv2.imencode('.jpg', img)
    return base64.b64encode(jpeg.tobytes())

@app.route("/canny")
def canny():
    global img
    img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img=cv2.Canny(img, 100, 255, 3)
    ret, jpeg = cv2.imencode('.jpg', img)
    return base64.b64encode(jpeg.tobytes())

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


# Get executables

import os
import shutil

from flaky import flaky
import pymake

from build_exes import meson_build
from framework import running_on_CI

if running_on_CI():
    print("running on CI environment")
    os.environ["PYMAKE_DOUBLE"] = "1"

# path to rebuilt executables for previous versions of MODFLOW
rebuilt_bindir = os.path.join("..", "bin", "rebuilt")

if not os.path.exists(rebuilt_bindir):
    os.makedirs(rebuilt_bindir)

# paths to downloaded for previous versions of MODFLOW
downloaded_bindir = os.path.join("..", "bin", "downloaded")

if not os.path.exists(downloaded_bindir):
    os.makedirs(downloaded_bindir)

mfexe_pth = "temp/mfexes"

# use the line below to set fortran compiler using environmental variables
# os.environ["FC"] = "gfortran"

# some flags to check for errors in the code
# add -Werror for compilation to terminate if errors are found
strict_flags = (
    "-Wtabs -Wline-truncation -Wunused-label "
    "-Wunused-variable -pedantic -std=f2008 "
    "-Wcharacter-truncation"
)

def get_compiler_envvar(fc):
    env_var = os.environ.get("FC")
    if env_var is not None:
        if env_var != fc:
            fc = env_var
    return fc

def create_dir(pth):
    # create pth directory
    print(f"creating... {os.path.abspath(pth)}")
    os.makedirs(pth, exist_ok=True)

    msg = f"could not create... {os.path.abspath(pth)}"
    assert os.path.exists(pth), msg

def rebuild_mf6_release():
    target = "mf6"
    download_pth = os.path.join("temp")
    target_dict = pymake.usgs_program_data.get_target(target)

    pymake.download_and_unzip(
        target_dict["url"],
        pth=download_pth,
        verbose=True,
    )

    # update IDEVELOP MODE in the release
    srcpth = os.path.join(
        download_pth, target_dict["dirname"], target_dict["srcdir"]
    )
    fpth = os.path.join(srcpth, "Utilities", "version.f90")
    with open(fpth) as f:
        lines = f.read().splitlines()
    assert len(lines) > 0, f"could not update {srcpth}"

    f = open(fpth, "w")
    for line in lines:
        tag = "IDEVELOPMODE = 0"
        if tag in line:
            line = line.replace(tag, "IDEVELOPMODE = 1")
        f.write(f"{line}\n")
    f.close()

    # build release source files with Meson
    root_path = os.path.join(download_pth, target_dict["dirname"])
    meson_build(dir_path=root_path, libdir=os.path.abspath(rebuilt_bindir))

def test_create_dirs():
    pths = [os.path.join("..", "bin"), os.path.join("temp")]

    for pth in pths:
        create_dir(pth)

@flaky(max_runs=3)
def test_getmfexes(verify=True):
    pymake.getmfexes(mfexe_pth, verify=verify)
    for target in os.listdir(mfexe_pth):
        srcpth = os.path.join(mfexe_pth, target)
        if os.path.isfile(srcpth):
            dstpth = os.path.join(downloaded_bindir, target)
            print(f"copying {srcpth} -> {dstpth}")
            shutil.copy(srcpth, dstpth)

@flaky(max_runs=3)
def test_rebuild_mf6_release():
    rebuild_mf6_release()

if __name__ == "__main__":
    test_create_dirs()
    test_getmfexes(verify=False)
    test_rebuild_mf6_release()


#kullanıcıdan şirket maili ve tel numarasını al, çıktı olarak aşağıdaki formata göre çıktı al

# murat.vuranok@bilgeadam.com
# 5321254151

# isim : Murat
# soyisim : Vuranok
# Telefon: +(90)532 352 0997
# Mail: murat.vuranok@bilgeadam.com

mail = input("Lütfen şirket mailinizi giriniz: ")
telefon = input("Lütfen telefon numaranızı yazınız: ")
isim = mail[:(mail.index('.'))].capitalize()
soyisim = mail[(mail.index('.')+1):(mail.index('@'))].capitalize()

print("İsim: {}\nSoyisim: {}\nTelefon: +(90){} {} {}\nMail: {}"\
    .format(isim, soyisim,telefon[:3],telefon[3:6],telefon[6:],mail))


from som.primitives.primitives import Primitives
from som.vmobjects.primitive   import Primitive
from som.vmobjects.block_bc import block_evaluate, BcBlock
from som.vm.globals import nilObject, trueObject, falseObject

from rlib import jit

def get_printable_location(interpreter, method_body, method_condition, while_type):
    from som.vmobjects.method_bc import BcMethod
    assert isinstance(method_body, BcMethod)
    assert isinstance(method_condition, BcMethod)

    return "[%s>>%s] while [%s>>%s]" % (method_condition.get_holder().get_name().get_embedded_string(),
                                        method_condition.get_signature().get_embedded_string(),
                                        method_body.get_holder().get_name().get_embedded_string(),
                                        method_body.get_signature().get_embedded_string())

jitdriver = jit.JitDriver(
    greens=['interpreter', 'method_body', 'method_condition', 'while_type'],
    reds='auto',
    # virtualizables=['frame'],
    is_recursive=True,
    get_printable_location=get_printable_location)

def _execute_block(frame, block, block_method, interpreter):
    b = BcBlock(block_method, block.get_context())
    frame.push(b)

    block_evaluate(b, interpreter, frame)
    return frame.pop()

def _while_loop(frame, interpreter, while_type):
    loop_body      = frame.pop()
    loop_condition = frame.pop()

    # universe = interpreter.get_universe()

    method_body = loop_body.get_method()
    method_condition = loop_condition.get_method()

    while True:
        jitdriver.jit_merge_point(interpreter=interpreter,
                                  method_body=method_body,
                                  method_condition=method_condition,
                                  #universe=universe,
                                  while_type=while_type)
        condition_result = _execute_block(frame, loop_condition, method_condition, interpreter)
        if condition_result is while_type:
            _execute_block(frame, loop_body, method_body, interpreter)
        else:
            break

    frame.push(nilObject)

def _while_false(ivkbl, frame, interpreter):
    _while_loop(frame, interpreter, falseObject)

def _while_true(ivkbl, frame, interpreter):
    _while_loop(frame, interpreter, trueObject)

class BlockPrimitives(Primitives):

    def install_primitives(self):
        self._install_instance_primitive(Primitive("whileTrue:",  self._universe, _while_true))
        self._install_instance_primitive(Primitive("whileFalse:", self._universe, _while_false))


import unittest
import datetime
import allure
from allure_commons.types import AttachmentType

from POM.home import Home
from POM.sms import Sms
from actions.purchase_pack import PurchasePack

from test.basetest import basetest

driver_global = None

def decorator_screenshot(func):
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except:
            allure.attach(driver_global.get_screenshot_as_png(), "Screenshot", AttachmentType.PNG)
            raise

    return wrapper

class test_MPT4U(unittest.TestCase):

    def setUp(self):
        global driver_global
        self.base = basetest()
        self.driver = driver_global = self.base.driver

    @decorator_screenshot
    def test_1_Data_Carry_Plus_pack_purchase(self):
        home = Home(self.driver)
        try:
            pass
            home.close_popups()
        except:
            pass
        print("loading app")
        home.wait_visible(home.LOCATOR_HAMBURGER)
        print("loaded")
        del home
        #PurchasePack(self.base).purchase("Data Carry Plus = 415MB [30Days]", 699, '.*',True)
        d = datetime.datetime.now() + datetime.timedelta(days=1)
        SMS=r"Success! You have subscribed to daily JOOX VIP music pack to listen to music in JOOX app.  Enjoy 120MB of JOOX data, valid till \d\d:\d\d:\d\d of {}. Click the link in the other SMS to get JOOX VIP.".format(d.strftime('%d/%m/%Y'))
        PurchasePack(self.base).purchase("120 MB JOOX Data + JOOX VIP [24 hours]", 129, SMS,True)
        sms=Sms(self.base.get_sms_app_driver())
        sms.check_sms(r"Click \{http://www\.joox\.com/mpt\?token=[0-9A-Za-z]{13,19}\} to get JOOX VIP for 24 hours",True)
        sms.check_sms(r"Dear customer, your have received 1 chance to play Hti-Pauk in MPT4U, pls note that this chance would expire in midnight 23:59:59. Click to Play now bit.ly/PlayLuckyDraw and check if you are lucky",True)

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(test_MPT4U)
    unittest.TextTestRunner().run(suite)


import requests
import simplejson
import unidecode
import operator
import json
import sys
from IPython.core.display import display, HTML
import pandas as pd
from collections import OrderedDict
from datetime import date
import random
from bs4 import *
import http.client, sys
#from Queue import Queue
from multiprocessing import Queue
# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures

async def fix_sold(range_start,range_end):

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor
            (
                executor,
                requests.get,
                df['permalink'].iloc[i],
                print ("sent ",i," ",df['permalink'].iloc[i])
            )
            for i in range(range_start,range_end)
        ]
        for response in await asyncio.gather(*futures):
            sold = retrieve_sold_from_text(response.text)
            print ("returned sold ",sold," from ",response.url)
            for index, row in df[range_start:range_end].iterrows():
                if str(df.loc[index,'permalink']) in response.url:
                    print (df.loc[index,'title'])
                    df.loc[index,'sold_new'] = sold

def retrieve_sold_from_link(link):
    r = requests.get(link)
    soup = BeautifulSoup(r.text)
    text_soup = soup.prettify()
    split_text = text_soup.split('\n')
    for num in range(0,len(split_text)):
        if ( '\tvendidos' in split_text[num]):
            return int(split_text[num - 1])
def retrieve_sold_from_text(text):
    soup = BeautifulSoup(text)
    text_soup = soup.prettify()
    split_text = text_soup.split('\n')
    for num in range(0,len(split_text)):
        if ( '\tvendidos' in split_text[num]):
            return int(split_text[num - 1])

def path_to_image_html(path):
    '''
     This function essentially convert the image url to
     '' format. And one can put any
     formatting adjustments to control the height, aspect ratio, size etc.
     within as in the below example.
    '''

    return ''

def path_to_link_html(path):
    '''
     This function essentially convert the image url to
     '' format. And one can put any
     formatting adjustments to control the height, aspect ratio, size etc.
     within as in the below example.
    '''

    return 'link'

def check_ALL_list_in_title(list,string ):
# ALL NEEDS TO MATCH
    result = 1
    for item in list:
        if item.lower() in string.lower():
            result = 1
        else:
            result = 0
    return result

def check_ANY_list_in_title(list,string ):
# ANY NEEDS TO MATCH
    result = 0
    for item in list:
        #print ("item:",item,"str:",string)
        if item.lower() in string.lower() :
            result = 1
    return result

def search_mla_return_list(product,min_price,max_price,category):
    #print ("Returning complete MLA list for product",product)
    link = 'https://api.mercadolibre.com/sites/MLA/search?q=\'' + product + '\'' + '&category=' + category
    price_filter = "&price=" + str(min_price) + "-" + str(max_price)
    link2 = link + '&offset=' + str(0) + '&limit=' + str(50) + price_filter
    r = requests.get(link2)
    #print (link2)
    c = r.json()
    #print (c['results'][0])
    c_orig = c
    c_partial = c['results']
    #print (c_partial)
    start =  c['paging']['offset']
    end =  c['paging']['limit']
    total =  c['paging']['total']
    total_saved = total
    total_c = c['results']
    maximum_sell = 0
    #print ("Total found:",total," (limited to 1k no token) start:",start," end ",end," , range: ",min_price,"-",max_price)
    if total > 1000:
        total = 1000
    # TEMOPORARY
    num_new = 0
    num=0
    num_new = 0
    while ( total > 51 and end > 10 ): # and 0):  ## <--- full list instead of first 50
        start = start + end
        #print (start,"..",end='')
        if ( (c['paging']['total'] - start) < end  ):
            end = c['paging']['total'] - 1 - start
        link2 = link + '&offset=' + str(start) + '&limit=' + str(end) + price_filter
        #print ("requesting LINK:",link2)
        r = requests.get(link2)
        c = r.json()
        c_partial = 0
        #print ("Total:",c['paging']['total']," start:",start," limit ",end)
        total_c = total_c + c['results']
        total = total - end
        num = num + 1
    return total_c

def return_max_sold_from_list(list,product,min_price,max_price):
    #print ("----- Searching max sold...");
    product_list = product.split()
    maximum_sell = 0
    num_new = 0
    for x in list[:]:
        #print(c['site_id'], c['results']['title'],c['results']['sold_quantity'], "$",c['results']['price'],c['site_id'], c['results']['address']['city_name'])
        sold_qty = list[num_new]['sold_quantity']
        price = list[num_new]['price']
        #print ("sold qty",sold_qty,"num:",num)
        title = unidecode.unidecode(list[num_new]['title']).lower()
        if ( sold_qty > maximum_sell and check_ALL_list_in_title(product_list,title ) and not check_ALL_list_in_title(product_to_avoid.split(),title ) and ( int(price) >= int(min_price) and int(price) <= int(max_price) )):
            maximum_sell = sold_qty
            #print ("new max sell found",maximum_sell)
        num_new = num_new + 1
    #print ("....max units sold at this range: ",maximum_sell)
    return maximum_sell

def return_tuples_from_list(list,product,min_price,max_price):
    print ("----- Searching maximum units sold...")
    product_list = product.split()
    maximum_sell = 0
    num_new = 0
    for x in list[:]:
        #print(c['site_id'], c['results']['title'],c['results']['sold_quantity'], "$",c['results']['price'],c['site_id'], c['results']['address']['city_name'])
        sold_qty = list[num_new]['sold_quantity']
        price = list[num_new]['price']
        title = list[num_new]['title']
        title_list = title.split()
        title_short = title_list[0:3]
        #print ("Title short:",title_short)
        #print ("sold qty",sold_qty,"num:",num)
        title = unidecode.unidecode(list[num_new]['title']).lower()
        if ( sold_qty > maximum_sell and check_ALL_list_in_title(product_list,title ) and not check_ALL_list_in_title(product_to_avoid.split(),title ) and ( int(price) >= int(min_price) and int(price) <= int(max_price) )):
            maximum_sell = sold_qty
            #print ("Title short:",title_short)
            #print ("new max sell found",maximum_sell)
        num_new = num_new + 1
    return maximum_sell

def return_products_from_list_pandas(total_c,product,condition,min_price,max_price):
    from operator import itemgetter
    import pandas as pd
    num = 0
    list_new = list()
    product_list = product.split()
    df = pd.DataFrame.from_dict(total_c)
    if (len(df)>0):
        df_temp = pd.DataFrame()
        df_temp = df.loc[:, ['title', 'price','sold_quantity','address','thumbnail','permalink','shipping','seller']].sort_values('sold_quantity',ascending=False)
        df_temp['city'] = df_temp['address'].apply(lambda x: x.get('city_name'))
        df_temp['seller_id'] = df_temp['seller'].apply(lambda x: x.get('id'))
        df_temp['free_shipping'] = df_temp['shipping'].apply(lambda x: x.get('free_shipping'))
        df_temp['state'] = df_temp['address'].apply(lambda x: x.get('state_name'))

        df_temp['total'] = df['price'] * df['sold_quantity']
        df_temp['title'] = df['title'].str.lower()
        return df_temp
    return ''

def display_product_old(product,min_price_list,max_price_list,sell_condition,percentage_max_sell,category,total):
    num = 0
    df_temp = ''
    df_temp = pd.DataFrame.from_dict([])
    for price in min_price_list:
        min_price = min_price_list[num]
        max_price = max_price_list[num]
        mla_list = search_mla_return_list(product,min_price,max_price,category)
        ranger = '$' + str(min_price) + '-$' + str(max_price)
        df = return_products_from_list_pandas(mla_list,product,sell_condition,min_price,max_price)

        for num2 in range(0,len(df)):
            df_value = df.iloc[num2]
            if ( float(df_value['total']) > total ):
                df_temp = df_temp.append(df_value, ignore_index=True)
        if ( len(df_temp)>0):
             a=1
        num = num + 1
    return df_temp

def display_product(product, min_price_list, max_price_list, sell_condition, percentage_max_sell, category, total):
    df_temp = pd.DataFrame()

    for min_price, max_price in zip(min_price_list, max_price_list):
        mla_list = search_mla_return_list(product, min_price, max_price, category)
        ranger = '$' + str(min_price) + '-$' + str(max_price)
        df = return_products_from_list_pandas(mla_list, product, sell_condition, min_price, max_price)

        try:
            df['total'] = pd.to_numeric(df['total'], errors='coerce')

            mask = df['total'] > total
            df_filtered = df[mask]

            if not df_filtered.empty:
                if df.empty:
                    df = df_filtered.copy()
                else:
                    df = pd.concat([df_temp, df_filtered])
        except:
            pass

    return df

def return_products_from_list_in_locations_pandas(total_c,product,sell_condition,locations,min_sell,min_price,max_price):
    #print ("----- Printing products from list in LOCATION..min $:",min_price," max $:",max_price)
    #sorted(total_c, key=lambda sold_quantity: sold_quantity[8])
    #sorted(total_c, key=operator.itemgetter(16) )
    df = pd.DataFrame.from_dict(total_c)
    df_resu = pd.DataFrame()
    df_temp = df.loc[:, ['total','title', 'price','sold_quantity','address','thumbnail','permalink']].sort_values('sold_quantity',ascending=False)
    df_temp['city'] = df_temp['address'].apply(lambda x: x.get('city_name'))
    df_temp['state'] = df_temp['address'].apply(lambda x: x.get('state_name'))
    df_temp2['title'] = df_temp2['title'].str.lower()

    for palabra in product.split(' '):
        df_temp2 = df_temp2[ df_temp2['title'].str.contains(palabra)]
        df_resu = df_resu.concat([df_resu,df_temp2])
    df_temp2 = df_resu[ df_resu['city'].str.contains(locations)]
    return df_temp2


from django.shortcuts import render
from django.http import HttpResponse
from .models import user_info
from .Recommender import Recommender
from sklearn.externals import joblib
import pickle
import csv
import sys
import reverse_geocoder as rg
import pprint
import geocoder
from math import cos, asin, sqrt
from collections import defaultdict
from geopy.geocoders import Nominatim
import googlemaps
def getPlaceName(coordinate):
  result = rg.search(coordinate)
  # result is a list containing ordered dictionary.
  pprint.pprint(result)
  return result

def getDistance(dest_coor):
  print(dest_coor)
  lat1,lon1=23.7593572,90.3788136
  lat2,lon2=dest_coor
  p = 0.017453292519943295     #Pi/180
  a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
  return 12742 * asin(sqrt(a))

def getTravelTime(distance,travel_speed):

    return distance/travel_speed

def getName(coordinate):
  geolocator = Nominatim(user_agent="wheretogo")
  location = geolocator.reverse(coordinate)
  return location.address
def predict(id):
  with open('assets/mysite/images/recommender_model.pkl','rb') as file:
      sys.modules['Recommender']=Recommender
      model=joblib.load(file)
      place_id=model.predict(id)
      print(place_id)
      location=model.getLocationInfo()
      all_place_info=list()
      index=0
      for pid in place_id:
        print("Myid: ", pid)
        #name=getName(location[index])
        name=getPlaceName(location[pid])
        #x=name.split(',')
        single_place_info=defaultdict(list)
        distance=getDistance(location[pid])
        travel_time=getTravelTime(distance,40)
        lat,lng=location[pid]
        single_place_info['lat']=lat
        single_place_info['lng']=lng
        single_place_info['place_id']=pid
        single_place_info['place_name']=name[0]['name']
        single_place_info['country']=name[0]['cc']
        #single_place_info['place_name']=str(x[0])+","+str(x[1])+","+str(x[2])
        #single_place_info['country']=x[len(x)-1]
        single_place_info['distance']=distance
        single_place_info['travel_time']=travel_time
        all_place_info.append(single_place_info)
        index+=1
        #print("Distance:",getDistance(location[0]),"KM","Travel Time:",travel_time,"hours")
        #print(all_place_info)
      user={"all_place_info":all_place_info,
            "coors":location}
      return user

def home_view(request,*arg,**kwargs):

    user=predict(80)
    return render(request,'home.html',user)

def recommendation(request,*arg,**kwargs):
    id=int(request.POST['id'])
    user=predict(id)
    return render(request,'home.html',user)

def sign_in(request,*arg,**kwargs):

  return render(request,'sign_in.html')
def sign_up(request,*arg,**kwargs):

  return render(request,'sign_up.html')


import sys
from test import PASH_TOP
sys.path.append(PASH_TOP)
from scripts.test_eval.logparser import LogParser, DEFAULT_LOG_FOLDER
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sys import argv
import os

def plot_barchart(df, y_axis="exec_time", test_names=None, save_file="output.png"):
    if test_names is not None:
        df = df[df["test_name"].isin(test_names)]
        labels = sorted(test_names)
    else:
        labels = sorted(df.test_name.unique())

    x = np.arange(len(labels))  # the label locations
    width = 0.2  # the width of the bars

    r_split = df[(df.split_type == "r-split") & (df.no_eager == False)]
    r_split_no_eager = df[(df.split_type == "r-split") & (df.no_eager == True)]
    auto_split = df[(df.split_type == "auto-split") & (df.no_eager == False)]
    auto_split_no_eager = df[(df.split_type == "auto-split") & (df.no_eager == True)]

    r = []
    rn = []
    a = []
    an = []
    error_r = []
    error_rn = []
    error_a = []
    error_an = []

    for label in labels:
        r.append(r_split.loc[r_split["test_name"] == label][y_axis].min())
        rn.append(r_split_no_eager.loc[r_split_no_eager["test_name"] == label][y_axis].min())
        a.append(auto_split.loc[auto_split["test_name"] == label][y_axis].min())
        an.append(auto_split_no_eager.loc[auto_split_no_eager["test_name"] == label][y_axis].min())

        error_r.append(r_split.loc[r_split["test_name"] == label][y_axis].max() - r[-1])
        error_rn.append(r_split_no_eager.loc[r_split_no_eager["test_name"] == label][y_axis].max() - rn[-1])
        error_a.append(auto_split.loc[auto_split["test_name"] == label][y_axis].max() - a[-1])
        error_an.append(auto_split_no_eager.loc[auto_split_no_eager["test_name"] == label][y_axis].max() - an[-1])

    fig, ax = plt.subplots(figsize=(20,10))
    rects1 = ax.bar(x - 3/2*width, r, width, yerr=error_r, label='r-split')
    rects2 = ax.bar(x - 1/2*width, rn, width, yerr=error_rn, label='r-split-no-eager')
    rects3 = ax.bar(x + 1/2*width, a, width, yerr=error_a, label='auto-split')
    rects4 = ax.bar(x + 3/2*width, an, width, yerr=error_an, label='auto-split-no-eager')

    # Add some text for labels, title and custom x-axis tick labels, etc.
    ax.set_ylabel('ms')
    # ax.set_title('')
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    plt.xticks(rotation=90)
    ax.legend()

    fig.savefig(save_file)

#This function only compares between folders
#dfs is tuple: (df_name, pd.df)
def plot_barchart_against(dfs: list, y_axis="exec_time", test_names=None, save_file="output.png"):
    print(test_names)
    df1 = dfs[0][1]
    if test_names is not None:
        df1 = df1[df1["test_name"].isin(test_names)]
        labels = sorted(test_names)
    else:
        labels = sorted(df1.test_name.unique())

    x = np.arange(len(labels))  # the label locations
    width = 1/(len(dfs))*4/5  # the width of the bars

    rects = []
    for df_name, df in dfs:
        df = df[(df.split_type == "r-split") & (df.no_eager == False) & (df.dgsh_tee == True)]
        rects.append(df)

    bar_height = [[] for i in range(len(rects))]
    error_height = [[] for i in range(len(rects))]

    for label in labels:
        for i, rect in enumerate(rects):
            try:
                bar_height[i].append(rect.loc[rect["test_name"] == label][y_axis].mean())
                error_height[i].append(rect.loc[rect["test_name"] == label][y_axis].std())
            except:
                print("plot_shart_against: failed: ", label)

    fig, ax = plt.subplots(figsize=(20,10))
    for i in range(len(dfs)):
        label = ""
        df_name = dfs[i][0]
        offset = (i -  int(len(dfs)/2))
        if len(dfs)%2 == 0:
            offset += 1/2
        print(offset)
        ax.bar(x + offset*width, bar_height[i], width, yerr=error_height[i], label=label+df_name)

    # Add some text for labels, title and custom x-axis tick labels, etc.
    ax.set_ylabel('ms')
    # ax.set_title('')
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    plt.xticks(rotation=90)
    ax.legend()

    fig.savefig(save_file)

if __name__ == '__main__':
    #sample execution

    log_dfs = []
    if len(argv) > 1:
        for folder in argv[1:]:
            log_parser = LogParser()
            df = log_parser.parse_folder(folder)
            log_dfs.append((folder, df))
    # parse more directories if needed
    # df = log_parser.parse_folder("tmp2_1G_width4bbackup")

    plot_barchart_against(log_dfs, save_file="compare" + ".png")


import re, argparse
from smartcard.System import readers
import datetime, sys
import requests
import urllib
import json
from smartcard.CardType import AnyCardType
from smartcard.CardRequest import  CardRequest
from smartcard.util import toHexString
url_prefix="http://certificateweb.sumato.tech/api/v1/"
url_all_certs_init=url_prefix+"studentsall"
url_all_certs_complete=url_prefix+"students/print/completed"
url_cert_status=url_prefix+"print/status/"
url_cert_pdf=url_prefix+"print/pdf/"#provide certificate id
url_update_cert_complete=url_prefix+"print/complete/" #provide certificate id
COMMAND = [0xFF, 0xCA, 0x00, 0x00, 0x00] #handshake cmd needed to initiate data transfer
LOAD_AUTH_KEY=[0xFF,0x82,0x00,0x00,0x06,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]#Load authentication key
AUTHENTICATE_COMMAND=[0xFF, 0x88, 0x00, 0x04, 0x60, 0x00]#authenticate
# get all the available readers
r = readers()
print ("Available readers:", r)
reader=r[0]

def getCertificateListInit():
    r=requests.get(url_all_certs_init)
    students=r.json()
    return students
def getCertPdf(certId):
    urllib.request.urlretrieve(url_cert_pdf+certId,"cert_"+certId+".pdf")
    return 1
def updateCertComplete(certId):
    r.requests.get(url_update_cert_complete+certId)
    return 1

def authenticate():
    connection = reader.createConnection()
    status_connection = connection.connect()
    connection.transmit(COMMAND)
    #Read command [FF, B0, 00, page, #bytes]
    resp=connection.transmit(LOAD_AUTH_KEY)
    if resp[1]==144:
        print("Authentication key loaded")
    else:
        print("Problem loading auth key "+resp)
    resp=connection.transmit(AUTHENTICATE_COMMAND)
    if resp[1]==144:
        print("Authentication done")
    else:
        print("Problem while authenticating "+str(resp))

def readTag(page):
            connection = reader.createConnection()
            status_connection = connection.connect()
            connection.transmit(COMMAND)
            #Read command [FF, B0, 00, page, #bytes]
            resp = connection.transmit([0xFF, 0xB0, 0x00, 0x04, 0x04])
            if resp[1]==144:
                print(resp)
            else:
                print("Couldnt read "+resp)
           # dataCurr = stringParser(resp)

            #only allows new tags to be worked so no duplicates

def writeTag(value):
                page=4
                cardtype=AnyCardType()
                cardreq=CardRequest(timeout=100, cardType=cardtype)
                cardservice=cardreq.waitforcard()
                cardservice.connection.connect()
                print(toHexString(cardservice.connection.getATR()))
                WRITE_COMMAND = [0xFF,0xD6,0x00,0x04,0x04,int(value[0:2],16),int(value[2:4],16),int(value[4:6],16),int(value[6:8],16)]
                print(WRITE_COMMAND)
                #[0xFF, 0xD6, 0x00, int(page), 0x04, int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16), int(value[6:8], 16)]
                #Let's write a page Page 9 is usually 00000000
                #resp = cardservice.connection.transmit(AUTHENTICATE_COMMAND)
                #print(resp)
                resp = cardservice.connection.transmit(WRITE_COMMAND)
                print(resp)
                if resp[1] == 144:
                    print ("Wrote " + str(value))
                else:
                    print("Error occured during write operation")
def printToNfc(data):
    #authenticate()
    writeTag(data)

certs=getCertificateListInit()
print(certs[0]['printjob']['certificate_id'])
for cert in certs:
    cert_id=cert['printjob']['certificate_id']
    print(cert_id)
    printToNfc(cert_id)
    getCertPdf(cert['printjob']['certificate_id'])
readTag(4)
#getCertPdf('9315224')


# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:

前后词互信息PMI: 计算两个词语之间的关联程度，pmi越大越紧密
左右邻熵：左右熵值越大，说明该词的周边词越丰富，意味着词的自由程度越大，其成为一个独立的词的可能性也就越大。
"""

import os
import re
from collections import Counter

import numpy as np

from wordrank import config
from wordrank.utils.io_utils import save_json, load_json
from wordrank.utils.logger import logger

def ngram_freq(text, ngram=4):
    """
    Get Ngram freq dict
    :param text: input text, sentence
    :param ngram: N
    :return: word frequency dict
    """
    words = []
    for i in range(1, ngram + 1):
        words += [text[j:j + i] for j in range(len(text) - i + 1)]
    words_freq = dict(Counter(words))
    return words_freq

def generate_pmi_score(word_freq_dict, pmi_path):
    """
    Generate PMI score
    :param word_freq_dict: dict
    :return: dict(word, float), pmi score
    """
    result = dict()
    for word in word_freq_dict:
        if len(word) > 1:
            p_x_y = min([word_freq_dict.get(word[:i]) * word_freq_dict.get(word[i:]) for i in range(1, len(word))])
            score = p_x_y / word_freq_dict.get(word)
            result[word] = score
    save_json(result, pmi_path)
    return result

def entropy_score(char_list):
    """
    Get entropy score
    :param char_list: input char list
    :return: float, score
    """
    char_freq_dict = dict(Counter(char_list))
    char_size = len(char_list)
    entropy = -1 * sum([char_freq_dict.get(i) / char_size * np.log2(char_freq_dict.get(i) / char_size)
                        for i in char_freq_dict])
    return entropy

def generate_entropy_score(word_freq_dict, text, entropy_path):
    """
    Generate entropy score
    :param word_freq_dict: dict
    :param text: input text, document
    :param entropy_path: save entropy file path
    :return: dict
    """
    result = dict()
    for word in word_freq_dict:
        if len(word) == 1:
            continue
        # pass error pattern
        if '*' in word:
            continue
        try:
            left_right_char = re.findall('(.)%s(.)' % word, text)
            left_char = [i[0] for i in left_right_char]
            left_entropy = entropy_score(left_char)

            right_char = [i[1] for i in left_right_char]
            right_entropy = entropy_score(right_char)
            if left_entropy > 0 or right_entropy > 0:
                result[word] = [left_entropy, right_entropy]
        except Exception as e:
            logger.error('error word %s, %s' % (word, e))
    save_json(result, entropy_path)
    return result

class PMI(object):
    def __init__(self,
                 text='',
                 ngram=4,
                 pmi_path=config.pmi_path,
                 entropy_path=config.entropy_path
                 ):
        if os.path.exists(pmi_path) and os.path.exists(entropy_path):
            self.pmi_score_dict = load_json(pmi_path)
            self.entropy_score_dict = load_json(entropy_path)
        elif len(text.strip()) > 0:
            words_freq = ngram_freq(text, ngram)
            self.pmi_score_dict = generate_pmi_score(words_freq, pmi_path)
            self.entropy_score_dict = generate_entropy_score(words_freq, text, entropy_path)
        else:
            raise ValueError("text and saved file path must exist one")

    def pmi_score(self, word):
        """
        Get PMI score
        :param word:
        :return:
        """
        return self.pmi_score_dict.get(word, 0.0)

    def entropy_score(self, word):
        """
        Get entropy score
        :param word:
        :return:
        """
        return self.entropy_score_dict.get(word, [0.0, 0.0])


import numpy as np
# C++ version of multiview triangulation
# void MultiCameraReconstructor::multiCamsDLT(const VecEP3f& controlPts, const std::vector<Eigen::Matrix4f>& controlMats, Eigen::Matrix<float, 3, 1>& X)
# {
# 	int numConstraints = controlPts.size();
# 	Eigen::MatrixXf A, b;
# 	if (numConstraints >= 2)
# 	{
# 		A.resize(2 * numConstraints, 4);
#
# 		for (size_t iC = 0; iC < numConstraints; iC++)
# 		{
# 			A.row(iC * 2) = controlPts[iC](0, 0) * controlMats[iC].row(2) - controlMats[iC].row(0);
# 			A.row(iC * 2 + 1) = controlPts[iC](1, 0) * controlMats[iC].row(2) - controlMats[iC].row(1);
# 		}
#
# 		b = -A.block(0, 3, 2 * numConstraints, 1);
# 		Eigen::MatrixXf AA = A.block(0, 0, 2 * numConstraints, 3);
#
# 		X = AA.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);
# 	}
# 	else
# 	{
# 		X << 0, 0, -1;
# 	}
# 	return ;
# }

def projectPoints(points, projMat):
    pts2D = []
    for iV in range(points.shape[0]):
        p3D = points[iV, :]
        p3DH = np.vstack([p3D.reshape(3, 1), 1])

        ptsP = projMat @ p3DH
        ptsP = ptsP / ptsP[2]

        # print(ptsP)
        pts2D.append(ptsP[:2, 0])

    pts2D = np.array(pts2D)

    return pts2D

def mulCamsDLT(controlPts, camProjMats):
    numConstraints = len(controlPts)
    A = np.zeros((2*numConstraints, 4))

    if numConstraints >= 2:
        for iCam in range(numConstraints):
            A[2*iCam, :] = controlPts[iCam][0] * camProjMats[iCam][2, :] - camProjMats[iCam][0, :]
            A[2*iCam + 1, :] = controlPts[iCam][1] * camProjMats[iCam][2, :] - camProjMats[iCam][1, :]
        b = -A[:, 3]

        AA = A[:, :3]
        X = np.linalg.lstsq(AA, b)[0]

        reprojErrs = []
        for iCam in range(numConstraints):
            p3DH = np.vstack([X.reshape(3, 1), 1])

            ptsP = camProjMats[iCam] @ p3DH
            ptsP = ptsP / ptsP[2]

            err = np.sqrt((controlPts[iCam][0] - ptsP[0])**2 + (controlPts[iCam][1] - ptsP[1])**2 )

            reprojErrs.append(err)

    else:
        print("Need at least 2 constraints")
        assert False

    return X, np.array(reprojErrs)


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 17:55:39 2021

@author: AAKASH
"""
from flask import Flask, render_template, request
import jsonify
import requests
import pickle
import numpy as np
import sklearn
from sklearn.preprocessing import StandardScaler
app = Flask(__name__)
model = pickle.load(open('linear_regression_model.pkl', 'rb'))
@app.route('/',methods=['GET'])
def Home():
    return render_template('index.html')

standard_to = StandardScaler()
@app.route("/predict", methods=['POST'])
def predict():
    #Fuel_Type_Diesel=0
    if request.method == 'POST':

        km_driven=int(request.form['km_driven'])

        ex_showroom_price=float(request.form['ex_showroom_price'])

        Year = int(request.form['year'])

        name=request.form['name']
        if(name=='Hero'):
            name_Hero=1
            name_Honda=0
            name_Royal = 0
            name_Suzuki = 0
            name_TVS = 0
            name_Yamaha = 0
        elif(name=='Honda'):
            name_Hero=0
            name_Honda=1
            name_Royal = 0
            name_Suzuki = 0
            name_TVS = 0
            name_Yamaha = 0
        elif(name=='Yamaha'):
            name_Hero=0
            name_Honda=0
            name_Royal = 0
            name_Suzuki = 0
            name_TVS = 0
            name_Yamaha = 1
        elif(name=='Royal'):
            name_Hero=0
            name_Honda=0
            name_Royal = 1
            name_Suzuki = 0
            name_TVS = 0
            name_Yamaha = 0
        elif(name=='TVS'):
            name_Hero=0
            name_Honda=0
            name_Royal = 0
            name_Suzuki = 0
            name_TVS = 1
            name_Yamaha = 0
        elif(name=='Suzuki'):
            name_Hero=0
            name_Honda=0
            name_Royal = 0
            name_Suzuki = 1
            name_TVS = 0
            name_Yamaha = 0
        else:
            name_Hero=0
            name_Honda=0
            name_Royal = 0
            name_Suzuki = 0
            name_TVS = 0
            name_Yamaha = 0

        Seller_Type=request.form['seller_type_Individual']
        if(Seller_Type=='Individual'):
            Seller_Type_Individual=1
        else:
             Seller_Type_Individual=0

                 # Present_Price=float(request.form['Present_Price'])

       # Kms_Driven2=np.log(Kms_Driven)
        Owner=request.form['owner']
        if(Owner=='First Owner'):
            owner_second=0
            owner_third=0
        elif(Owner=='Second Owner'):
            owner_second=1
            owner_third=0
        elif(Owner=='Third Owner'):
            owner_second=0
            owner_third=1

        Year=2021-Year

        prediction=model.predict([[km_driven,ex_showroom_price,Year,name_Hero,name_Honda,name_Royal,name_Suzuki,name_TVS,name_Yamaha,Seller_Type_Individual,owner_second,owner_third]])
        output=round(prediction[0],2)
        if output<0:
            return render_template('index.html',prediction_text="Sorry you cannot sell this bike")
        else:
            return render_template('index.html',prediction_text="You Can Sell The bike at {}".format(output))
    else:
        return render_template('index.html')

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


#!/usr/bin/env python

import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)

#Define Relay outputs R1-Lights, R2-Compressor, R3-UV
R1 = 22
R2 = 27
R3 = 17

GPIO.setmode(GPIO.BCM)

# Setup GPIO pins
GPIO.setup(R1, GPIO.OUT)
GPIO.setup(R2, GPIO.OUT)
GPIO.setup(R3, GPIO.OUT)

while True:

    dt = list(time.localtime())
    hour = dt[3]
    minute = dt[4]
    second = dt[5]
    time.sleep(1)
    print (hour, ":", minute, ":", second);

    if (hour >= 0 and hour < 8):
        GPIO.output(R1, GPIO.HIGH)
        GPIO.output(R2, GPIO.HIGH)
        GPIO.output(R3, GPIO.HIGH)
        print ("Lights are OFF, Compressor is OFF, UV is OFF");

    if (hour >= 8 and hour < 22):
        GPIO.output(R1, GPIO.LOW)
        GPIO.output(R2, GPIO.HIGH)
        GPIO.output(R3, GPIO.HIGH)
        print ("Lights are ON, Compressor is OFF, UV is OFF");

    if (hour >= 22 and hour < 24):
        GPIO.output(R1, GPIO.HIGH)
        GPIO.output(R2, GPIO.LOW)
        GPIO.output(R3, GPIO.HIGH)
        print ("Lights are OFF Compressor is ON, UV is OFF");


# -*- coding: utf-8 -*-
"""
Created on Sat Jul 25 19:00:10 2020

@author: Josh Burkey & Ivan Ahumada
based on code by arun prakash
https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e

"""

import cv2
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
import tensorflow as tf
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.models import Model
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import *
from keras.applications.vgg16 import VGG16

#declare folders with the data and where the model is saved.#
model_weights_path = 'model'
train_data = 'train'
test_data = 'test'

#initialize classes and label split labels for identification#
def one_hot_label(img):
    label = img.split('.')[0]
    if label == 'antelope':
        ohl = np.array([1,0,0,0,0,0])
    elif label == 'bobcat':
        ohl = np.array([0,1,0,0,0,0])
    elif label == 'buffalo':
        ohl = np.array([0,0,1,0,0,0])
    elif label == 'chimpanzee':
        ohl = np.array([0,0,0,1,0,0])
    elif label == 'rhinoceros':
        ohl = np.array([0,0,0,0,1,0])
    elif label == 'wolf':
        ohl = np.array([0,0,0,0,0,1])
    return ohl

#pull in the training images and labels, resize and shuffle them#
def train_data_with_label():
    train_images = []
    for i in tqdm(os.listdir(train_data)):
        path = os.path.join(train_data, i)
        img = cv2.imread(path, cv2.IMREAD_COLOR)
        img = cv2.resize(img, (200, 200))
        train_images.append([np.array(img), one_hot_label(i)])
        shuffle(train_images)
    return train_images

#pull in testing images and labels, resize and shuffle them#
def test_data_with_label():
    test_images = []
    for i in tqdm(os.listdir(test_data)):
        path = os.path.join(test_data, i)
        img = cv2.imread(path, cv2.IMREAD_COLOR)
        img = cv2.resize(img, (200, 200))
        test_images.append([np.array(img), one_hot_label(i)])
        shuffle(test_images)
    return test_images

training_images = train_data_with_label()
testing_images = test_data_with_label()

#establish arrays for processing by model and training during network#
#compilation, establish sizes and color mode (3 for color)#
tr_img_data = np.array([i[0] for i in training_images]).reshape(-1,200,200,3)
tr_lbl_data = np.array([i[1] for i in training_images])

tst_img_data = np.array([i[0] for i in testing_images]).reshape(-1,200,200,3)
tst_lbl_data = np.array([i[1] for i in testing_images])

#pull in VGG16 pretrained model#
IMG_SHAPE = (200,200,3)
base_model = VGG16(input_shape = IMG_SHAPE,include_top = False,weights = 'imagenet')
base_model.trainable = False

#callback saves the model after each epoch#
checkpoint_callback = ModelCheckpoint(filepath=model_weights_path+"/"+'best_model.h5', verbose=1,
                                      save_best_only=False, include_optimizer=False, mode='max')

#establish model parameters and import pretrained model#
model = Sequential()
model.add(base_model)

#add input layer and first convolution and pooling layer#
model.add(InputLayer(input_shape=[200,200,3]))
model.add(Conv2D(filters=32,kernel_size=5,strides=1,padding='same', activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

#add second convolution layer and pooling layer#
model.add(Conv2D(filters=50,kernel_size=5,strides=1,padding='same', activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

#add third convolution layer and pooling layer#
model.add(Conv2D(filters=80,kernel_size=5,strides=1,padding='same', activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

#establish neural network layers#
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(6,activation='softmax'))

optimizer = Adam(lr=1e-3)

#compile model, epochs and batch_size were established through testing#
model.compile(optimizer = optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x=tr_img_data,y=tr_lbl_data,epochs=30,batch_size=100, callbacks = [checkpoint_callback])
model = Model(model.input,model.output)
model.summary()

#establish plot for test data#
fig = plt.figure(figsize=(14, 14))
#run testing phase going through first 30 images in the testing image set#
for cnt, data, in enumerate(testing_images[10:40]):

    y = fig.add_subplot(6, 5, cnt+1)
    img = data[0]
    data = img.reshape(1,200, 200,3)
    model_out = model.predict([data])

    if np.argmax(model_out) == 0:
        str_label='antelope'
    elif np.argmax(model_out) == 1:
        str_label='bobcat'
    elif np.argmax(model_out) == 2:
        str_label='buffalo'
    elif np.argmax(model_out) == 3:
        str_label='chimpanzee'
    elif np.argmax(model_out) == 4:
        str_label='rhinoceros'
    elif np.argmax(model_out) == 5:
        str_label='wolf'

#plot test output from neural network model post training for visual check of accuracy#
    y.imshow(img, cmap='gray')
    plt.title(str_label)
    print(str_label)
    y.axes.get_xaxis().set_visible(False)
    y.axes.get_yaxis().set_visible(False)
plt.show()
#convert model to tflite format for use in android studio#
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
open(model_weights_path + "/" + 'img_rec_model.tflite', 'wb').write(tflite_model)


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'download/$',                   views.download_csv, name='user_download'),
    url(r'^edit/(?P<user_id>[0-9]+)/$',   views.update,  name='user_edit'),
    url(r'^delete/(?P<user_id>[0-9]+)/$', views.delete,  name='user_delete'),
    url(r'^add/$',                        views.create,  name='user_add'),
    url(r'^(?P<user_id>[0-9]+)/$',        views.read,    name='user_show'),
    url(r'^$',                            views.list_all,name='user_list'),
]


# SConstruct for src/pool

# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

Import('sched_env')

lib_name='scheduler_xml'

if sched_env['parsers']=='yes':
    # LEX
    parser=sched_env.Lex(
        source='expr_parser.l'
    )
    sched_env.NoClean(parser)

    # BISON
    parser=sched_env.Bison(
        source='expr_arith.y'
    )
    sched_env.NoClean(parser)

    parser=sched_env.Bison(
        source='expr_bool.y'
    )
    sched_env.NoClean(parser)

source_files=['ObjectXML.cc',
              'Client.cc',
              'expr_parser.c',
              'expr_bool.cc',
              'expr_arith.cc']

# Build library
sched_env.StaticLibrary(lib_name, source_files)


import pytest
import task_17_3
import sys

sys.path.append("..")

from common_functions import check_function_exists

# Проверка что тест вызван через pytest ..., а не python ...
from _pytest.assertion.rewrite import AssertionRewritingHook

if not isinstance(__loader__, AssertionRewritingHook):
    print(f"Тесты нужно вызывать используя такое выражение:\npytest {__file__}\n\n")

def test_function_created():
    """
    Проверка, что функция создана
    """
    check_function_exists(task_17_3, "parse_sh_cdp_neighbors")

def test_function_return_value():
    """
    Проверка работы функции
    """
    with open("sh_cdp_n_sw1.txt") as f:
        sh_cdp_n_sw1 = f.read()

    correct_return_value = {
        "SW1": {
            "Eth 0/1": {"R1": "Eth 0/0"},
            "Eth 0/2": {"R2": "Eth 0/0"},
            "Eth 0/3": {"R3": "Eth 0/0"},
            "Eth 0/4": {"R4": "Eth 0/0"},
        }
    }

    return_value = task_17_3.parse_sh_cdp_neighbors(sh_cdp_n_sw1)
    assert return_value != None, "Функция ничего не возвращает"
    assert (
        type(return_value) == dict
    ), f"По заданию функция должна возвращать словарь, а возвращает {type(return_value).__name__}"
    assert (
        return_value == correct_return_value
    ), "Функция возвращает неправильное значение"

def test_function_return_value_different_args():
    """
    Проверка работы функции на другом выводе
    """
    with open("sh_cdp_n_sw1.txt") as f:
        sh_cdp_n_sw1 = f.read()

    correct_return_value = {
        "SW1": {
            "Eth 0/1": {"R1": "Eth 0/0"},
            "Eth 0/2": {"R2": "Eth 0/0"},
            "Eth 0/3": {"R3": "Eth 0/0"},
            "Eth 0/4": {"R4": "Eth 0/0"},
        }
    }

    return_value = task_17_3.parse_sh_cdp_neighbors(sh_cdp_n_sw1)
    assert return_value != None, "Функция ничего не возвращает"
    assert (
        type(return_value) == dict
    ), f"По заданию функция должна возвращать словарь, а возвращает {type(return_value).__name__}"
    assert (
        return_value == correct_return_value
    ), "Функция возвращает неправильное значение"


"""
@author : 'XXY'
@contact : '529379497@qq.com'
@researchFie1d : 'NLP DL ML'
@date : 2018/9/26 0026 上午 10:57
"""
"""
递归思想：
取出数组中第一个元素放到最后，即a[1]与a[n]交换，然后递归求a[n-1]的全排列
例如：集合{1,2,3}
1、如果数组只有一个元素n = 1, a={1}则全排列就是{1}
2、如果数组元素只有两个n = 2, a={1,2}则全排列是：
{2,1}--a[1]与a[2]交换，交换后求a[2-1]={2}，归结到1、
{1,2}--a[2]与a[2]交换，交换后求a[2-1]={1}，归结到1、
3、如果数组有三个元素n=3，a={1,2,3} 则全排列是
 {{2,3},1}--a[1]与a[3]交换。后求a[3-1]={2,3}的全排列，归结到2）
 {{1,3},2)--a[2]与a[3]交换。后求a[3-1]={1,3}的全排列，归结到2）
 {{1,2},3)--a[3]与a[3]交换。后求a[3-1]={1,2}的全排列，归结到2）
 ....类推

也可以按照下面的思路：
    每次循环，取出一个元素添加到结果数组中，而对剩余的元素进行相同的全排列操作，终止条件剩余的元素为1
例如：[1,2,3,4]
    全排列可以看成是将1或2或3或4(for)放在固定位置，[2,3,4]，[1,2,4],[1,3,4]的全排列。以此类推
    直到数组中仅有一个元素
"""
# COUNT = 0
#
#
# def perm(nums, begin, end):
#     global COUNT
#     if begin >= end:
#         print(nums)
#         COUNT += 1
#     else:
#         i = begin
#         for j in range(begin, end):
#             nums[j], nums[i] = nums[i], nums[j]
#             perm(nums, begin+1, end)
#             nums[j], nums[i] = nums[i], nums[j]
import copy
retsult = []
COUNT = 0
def perm_func(remian_list, res_list):
    global COUNT
    if len(remian_list) == 1:
        res_list.append(remian_list[0])
        print(res_list)
        COUNT += 1
        return res_list

    else:
        for j in range(len(remian_list)):
            remian_list_c = copy.deepcopy(remian_list)
            res_list_c = copy.deepcopy(res_list)
            twp = remian_list_c.pop(j)
            res_list_c.append(twp)
            perm_func(remian_list_c, res_list_c)

if __name__ == '__main__':
    n = [1, 2, 3, 4]
    perm_func(n, [])
    print(COUNT)


""" Tests Reading of PypeIt Input files """
from pathlib import Path
import os
import shutil
import glob

from IPython import embed

from pypeit import inputfiles
from pypeit.scripts.setup import Setup

def test_read_fluxing_files():
    """ Test reading fluxing files """
    # Grab em
    fluxing_files = glob.glob(os.path.join(
        os.getenv('PYPEIT_DEV'), 'fluxing_files', '*.flux'))
    # Loop
    for ifile in fluxing_files:
        fluxFile = inputfiles.FluxFile.from_file(ifile)
        assert len(fluxFile.data['filename']) > 0

def test_read_coadd1d_files():
    """ Test reading coadd1d files """
    # Grab em
    coadd1d_files = glob.glob(os.path.join(
        os.getenv('PYPEIT_DEV'), 'coadd1d_files', '*.coadd1d'))
    # Loop
    for ifile in coadd1d_files:
        coadd1dFile = inputfiles.Coadd1DFile.from_file(ifile)
        assert len(coadd1dFile.data['filename']) > 0

def test_read_coadd2d_files():
    """ Test reading coadd2d files """
    # Grab em
    coadd2d_files = glob.glob(os.path.join(
        os.getenv('PYPEIT_DEV'), 'coadd2d_files', '*.coadd2d'))
    # Loop
    for ifile in coadd2d_files:
        coadd2dFile = inputfiles.Coadd2DFile.from_file(ifile)
        assert len(coadd2dFile.data['filename']) > 0

def test_read_flexure_files():
    """ Test reading flexure files """
    # Grab em
    flexure_files = glob.glob(os.path.join(
        os.getenv('PYPEIT_DEV'), 'flexure_files', '*.flex'))
    # Loop
    for ifile in flexure_files:
        flexureFile = inputfiles.FlexureFile.from_file(ifile)
        assert len(flexureFile.data['filename']) > 0

def test_read_pypeit_files():
    """ Test reading PypeIt files """
    # Grab em
    pypeit_files = glob.glob(os.path.join(
        os.getenv('PYPEIT_DEV'), 'pypeit_files', '*.pypeit'))
    # Loop
    for ifile in pypeit_files:
        pypeitFile = inputfiles.PypeItFile.from_file(ifile)

def test_get_spectrograph():
    pypeit_file = Path(os.getenv('PYPEIT_DEV')) / 'pypeit_files' \
                    / 'shane_kast_blue_452_3306_d57.pypeit'
    assert pypeit_file.exists(), 'Missing test pypeit file'

    pypeitFile = inputfiles.PypeItFile.from_file(pypeit_file)
    spec = pypeitFile.get_spectrograph()
    assert spec.name == 'shane_kast_blue', 'Wrong spectrograph'

def test_get_pypeitpar():

    spec = 'shane_kast_blue'
    setup = '600_4310_d55'

    # Define the path with the raw data
    data_root = Path(os.environ['PYPEIT_DEV']).resolve() / 'RAW_DATA' / spec / setup
    assert data_root.exists(), 'TEST ERROR: Raw data path does not exist'

    # Define the output directory and remove it if it already exist
    setup_path = Path().resolve() / f'{spec}_A'
    if setup_path.exists():
        shutil.rmtree(setup_path)

    args = ['-r', str(data_root), '-s', spec, '-c', 'all']
    pargs = Setup.parse_args(args)
    Setup.main(pargs)

    assert setup_path.exists(), 'No setup_files directory created'
    pypeit_file = setup_path / f'{spec}_A.pypeit'
    assert pypeit_file.exists(), 'PypeIt file not written'

    pypeitFile = inputfiles.PypeItFile.from_file(pypeit_file)
    spectrograph, par, file = pypeitFile.get_pypeitpar()

    assert spectrograph.name == spec, 'Wrong spectrograph'
    assert par['rdx']['spectrograph'] == spec, 'Wrong spectrgraph'
    assert par['rdx']['scidir'] == 'Science', 'Wrong default science directory'
    assert Path(file).name == 'b27.fits.gz', 'File name changed'

    # Clean-up
    shutil.rmtree(setup_path)


import cv2
import numpy as np

# input is numpy image array
def opticalflow(img1, img2):
    prvs = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
    next = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)
    hsv = np.zeros_like(prvs)
    hsv[..., 1] = 255

    flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)

    mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
    hsv[...,0] = ang*180/np.pi/2
    hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
    rgb = cv2.cvtColor(hsv,cv2.COLOR_HSV2RGB)
    gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)

    mask = np.where(x > 0.5, 0, 1)
    gray[mask]

    return rgb, gray[mask]


#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""A framework for developing sources for new file types.

To create a source for a new file type a sub-class of ``FileBasedSource`` should
be created. Sub-classes of ``FileBasedSource`` must implement the method
``FileBasedSource.read_records()``. Please read the documentation of that method
for more details.

For an example implementation of ``FileBasedSource`` see ``avroio.AvroSource``.
"""

from apache_beam.internal import pickler
from apache_beam.io import concat_source
from apache_beam.io import iobase
from apache_beam.io import range_trackers
from apache_beam.io.filesystem import CompressionTypes
from apache_beam.io.filesystems_util import get_filesystem
from apache_beam.transforms.display import DisplayDataItem
from apache_beam.utils.value_provider import ValueProvider
from apache_beam.utils.value_provider import StaticValueProvider
from apache_beam.utils.value_provider import check_accessible

MAX_NUM_THREADS_FOR_SIZE_ESTIMATION = 25

class FileBasedSource(iobase.BoundedSource):
  """A ``BoundedSource`` for reading a file glob of a given type."""

  MIN_NUMBER_OF_FILES_TO_STAT = 100
  MIN_FRACTION_OF_FILES_TO_STAT = 0.01

  def __init__(self,
               file_pattern,
               min_bundle_size=0,
               compression_type=CompressionTypes.AUTO,
               splittable=True,
               validate=True):
    """Initializes ``FileBasedSource``.

    Args:
      file_pattern: the file glob to read a string or a ValueProvider
                    (placeholder to inject a runtime value).
      min_bundle_size: minimum size of bundles that should be generated when
                       performing initial splitting on this source.
      compression_type: compression type to use
      splittable: whether FileBasedSource should try to logically split a single
                  file into data ranges so that different parts of the same file
                  can be read in parallel. If set to False, FileBasedSource will
                  prevent both initial and dynamic splitting of sources for
                  single files. File patterns that represent multiple files may
                  still get split into sources for individual files. Even if set
                  to True by the user, FileBasedSource may choose to not split
                  the file, for example, for compressed files where currently
                  it is not possible to efficiently read a data range without
                  decompressing the whole file.
      validate: Boolean flag to verify that the files exist during the pipeline
                creation time.
    Raises:
      TypeError: when compression_type is not valid or if file_pattern is not a
                 string or a ValueProvider.
      ValueError: when compression and splittable files are specified.
      IOError: when the file pattern specified yields an empty result.
    """

    if (not (isinstance(file_pattern, basestring)
             or isinstance(file_pattern, ValueProvider))):
      raise TypeError('%s: file_pattern must be of type string'
                      ' or ValueProvider; got %r instead'
                      % (self.__class__.__name__, file_pattern))

    if isinstance(file_pattern, basestring):
      file_pattern = StaticValueProvider(str, file_pattern)
    self._pattern = file_pattern
    if file_pattern.is_accessible():
      self._file_system = get_filesystem(file_pattern.get())
    else:
      self._file_system = None

    self._concat_source = None
    self._min_bundle_size = min_bundle_size
    if not CompressionTypes.is_valid_compression_type(compression_type):
      raise TypeError('compression_type must be CompressionType object but '
                      'was %s' % type(compression_type))
    self._compression_type = compression_type
    if compression_type in (CompressionTypes.UNCOMPRESSED,
                            CompressionTypes.AUTO):
      self._splittable = splittable
    else:
      # We can't split compressed files efficiently so turn off splitting.
      self._splittable = False
    if validate and file_pattern.is_accessible():
      self._validate()

  def display_data(self):
    return {'file_pattern': DisplayDataItem(str(self._pattern),
                                            label="File Pattern"),
            'compression': DisplayDataItem(str(self._compression_type),
                                           label='Compression Type')}

  @check_accessible(['_pattern'])
  def _get_concat_source(self):
    if self._concat_source is None:
      pattern = self._pattern.get()

      single_file_sources = []
      if self._file_system is None:
        self._file_system = get_filesystem(pattern)
      match_result = self._file_system.match([pattern])[0]
      files_metadata = match_result.metadata_list

      # We create a reference for FileBasedSource that will be serialized along
      # with each _SingleFileSource. To prevent this FileBasedSource from having
      # a reference to ConcatSource (resulting in quadratic space complexity)
      # we clone it here.
      file_based_source_ref = pickler.loads(pickler.dumps(self))

      for file_metadata in files_metadata:
        file_name = file_metadata.path
        file_size = file_metadata.size_in_bytes
        if file_size == 0:
          continue  # Ignoring empty file.

        # We determine splittability of this specific file.
        splittable = self.splittable
        if (splittable and
            self._compression_type == CompressionTypes.AUTO):
          compression_type = CompressionTypes.detect_compression_type(
              file_name)
          if compression_type != CompressionTypes.UNCOMPRESSED:
            splittable = False

        single_file_source = _SingleFileSource(
            file_based_source_ref, file_name,
            0,
            file_size,
            min_bundle_size=self._min_bundle_size,
            splittable=splittable)
        single_file_sources.append(single_file_source)
      self._concat_source = concat_source.ConcatSource(single_file_sources)
    return self._concat_source

  def open_file(self, file_name):
    return get_filesystem(file_name).open(
        file_name, 'application/octet-stream',
        compression_type=self._compression_type)

  @check_accessible(['_pattern'])
  def _validate(self):
    """Validate if there are actual files in the specified glob pattern
    """
    pattern = self._pattern.get()
    if self._file_system is None:
      self._file_system = get_filesystem(pattern)

    # Limit the responses as we only want to check if something exists
    match_result = self._file_system.match([pattern], limits=[1])[0]
    if len(match_result.metadata_list) <= 0:
      raise IOError(
          'No files found based on the file pattern %s' % pattern)

  def split(
      self, desired_bundle_size=None, start_position=None, stop_position=None):
    return self._get_concat_source().split(
        desired_bundle_size=desired_bundle_size,
        start_position=start_position,
        stop_position=stop_position)

  @check_accessible(['_pattern'])
  def estimate_size(self):
    pattern = self._pattern.get()
    if self._file_system is None:
      self._file_system = get_filesystem(pattern)
    match_result = self._file_system.match([pattern])[0]
    return sum([f.size_in_bytes for f in match_result.metadata_list])

  def read(self, range_tracker):
    return self._get_concat_source().read(range_tracker)

  def get_range_tracker(self, start_position, stop_position):
    return self._get_concat_source().get_range_tracker(start_position,
                                                       stop_position)

  def read_records(self, file_name, offset_range_tracker):
    """Returns a generator of records created by reading file 'file_name'.

    Args:
      file_name: a ``string`` that gives the name of the file to be read. Method
                 ``FileBasedSource.open_file()`` must be used to open the file
                 and create a seekable file object.
      offset_range_tracker: a object of type ``OffsetRangeTracker``. This
                            defines the byte range of the file that should be
                            read. See documentation in
                            ``iobase.BoundedSource.read()`` for more information
                            on reading records while complying to the range
                            defined by a given ``RangeTracker``.

    Returns:
      an iterator that gives the records read from the given file.
    """
    raise NotImplementedError

  @property
  def splittable(self):
    return self._splittable

class _SingleFileSource(iobase.BoundedSource):
  """Denotes a source for a specific file type."""

  def __init__(self, file_based_source, file_name, start_offset, stop_offset,
               min_bundle_size=0, splittable=True):
    if not isinstance(start_offset, (int, long)):
      raise TypeError(
          'start_offset must be a number. Received: %r' % start_offset)
    if stop_offset != range_trackers.OffsetRangeTracker.OFFSET_INFINITY:
      if not isinstance(stop_offset, (int, long)):
        raise TypeError(
            'stop_offset must be a number. Received: %r' % stop_offset)
      if start_offset >= stop_offset:
        raise ValueError(
            'start_offset must be smaller than stop_offset. Received %d and %d '
            'for start and stop offsets respectively' %
            (start_offset, stop_offset))

    self._file_name = file_name
    self._is_gcs_file = file_name.startswith('gs://') if file_name else False
    self._start_offset = start_offset
    self._stop_offset = stop_offset
    self._min_bundle_size = min_bundle_size
    self._file_based_source = file_based_source
    self._splittable = splittable

  def split(self, desired_bundle_size, start_offset=None, stop_offset=None):
    if start_offset is None:
      start_offset = self._start_offset
    if stop_offset is None:
      stop_offset = self._stop_offset

    if self._splittable:
      bundle_size = max(desired_bundle_size, self._min_bundle_size)

      bundle_start = start_offset
      while bundle_start < stop_offset:
        bundle_stop = min(bundle_start + bundle_size, stop_offset)
        yield iobase.SourceBundle(
            bundle_stop - bundle_start,
            _SingleFileSource(
                # Copying this so that each sub-source gets a fresh instance.
                pickler.loads(pickler.dumps(self._file_based_source)),
                self._file_name,
                bundle_start,
                bundle_stop,
                min_bundle_size=self._min_bundle_size,
                splittable=self._splittable),
            bundle_start,
            bundle_stop)
        bundle_start = bundle_stop
    else:
      # Returning a single sub-source with end offset set to OFFSET_INFINITY (so
      # that all data of the source gets read) since this source is
      # unsplittable. Choosing size of the file as end offset will be wrong for
      # certain unsplittable source, e.g., compressed sources.
      yield iobase.SourceBundle(
          stop_offset - start_offset,
          _SingleFileSource(
              self._file_based_source,
              self._file_name,
              start_offset,
              range_trackers.OffsetRangeTracker.OFFSET_INFINITY,
              min_bundle_size=self._min_bundle_size,
              splittable=self._splittable
          ),
          start_offset,
          range_trackers.OffsetRangeTracker.OFFSET_INFINITY
      )

  def estimate_size(self):
    return self._stop_offset - self._start_offset

  def get_range_tracker(self, start_position, stop_position):
    if start_position is None:
      start_position = self._start_offset
    if stop_position is None:
      # If file is unsplittable we choose OFFSET_INFINITY as the default end
      # offset so that all data of the source gets read. Choosing size of the
      # file as end offset will be wrong for certain unsplittable source, for
      # e.g., compressed sources.
      stop_position = (
          self._stop_offset if self._splittable
          else range_trackers.OffsetRangeTracker.OFFSET_INFINITY)

    range_tracker = range_trackers.OffsetRangeTracker(
        start_position, stop_position)
    if not self._splittable:
      range_tracker = range_trackers.UnsplittableRangeTracker(range_tracker)

    return range_tracker

  def read(self, range_tracker):
    return self._file_based_source.read_records(self._file_name, range_tracker)

  def default_output_coder(self):
    return self._file_based_source.default_output_coder()