'''
根据QSim将Parser生成的语法树翻译成Pyhton代码
if __name__ == '__main__':
    将生成的py文件保存在 log/auto.py
date: 2020-11-10
'''
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #当前程序上上一级目录，这里为QSim
sys.path.append(BASE_DIR) #添加环境变量
from string import Template
from Lexer.Lexer import Lexer
from Parser.Parser import Parser
import logging
def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        return True
    else:
        return False
mkdir('log')
logging.basicConfig(filename='log/translate.log', level=logging.DEBUG)
log = logging.getLogger('translate')

py_template = {
    'header':
    '''
import os
import sys
import time
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #当前程序上上一级目录，这里为QSim
# sys.path.append(BASE_DIR)
from lib.QSim import QuantumRegister
from lib.QSim import Tools
tools = Tools()
import numpy as np
start_time = time.perf_counter ()
    ''',
    'footer':
    '''
t_cost = time.perf_counter () - start_time
_wf = tools.print_wf(qubit.a2wf())
memory_cost = sys.getsizeof(qubit) / 1024 / 1024
# print(_wf)
    ''',
    'FuncStatement':
Template('''
def $FuncStatement_Name($ParameterList):
    $Statement
'''),
    'IFStatement':
Template('''if $bool_str:
    $Statement'''),
    'Declare_func':
Template('''$name = $FuncCall_Name($ParameterList)'''),
    'Declare_INT':
Template('''$Iden = $INT'''),
    'GateOp':
Template('''qubit.applyGate('$GateOp_Name',$placeList)'''),
    'FuncCall':
Template('''$FuncCall_Name($ParameterList)'''),
    'measure':
Template('''qubit.measure(place=$place, count=$count)'''),
    'Declare_quantum':
Template('''qubit = QuantumRegister($numQubits)'''),
    'Declare_measure':
Template('''$Iden = qubit.measure(place=$place, count=$count)'''),
    'show':
Template('''# show( $Iden )'''),
    'R':
Template('''qubit.applyGate('$GateOp_Name',$placeList)''')
}

# TODO
qasm_template = {
    'header':
    '''
OPENQASM 3;
include "stdgates.inc";
    ''',
    'Declare_quantum':
Template('''qubit[$numQubits] _q'''),
    'GateOp':
Template('''$GateOp_Name $placeList'''),
    'R':
Template('''cphase(pi / $k) $placeList'''),
    'measure':
Template('''_c = measure _q''')
}

class pyFileHandler():
    '''维护生成的代码'''
    def __init__(self):
        self.result = []
        self.result.append(py_template['header'])

    def insert(self, _value, _type):
        s = py_template[_type].substitute(_value)
        self.result.append(s)

    def generate_file(self, file_name=''):
        if file_name == '':
            file_name = 'log/auto.py'
        self.result.append(py_template['footer'])
        self.file = open(file_name, 'w+', encoding = 'utf-8')
        self.file.write('\n'.join(self.result) + '\n')
        self.file.close()

class qasmFileHandler():
    '''维护生成的代码'''
    def __init__(self):
        self.result = []
        self.result.append(py_template['header'])

    def insert(self, _value, _type):
        s = py_template[_type].substitute(_value)
        self.result.append(s)

    def generate_file(self, file_name=''):
        if file_name == '':
            file_name = 'log/qasm.txt'
        self.file = open(file_name, 'w+', encoding = 'utf-8')
        self.file.write('\n'.join(self.result) + '\n')
        self.file.close()

class SymbalTable:
    '''
    符号表
    负责维护程序中的变量信息，以便调用
    '''
    def __init__(self):
        self.table = {
            'qubit': 'qubit',
            '_wf': '_wf',
            't_cost': 't_cost',
            'measure' : [],
            'show' : [],
            'FuncStatement': [],
            'Identify': []
        }
        self.showCount = 0

    def add(self, name=None, value=None, type=None):
        if type == 'measure':
            self.table['measure'].append({name: value})
        elif type == 'show':
            name = str(self.showCount)
            self.showCount += 1
            self.table['show'].append({name: value})
        elif type == 'FuncStatement':
            self.table['FuncStatement'].append({name: value})
        elif type == 'Identify':
            self.table['Identify'].append({name: value})
        else:
            raise ValueError('type {} is not defined!'.format(type))

    def initial(self):
        del self.table['measure']
        self.table['measure'] = []
        del self.table['show']
        self.table['show'] = []
        del self.table['FuncStatement']
        self.table['FuncStatement'] = []
        del self.table['Identify']
        self.table['Identify'] = []

    def check(self, name, type):
        pass

symbalTable = SymbalTable()

class Translate:
    def __init__(self, tree):
        self.tree = tree
        self.fileHandler = pyFileHandler()

    def log(self, file_name=''):
        self.fileHandler.generate_file(file_name)

    def getResult(self):
        result = self.fileHandler.result
        result.append(py_template['footer'])
        return '\n'.join(result) + '\n'

    def getSymbalTable(self):
        return symbalTable.table

    def initSymbalTable(self):
        symbalTable.initial()

    def process_statement(self, node):
        '''处理大括号内的情况，如if,while,func'''
        if not node:
            return
        child = node.first_son
        statement_list = []
        while child:
            if child.value == 'Declare_func':
                dict = self.Declare_func(child)
                s = py_template['Declare_func'].substitute(dict)
                statement_list.append(s)
            elif child.value == 'Declare_INT':
                dict = self.Declare_INT(child)
                self.fileHandler.insert(dict, 'Declare_INT')
            elif child.value == 'Declare_quantum':
                dict = self.Declare_quantum(child)
                s = py_template['Declare_quantum'].substitute(dict)
                statement_list.append(s)
                pass
            elif child.value == 'Declare_measure':
                dict = self.Declare_measure(child)
                self.fileHandler.insert(dict, 'Declare_measure')
            elif child.value == 'GateOp':
                dict = self.GateOp(child)
                s = py_template['GateOp'].substitute(dict)
                statement_list.append(s)
            elif child.value == 'FuncStatement':
                dict = self.FuncStatement(child)
                s = py_template['FuncStatement'].substitute(dict)
                statement_list.append(s)
            elif child.value == 'FuncCall':
                if child.first_son.value == 'measure':
                    dict = self.measure(child)
                    s = py_template['measure'].substitute(dict)
                    statement_list.append(s)
                elif child.first_son.value == 'show':
                    dict = self.show(child)
                    s = py_template['show'].substitute(dict)
                    statement_list.append(s)
                elif child.first_son.value == 'R':
                    dict = self.R(child)
                    s = py_template['R'].substitute(dict)
                else:
                    dict = self.FuncCall(child)
                    s = py_template['FuncCall'].substitute(dict)
                    statement_list.append(s)
            elif child.value == 'IFStatement':
                dict = self.IFStatement(child)
                s = py_template['IFStatement'].substitute(dict)
                statement_list.append(s)
                pass
            child = child.right
        statement_str = ''.join(statement_list) + '\n'
        return statement_str

    def FuncStatement(self, node):
        '''
        func f(){}
        '''
        if not node:
            return
        child = node.first_son
        FuncStatement_Name = ''
        ParameterList = ''
        Statement_str = ''
        while child:
            if child.type == 'FuncStatement_Name':
                FuncStatement_Name = child.value
            elif child.value == 'ParameterList' and child.type == None:
                pl = self.tree.find_all_child(child)
                for p in pl:
                    ParameterList += ',' + p.value
                ParameterList = ParameterList[1:]   # 去除第一个,
            elif child.value == 'Statement' and child.type == None:
                Statement_str = self.process_statement(child)
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        symbalTable.add(name=FuncStatement_Name, value='FuncStatement', type='FuncStatement')
        return dict(FuncStatement_Name=FuncStatement_Name,ParameterList=ParameterList,Statement=Statement_str)

    def IFStatement(self, node):
        '''
        if(2>1){}
        '''
        if not node:
            return
        child = node.first_son
        bool_str = ''
        statement_str = ''
        while child:
            if child.value == 'Bool' and child.type == None:
                bs = self.tree.find_all_child(child)
                for b in bs:
                    bool_str += b.value
            elif child.value == 'Statement' and child.type == None:
                statement_str = self.process_statement(child)
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(bool_str=bool_str, Statement=statement_str)

    def Return(self, node):
        pass

    def Expression(self, node):
        if not node:
            return
        child = node.first_son
        Expression_str = ''
        while child:
            Expression_str += child.value
        return Expression_str

    def Declare_func(self, node):
        '''
        a = f()
        '''
        if not node:
            return
        child = node.first_son
        name = ''
        FuncCall_Name = ''
        ParameterList = ''
        '''按层遍历'''
        while child:
            # print(child.format())
            if child.type == 500:
                name = child.value
            elif child.value == '=':
                pass
            elif child.value == 'FuncCall' and child.type == None:
                list = self.tree.find_all_child(child)
                for n in list:
                    if n.type == 'FuncCall_Name':
                        FuncCall_Name = n.value
                    elif n.value == 'ParameterList' and n.type == None:
                        pl = self.tree.find_all_child(n)
                        for p in pl:
                            ParameterList += ',' + p.value
                        ParameterList = ParameterList[1:]   # 去除第一个,
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(name=name,FuncCall_Name=FuncCall_Name,ParameterList=ParameterList)

    def GateOp(self, node):
        if not node:
            return
        child = node.first_son
        GateOp_Name = ''
        placeList = ''
        while child:
            if child.type == 'GateOp_Name':
                GateOp_Name = child.value
            elif child.value == 'ParameterList' and child.type == None:
                list = self.tree.find_all_child(child)
                for n in list:
                    placeList += ',' + n.value
                placeList = placeList[1:]   # 去除第一个,
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(GateOp_Name=GateOp_Name, placeList=placeList)

    def R(self, node):
        if not node:
            return
        child = node.first_son
        GateOp_Name = ''
        placeList = ''
        while child:
            if child.value == 'R':
                GateOp_Name = child.value
            elif child.value == 'ParameterList' and child.type == None:
                list = self.tree.find_all_child(child)
                GateOp_Name = GateOp_Name + list[0].value
                list = list[1:]
                for n in list:
                    placeList += ',' + n.value
                placeList = placeList[1:]   # 去除第一个,
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(GateOp_Name=GateOp_Name, placeList=placeList)

    def FuncCall(self, node):
        if not node:
            return
        child = node.first_son
        FuncCall_Name = ''
        ParameterList = ''
        while child:
            if child.type == 'FuncCall_Name':
                FuncCall_Name = child.value
            elif child.value == 'ParameterList' and child.type == None:
                pl = self.tree.find_all_child(child)
                for p in pl:
                    ParameterList += ',' + p.value
                ParameterList = ParameterList[1:]   # 去除第一个,
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(FuncCall_Name=FuncCall_Name, ParameterList=ParameterList)

    '''qubit.measure(place=$place, count=$count)'''
    def measure(self, node):
        if not node:
            return
        child = node.first_son
        place = '-1'
        count = '1'
        while child:
            if child.value == 'measure':
                pass
            elif child.value == 'ParameterList' and child.type == None:
                pl = self.tree.find_all_child(child)
                '''这里需要分别处理measure(q) === measure(),
                    measure(q[0]) === measure(0)的情况'''
                for p in pl:
                    if p.type == 500:
                        pass
                    elif p.type == 600:
                        place = p.value
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(place=place, count=count)

    def show(self, node):
        if not node:
            return
        child = node.first_son
        iden = None
        while child:
            if child.value == 'show':
                pass
            elif child.value == 'ParameterList' and child.type == None:
                pl = self.tree.find_all_child(child)
                '''show(m1), show(1)'''
                for p in pl:
                    if p.type == 500:
                        iden = p.value
                    elif p.type == 600:
                        iden = p.value
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        symbalTable.add(value=iden, type='show')
        return dict(Iden=iden)

    def Declare_quantum(self, node):
        if not node:
            return
        child = node.first_son
        numQubits = '-1'
        qubit = 'qubit'
        while child:
            if child.value == 'quantum':
                pass
            elif child.type == 500:
                pass
            elif child.value == '=':
                pass
            elif child.value == 'Declare_quantum' and child.father.value == 'Declare_quantum':
                return Translate.Declare_quantum(self, child)
            elif child.value == 'FuncCall' and child.type == None:
                list = self.tree.find_all_child(child)
                for n in list:
                    if n.type == 'FuncCall_Name':
                        pass
                    elif n.value == 'ParameterList' and n.type == None:
                        pl = self.tree.find_all_child(n)
                        numQubits = pl[0].value
            elif child.type == None and child.value == 'ParameterList':
                # 函数式声明quantumRegister
                list = self.tree.find_all_child(child)
                numQubits = list[0].value
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        return dict(qubit=qubit, numQubits=numQubits)

    def Declare_measure(self, node):
        if not node:
            return
        child = node.first_son
        Iden = 'm'
        place = '-1'
        count = '1'
        while child:
            if child.type == 500:
                Iden = child.value
            elif child.value == '=':
                pass
            elif child.value == 'FuncCall' and child.type == None:
                list = self.tree.find_all_child(child)
                for n in list:
                    if n.type == 'FuncCall_Name':
                        pass
                    elif n.value == 'ParameterList' and n.type == None:
                        pl = self.tree.find_all_child(n)
                        '''这里需要分别处理measure(q), measure(q[0])的情况'''
                        for p in pl:
                            if p.type == 500:
                                pass
                            elif p.type == 600:
                                place = p.value
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        symbalTable.add(name=Iden, value='measure', type='measure')
        return dict(Iden=Iden, place=place, count=count)

    def Declare_INT(self, node):
        if not node:
            return
        child = node.first_son
        Iden = 'Iden'
        INT = ''
        while child:
            if child.type == 500:
                Iden = child.value
            elif child.value == '=':
                pass
            elif child.type == 'INT':
                INT = child.value
            else:
                raise ValueError('Failed to analyze child: {}'.format(child.format()))
            child = child.right
        symbalTable.add(name=Iden, value=INT, type='Identify')
        return dict(Iden=Iden, INT=INT)

    def main(self):
        tree = self.tree
        childs = tree.find_all_child(tree.root)
        for child in childs:
            if child.value == 'Declare_func':
                dict = self.Declare_func(child)
                self.fileHandler.insert(dict, 'Declare_func')
            elif child.value == 'Declare_INT':
                dict = self.Declare_INT(child)
                self.fileHandler.insert(dict, 'Declare_INT')
            elif child.value == 'Declare_quantum':
                dict = self.Declare_quantum(child)
                self.fileHandler.insert(dict, 'Declare_quantum')
            elif child.value == 'Declare_measure':
                dict = self.Declare_measure(child)
                self.fileHandler.insert(dict, 'Declare_measure')
            elif child.value == 'GateOp':
                dict = self.GateOp(child)
                self.fileHandler.insert(dict, 'GateOp')
            elif child.value == 'FuncStatement':
                dict = self.FuncStatement(child)
                self.fileHandler.insert(dict, 'FuncStatement')
            elif child.value == 'FuncCall':
                if child.first_son.value == 'measure':
                    dict = self.measure(child)
                    self.fileHandler.insert(dict, 'measure')
                elif child.first_son.value == 'show':
                    # show函数不需要生成代码
                    dict = self.show(child)
                    self.fileHandler.insert(dict, 'show')
                elif child.first_son.value == 'R':
                    dict = self.R(child)
                    self.fileHandler.insert(dict, 'R')
                else:
                    dict = self.FuncCall(child)
                    self.fileHandler.insert(dict, 'FuncCall')
            elif child.value == 'IFStatement':
                dict = self.IFStatement(child)
                self.fileHandler.insert(dict, 'IFStatement')
                pass

if __name__ == '__main__':
    print('translate')
    lexer = Lexer(file_path='QLight/code_2.txt')
    lexer.scanner()
    lexer.log()
    parser = Parser(lexer.getTOKEN())
    parser.parse()
    parser.log()
    translate = Translate(parser.tree)
    translate.main()
    translate.log()


#!/usr/bin/env python

import logging
import sys
import pprint
import platform
from setuptools import setup, find_packages
from setuptools.extension import Extension

# Set up the logging environment
logging.basicConfig()
log = logging.getLogger()

# Handle the -W all flag
if 'all' in sys.warnoptions:
    log.level = logging.DEBUG

with open('VERSION.txt', 'r') as f:
    version = f.read()

# Use Cython if available
try:
    from Cython.Build import cythonize
except:
    log.critical(
        'Cython.Build.cythonize not found. '
        'Cython is required to build from a repo.')
    sys.exit(1)

# Use README.rst as the long description
with open('README.rst') as f:
    readme = f.read()

# Extension options
include_dirs = []
try:
    import numpy
    include_dirs.append(numpy.get_include())
except ImportError:
    log.critical('Numpy and its headers are required to run setup(). Exiting')
    sys.exit(1)

opts = dict(
    include_dirs=include_dirs,
)
log.debug('opts:\n%s', pprint.pformat(opts))
pyx_path = 'feerci.pyx'

if 'test' in sys.argv and platform.python_implementation() == 'CPython':
    from Cython.Build import cythonize
    ext_modules = cythonize(Extension(
        "feerci",
        [pyx_path],
        define_macros=[('CYTHON_TRACE', '1')],**opts
    ), compiler_directives={
        'linetrace': True,
        'binding': True
    })
else:
    from Cython.Build import cythonize, build_ext
    ext_modules = cythonize(Extension(
        "feerci",
        [pyx_path],
        extra_compile_args=['-O3'],**opts
    ))
# Dependencies
install_requires = [
    'numpy>=1.7',
    'Cython',
]
python_requires = '>=3.5'

setup_args = dict(
    name='feerci',
    version=version,
    description='FEERCI: A python package for EER confidence intervals ',
    long_description=readme,
    url='https://github.com/feerci/feerci',
    # author='FEERCI Dev',
    # author_email='feerci@example.com',
    # license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
    ],
    keywords=['EER', 'Confidence Interval', 'feerci','feer','biometrics'],
    ext_modules=ext_modules,
    install_requires=install_requires,
    packages=find_packages(exclude='tests'),
    tests_require=['cython', 'pytest', 'coverage'],
    test_suite='tests'
)

setup(**setup_args)


#This programe is to direction dependent velocity

import math

def main():

  v1 ,v2 ,v3 = ([] for i in range(3))

  tth = [0.0, 5.0, 15.0, 25.0, 35.0, 45.0, 55.0, 65.0, 75.0, 85.0, 90.0]

  comp = input(" Enter the compound's name = ")
  c11 = float(input(" Enter the value of c11 =  "))
  c12 = float(input(" Enter the value of c12 =  "))
  c13 = float(input(" Enter the value of c13 =  "))
  c33 = float(input(" Enter the value of c33 =  "))
  c44 = float(input(" Enter the value of c44 =  "))
  print()

  for tthValue in tth:

    th = (tthValue*22)/(180*7)

    p = pow(math.sin(th),2.0)
    q = pow(math.cos(th), 2.0)

    r = c11*p-c33*q+c44*(q-p)
    s = pow(r, 2.0);

    t = 4.0*p*q*pow((c13+c44), 2)
    u = pow((s+t),0.5)

    v1.append((c33*q+c11*p+c44+u)/2)
    v2.append((c33*q+c11*p+c44-u)/2)
    v3.append((c44*q+((c11-c12)/2.0)*p))

  print("Table of velocity for hcp compound-")
  print("Compound name="+ comp+"\n")

  print("{:<18} {:<18} {:<18} {:<18}".format("Theeta", "v1", "v2", "v3"))
  print("{:<18} {:<18} {:<18} {:<18}".format("---------", "---------", "---------", "---------"))

  for tthValue, v1Value, v2Value, v3Value in zip(tth, v1, v2, v3):

    print("{:<18} {:<18.10f} {:<18.10f} {:<18.10f}".format(tthValue, v1Value, v2Value, v3Value))

  print()

if __name__ == "__main__":

    main()


import os
import pickle
import cv2
import mediapipe as mp

#Drawing function on hands initialization
drawing = mp.solutions.drawing_utils
drawing_styles = mp.solutions.drawing_styles

#Initialise hands class
hand = mp.solutions.hands

data, labels = [],[]
data_folder = './ASL/data'

#Sets up hand detection, if comp is sure above 30% then it reads image as hand
hands = hand.Hands(static_image_mode=True, min_detection_confidence=0.3)

for dir_ in os.listdir(data_folder):
    for img_path in os.listdir(os.path.join(data_folder, dir_)):
        #Reads through every image
        hand_data, x_, y_ = [], [], []

        img = cv2.imread(os.path.join(data_folder, dir_, img_path))

        #Converts image to RGB format from BGR, coz cv2 by default changes all to BGR
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        #Checks if handmarks are detected then iterates through them all
        results = hands.process(img_rgb)
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                for i in range(len(hand_landmarks.landmark)):
                    #Saves x,y coordinate of every handpoint as array
                    x = hand_landmarks.landmark[i].x
                    y = hand_landmarks.landmark[i].y
                    x_.append(x)
                    y_.append(y)

                for i in range(len(hand_landmarks.landmark)):
                    x = hand_landmarks.landmark[i].x
                    y = hand_landmarks.landmark[i].y
                    #For normalisation of dataset, takes only distance between data
                    hand_data.append(x - min(x_))
                    hand_data.append(y - min(y_))

            data.append(hand_data)
            labels.append(dir_)

#Makes a binary file with data of every handmark corresponding to its label(A/B/C/....)
file = open('./ASL/data.pickle', 'wb')
pickle.dump({'data': data, 'labels': labels}, file)
file.close()


import gc
import pathlib
import os
import sys
from weakref import proxy
from pathlib import Path

import imageio
import numpy as np
import pytest
import vtk

import pyvista
from pyvista import examples
from pyvista.plotting import system_supports_plotting
from pyvista.plotting.plotting import SUPPORTED_FORMATS

NO_PLOTTING = not system_supports_plotting()

ffmpeg_failed = False
try:
    try:
        import imageio_ffmpeg
        imageio_ffmpeg.get_ffmpeg_exe()
    except ImportError:
        imageio.plugins.ffmpeg.download()
except:
    ffmpeg_failed = True

if __name__ != '__main__':
    OFF_SCREEN = 'pytest' in sys.modules
else:
    OFF_SCREEN = False

pyvista.OFF_SCREEN = OFF_SCREEN
VTK9 = vtk.vtkVersion().GetVTKMajorVersion() >= 9

sphere = pyvista.Sphere()
sphere_b = pyvista.Sphere(1.0)
sphere_c = pyvista.Sphere(2.0)

def _is_vtk(obj):
    try:
        return obj.__class__.__name__.startswith('vtk')
    except Exception:  # old Python sometimes no __class__.__name__
        return False

@pytest.fixture(autouse=True)
def check_gc():
    """Ensure that all VTK objects are garbage-collected by Python."""
    before = set(id(o) for o in gc.get_objects() if _is_vtk(o))
    yield
    pyvista.close_all()
    gc.collect()
    after = [o for o in gc.get_objects() if _is_vtk(o) and id(o) not in before]
    assert len(after) == 0, \
        'Not all objects GCed:\n' + \
        '\n'.join(sorted(o.__class__.__name__ for o in after))

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot(tmpdir):
    tmp_dir = tmpdir.mkdir("tmpdir2")
    filename = str(tmp_dir.join('tmp.png'))
    scalars = np.arange(sphere.n_points)
    cpos, img = pyvista.plot(sphere,
                             off_screen=OFF_SCREEN,
                             full_screen=True,
                             text='this is a sphere',
                             show_bounds=True,
                             color='r',
                             style='wireframe',
                             line_width=10,
                             scalars=scalars,
                             flip_scalars=True,
                             cmap='bwr',
                             interpolate_before_map=True,
                             screenshot=filename,
                             return_img=True)
    assert isinstance(cpos, pyvista.CameraPosition)
    assert isinstance(img, np.ndarray)
    assert os.path.isfile(filename)

    filename = pathlib.Path(str(tmp_dir.join('tmp2.png')))
    cpos = pyvista.plot(sphere, off_screen=OFF_SCREEN, screenshot=filename)

    # Ensure it added a PNG extension by default
    assert filename.with_suffix(".png").is_file()

    # test invalid extension
    with pytest.raises(ValueError):
        filename = pathlib.Path(str(tmp_dir.join('tmp3.foo')))
        pyvista.plot(sphere, off_screen=OFF_SCREEN, screenshot=filename)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_invalid_style():
    with pytest.raises(ValueError):
        pyvista.plot(sphere, style='not a style')

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_interactor_style():
    plotter = pyvista.Plotter()
    plotter.add_mesh(sphere)
    interactions = (
        'trackball',
        'trackball_actor',
        'image',
        'joystick',
        'zoom',
        'terrain',
        'rubber_band',
        'rubber_band_2d',
    )
    for interaction in interactions:
        getattr(plotter, f'enable_{interaction}_style')()
        assert plotter._style_class is not None
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_lighting():
    plotter = pyvista.Plotter()

    # test default disable_3_lights()
    lights = list(plotter.renderer.GetLights())
    assert all([light.GetSwitch() for light in lights])

    plotter.enable_3_lights()
    lights = list(plotter.renderer.GetLights())
    headlight = lights.pop(0)
    assert not headlight.GetSwitch()
    for i in range(len(lights)):
        if i < 3:
            assert lights[i].GetSwitch()
        else:
            assert not lights[i].GetSwitch()
    assert lights[0].GetIntensity() == 1.0
    assert lights[1].GetIntensity() == 0.6
    assert lights[2].GetIntensity() == 0.5
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plotter_shape_invalid():
    # wrong size
    with pytest.raises(ValueError):
        pyvista.Plotter(shape=(1,))
    # not positive
    with pytest.raises(ValueError):
        pyvista.Plotter(shape=(1, 0))
    with pytest.raises(ValueError):
        pyvista.Plotter(shape=(0, 2))
    # not a sequence
    with pytest.raises(TypeError):
        pyvista.Plotter(shape={1, 2})

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_bounds_axes_with_no_data():
    plotter = pyvista.Plotter()
    plotter.show_bounds()
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_show_grid():
    plotter = pyvista.Plotter()
    plotter.show_grid()
    plotter.add_mesh(sphere)
    plotter.close()

cpos_param = [[(2.0, 5.0, 13.0),
              (0.0, 0.0, 0.0),
              (-0.7, -0.5, 0.3)],
             [-1, 2, -5],  # trigger view vector
             [1.0, 2.0, 3.0],
]
cpos_param.extend(pyvista.plotting.Renderer.CAMERA_STR_ATTR_MAP)
@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
@pytest.mark.parametrize('cpos', cpos_param)
def test_set_camera_position(cpos, sphere):
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.camera_position = cpos
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
@pytest.mark.parametrize('cpos', [[(2.0, 5.0),
                                   (0.0, 0.0, 0.0),
                                   (-0.7, -0.5, 0.3)],
                                  [-1, 2],
                                  [(1,2,3)],
                                  'notvalid'])
def test_set_camera_position_invalid(cpos, sphere):
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    with pytest.raises(pyvista.core.errors.InvalidCameraError):
        plotter.camera_position = cpos

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_no_active_scalars():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    with pytest.raises(ValueError):
        plotter.update_scalars(np.arange(5))
    with pytest.raises(ValueError):
        plotter.update_scalars(np.arange(sphere.n_faces))

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_show_bounds():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.show_bounds(show_xaxis=False,
                        show_yaxis=False,
                        show_zaxis=False,
                        show_xlabels=False,
                        show_ylabels=False,
                        show_zlabels=False,
                        use_2d=True)
    # And test backwards compatibility
    plotter.add_bounds_axes(show_xaxis=False,
                            show_yaxis=False,
                            show_zaxis=False,
                            show_xlabels=False,
                            show_ylabels=False,
                            show_zlabels=False,
                            use_2d=True)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_label_fmt():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.show_bounds(xlabel='My X', fmt=r'%.3f')
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
@pytest.mark.parametrize('grid', [True, 'both', 'front', 'back'])
@pytest.mark.parametrize('location', ['all', 'origin', 'outer', 'front', 'back'])
def test_plot_show_bounds_params(grid, location):
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(pyvista.Cube())
    plotter.show_bounds(grid=grid, ticks='inside', location=location)
    plotter.show_bounds(grid=grid, ticks='outside', location=location)
    plotter.show_bounds(grid=grid, ticks='both', location=location)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plotter_scale():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.set_scale(10, 10, 10)
    assert plotter.scale == [10, 10, 10]
    plotter.set_scale(5.0)
    plotter.set_scale(yscale=6.0)
    plotter.set_scale(zscale=9.0)
    assert plotter.scale == [5.0, 6.0, 9.0]
    plotter.scale = [1.0, 4.0, 2.0]
    assert plotter.scale == [1.0, 4.0, 2.0]
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_add_scalar_bar():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.add_scalar_bar(label_font_size=10, title_font_size=20, title='woa',
                           interactive=True, vertical=True)
    plotter.add_scalar_bar(background_color='white', n_colors=256)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_invalid_add_scalar_bar():
    with pytest.raises(AttributeError):
        plotter = pyvista.Plotter()
        plotter.add_scalar_bar()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_list():
    pyvista.plot([sphere, sphere_b],
                 off_screen=OFF_SCREEN,
                 style='points')

    pyvista.plot([sphere, sphere_b, sphere_c],
                 off_screen=OFF_SCREEN,
                 style='wireframe')

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_add_lines_invalid():
    plotter = pyvista.Plotter()
    with pytest.raises(TypeError):
        plotter.add_lines(range(10))

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_open_gif_invalid():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    with pytest.raises(ValueError):
        plotter.open_gif('file.abs')

@pytest.mark.skipif(ffmpeg_failed, reason="Requires imageio-ffmpeg")
@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_make_movie():
    # Make temporary file
    filename = os.path.join(pyvista.USER_DATA_PATH, 'tmp.mp4')

    movie_sphere = sphere.copy()
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.open_movie(filename)
    actor = plotter.add_axes_at_origin()
    plotter.remove_actor(actor, reset_camera=False, render=True)
    plotter.add_mesh(movie_sphere,
                     scalars=np.random.random(movie_sphere.n_faces))
    plotter.show(auto_close=False, window_size=[304, 304])
    plotter.set_focus([0, 0, 0])
    for i in range(3):  # limiting number of frames to write for speed
        plotter.write_frame()
        random_points = np.random.random(movie_sphere.points.shape)
        movie_sphere.points[:] = random_points*0.01 + movie_sphere.points*0.99
        movie_sphere.points[:] -= movie_sphere.points.mean(0)
        scalars = np.random.random(movie_sphere.n_faces)
        plotter.update_scalars(scalars)

    # checking if plotter closes
    ref = proxy(plotter)
    plotter.close()

    # remove file
    os.remove(filename)

    try:
        ref
    except:
        raise RuntimeError('Plotter did not close')

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_add_legend():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    with pytest.raises(ValueError):
        plotter.add_legend()
    legend_labels = [['sphere', 'r']]
    plotter.add_legend(labels=legend_labels, border=True, bcolor=None,
                       size=[0.1, 0.1])
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_add_axes_twice():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_axes()
    plotter.add_axes(interactive=True)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_add_point_labels():
    n = 10
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    points = np.random.random((n, 3))

    with pytest.raises(ValueError):
        plotter.add_point_labels(points, range(n - 1))

    plotter.add_point_labels(points, range(n), show_points=True, point_color='r')
    plotter.add_point_labels(points - 1, range(n), show_points=False, point_color='r')
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
@pytest.mark.parametrize('always_visible', [False, True])
def test_add_point_labels_always_visible(always_visible):
    # just make sure it runs without exception
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_point_labels(
        np.array([[0, 0, 0]]), ['hello world'], always_visible=always_visible)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_set_background():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.set_background('k')
    plotter.background_color = "yellow"
    plotter.set_background([0, 0, 0], top=[1,1,1]) # Gradient
    _ = plotter.background_color
    plotter.show()

    plotter = pyvista.Plotter(off_screen=OFF_SCREEN, shape=(1,2))
    plotter.set_background('orange')
    for renderer in plotter.renderers:
        assert renderer.GetBackground() == pyvista.parse_color('orange')
    plotter.show()

    plotter = pyvista.Plotter(off_screen=OFF_SCREEN, shape=(1,2))
    plotter.subplot(0,1)
    plotter.set_background('orange', all_renderers=False)
    assert plotter.renderers[0].GetBackground() != pyvista.parse_color('orange')
    assert plotter.renderers[1].GetBackground() == pyvista.parse_color('orange')
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_add_points():
    n = 10
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    points = np.random.random((n, 3))
    plotter.add_points(points, scalars=np.arange(10), cmap=None, flip_scalars=True)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_key_press_event():
    plotter = pyvista.Plotter(off_screen=False)
    plotter.key_press_event(None, None)
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_enable_picking_gc():
    plotter = pyvista.Plotter(off_screen=False)
    sphere = pyvista.Sphere()
    plotter.add_mesh(sphere)
    plotter.enable_cell_picking()
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_left_button_down():
    plotter = pyvista.Plotter(off_screen=False)
    if VTK9:
        with pytest.raises(ValueError):
            plotter.left_button_down(None, None)
    else:
        plotter.left_button_down(None, None)
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_show_axes():
    # if not closed correctly, a seg fault occurs when exitting
    plotter = pyvista.Plotter(off_screen=False)
    plotter.show_axes()
    plotter.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_update():
    plotter = pyvista.Plotter(off_screen=True)
    plotter.update()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_cell_arrays():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    scalars = np.arange(sphere.n_faces)
    plotter.add_mesh(sphere, interpolate_before_map=True, scalars=scalars,
                     n_colors=5, rng=10)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_clim():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    scalars = np.arange(sphere.n_faces)
    plotter.add_mesh(sphere, interpolate_before_map=True, scalars=scalars,
                     n_colors=5, clim=10)
    plotter.show()
    assert plotter.mapper.GetScalarRange() == (-10, 10)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_invalid_n_arrays():
    with pytest.raises(ValueError):
        plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
        plotter.add_mesh(sphere, scalars=np.arange(10))
        plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_arrow():
    cent = np.random.random(3)
    direction = np.random.random(3)
    pyvista.plot_arrows(cent, direction, off_screen=OFF_SCREEN)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_arrows():
    cent = np.random.random((100, 3))
    direction = np.random.random((100, 3))
    pyvista.plot_arrows(cent, direction, off_screen=OFF_SCREEN)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_axes():
    plotter = pyvista.Plotter(off_screen=True)
    plotter.add_axes()
    plotter.add_mesh(pyvista.Sphere())
    plotter.show()
    plotter = pyvista.Plotter(off_screen=True)
    plotter.add_orientation_widget(pyvista.Cube())
    plotter.add_mesh(pyvista.Cube())
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_box_axes():
    plotter = pyvista.Plotter(off_screen=True)
    plotter.add_axes(box=True, box_args={'color_box':True})
    plotter.add_mesh(pyvista.Sphere())
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_screenshot(tmpdir):
    plotter = pyvista.Plotter(off_screen=True)
    plotter.add_mesh(pyvista.Sphere())
    img = plotter.screenshot(transparent_background=True)
    assert np.any(img)
    img_again = plotter.screenshot()
    assert np.any(img_again)
    filename = str(tmpdir.mkdir("tmpdir").join('export-graphic.svg'))
    plotter.save_graphic(filename)

    # checking if plotter closes
    ref = proxy(plotter)
    plotter.close()

    try:
        ref
    except:
        raise RuntimeError('Plotter did not close')

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
@pytest.mark.parametrize('ext', SUPPORTED_FORMATS)
def test_save_screenshot(tmpdir, sphere, ext):
    filename = str(tmpdir.mkdir("tmpdir").join('tmp' + ext))
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.screenshot(filename)
    assert os.path.isfile(filename)
    assert Path(filename).stat().st_size

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_scalars_by_name():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    data = examples.load_uniform()
    plotter.add_mesh(data, scalars='Spatial Cell Data')
    plotter.show()

def test_themes():
    pyvista.set_plot_theme('paraview')
    pyvista.set_plot_theme('document')
    pyvista.set_plot_theme('night')
    pyvista.set_plot_theme('default')

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_multi_block_plot():
    multi = pyvista.MultiBlock()
    multi.append(examples.load_rectilinear())
    uni = examples.load_uniform()
    arr = np.random.rand(uni.n_cells)
    uni.cell_arrays.append(arr, 'Random Data')
    multi.append(uni)
    # And now add a data set without the desired array and a NULL component
    multi[3] = examples.load_airplane()
    with pytest.raises(ValueError):
        # The scalars are not available in all datasets so raises ValueError
        multi.plot(scalars='Random Data', off_screen=OFF_SCREEN, multi_colors=True)
    multi.plot(off_screen=OFF_SCREEN, multi_colors=True)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_clear():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.clear()
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_texture():
    """"Test adding a texture to a plot"""
    globe = examples.load_globe()
    texture = examples.load_globe_texture()
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(globe, texture=texture)
    plotter.show()
    texture.plot(off_screen=OFF_SCREEN)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_texture_associated():
    """"Test adding a texture to a plot"""
    globe = examples.load_globe()
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(globe, texture=True)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_read_texture_from_numpy():
    """"Test adding a texture to a plot"""
    globe = examples.load_globe()
    texture = pyvista.numpy_to_texture(imageio.imread(examples.mapfile))
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(globe, texture=texture)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_rgb():
    """"Test adding a texture to a plot"""
    cube = pyvista.Cube()
    cube.clear_arrays()
    x_face_color = (255, 0, 0)
    y_face_color = (0, 255, 0)
    z_face_color = (0, 0, 255)
    face_colors = np.array([x_face_color,
                            x_face_color,
                            y_face_color,
                            y_face_color,
                            z_face_color,
                            z_face_color,
                            ], dtype=np.uint8)
    cube.cell_arrays['face_colors'] = face_colors
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(cube, scalars='face_colors', rgb=True)
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_multi_component_array():
    """"Test adding a texture to a plot"""
    image = pyvista.UniformGrid((3,3,3))
    image['array'] = np.random.randn(*image.dimensions).ravel(order='f')
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(image, scalars='array')
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_camera():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(sphere)
    plotter.view_isometric()
    plotter.reset_camera()
    plotter.view_xy()
    plotter.view_xz()
    plotter.view_yz()
    plotter.add_mesh(examples.load_uniform(), reset_camera=True, culling=True)
    plotter.view_xy(True)
    plotter.view_xz(True)
    plotter.view_yz(True)
    plotter.show()
    plotter.camera_position = None

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_multi_renderers():
    plotter = pyvista.Plotter(shape=(2, 2), off_screen=OFF_SCREEN)

    plotter.subplot(0, 0)
    plotter.add_text('Render Window 0', font_size=30)
    sphere = pyvista.Sphere()
    plotter.add_mesh(sphere, scalars=sphere.points[:, 2])
    plotter.add_scalar_bar('Z', vertical=True)

    plotter.subplot(0, 1)
    plotter.add_text('Render Window 1', font_size=30)
    plotter.add_mesh(pyvista.Cube(), show_edges=True)

    plotter.subplot(1, 0)
    plotter.add_text('Render Window 2', font_size=30)
    plotter.add_mesh(pyvista.Arrow(), color='y', show_edges=True)

    plotter.subplot(1, 1)
    plotter.add_text('Render Window 3', position=(0., 0.),
                     font_size=30, viewport=True)
    plotter.add_mesh(pyvista.Cone(), color='g', show_edges=True,
                     culling=True)
    plotter.add_bounding_box(render_lines_as_tubes=True, line_width=5)
    plotter.show_bounds(all_edges=True)

    plotter.update_bounds_axes()
    plotter.show()

    # Test subplot indices (2 rows by 1 column)
    plotter = pyvista.Plotter(shape=(2, 1), off_screen=OFF_SCREEN)
    # First row
    plotter.subplot(0,0)
    plotter.add_mesh(pyvista.Sphere())
    # Second row
    plotter.subplot(1,0)
    plotter.add_mesh(pyvista.Cube())
    plotter.show()

    # Test subplot indices (1 row by 2 columns)
    plotter = pyvista.Plotter(shape=(1, 2), off_screen=OFF_SCREEN)
    # First column
    plotter.subplot(0,0)
    plotter.add_mesh(pyvista.Sphere())
    # Second column
    plotter.subplot(0,1)
    plotter.add_mesh(pyvista.Cube())
    plotter.show()

    with pytest.raises(IndexError):
        # Test bad indices
        plotter = pyvista.Plotter(shape=(1, 2), off_screen=OFF_SCREEN)
        plotter.subplot(0,0)
        plotter.add_mesh(pyvista.Sphere())
        plotter.subplot(1,0)
        plotter.add_mesh(pyvista.Cube())
        plotter.show()

    # Test subplot 3 on left, 1 on right
    plotter = pyvista.Plotter(shape='3|1', off_screen=OFF_SCREEN)
    # First column
    plotter.subplot(0)
    plotter.add_mesh(pyvista.Sphere())
    plotter.subplot(1)
    plotter.add_mesh(pyvista.Cube())
    plotter.subplot(2)
    plotter.add_mesh(pyvista.Cylinder())
    plotter.subplot(3)
    plotter.add_mesh(pyvista.Cone())
    plotter.show()

    # Test subplot 3 on bottom, 1 on top
    plotter = pyvista.Plotter(shape='1|3', off_screen=OFF_SCREEN)
    # First column
    plotter.subplot(0)
    plotter.add_mesh(pyvista.Sphere())
    plotter.subplot(1)
    plotter.add_mesh(pyvista.Cube())
    plotter.subplot(2)
    plotter.add_mesh(pyvista.Cylinder())
    plotter.subplot(3)
    plotter.add_mesh(pyvista.Cone())
    plotter.show()

def test_subplot_groups():
    plotter = pyvista.Plotter(shape=(3,3), groups=[(1,[1,2]),(np.s_[:],0)])
    plotter.subplot(0,0)
    plotter.add_mesh(pyvista.Sphere())
    plotter.subplot(0,1)
    plotter.add_mesh(pyvista.Cube())
    plotter.subplot(0,2)
    plotter.add_mesh(pyvista.Arrow())
    plotter.subplot(1,1)
    plotter.add_mesh(pyvista.Cylinder())
    plotter.subplot(2,1)
    plotter.add_mesh(pyvista.Cone())
    plotter.subplot(2,2)
    plotter.add_mesh(pyvista.Box())
    # Test group overlap
    with pytest.raises(AssertionError):
        # Partial overlap
        pyvista.Plotter(shape=(3,3),groups=[([1,2],[0,1]),([0,1],[1,2])])
    with pytest.raises(AssertionError):
        # Full overlap (inner)
        pyvista.Plotter(shape=(4,4),groups=[(np.s_[:],np.s_[:]),([1,2],[1,2])])
    with pytest.raises(AssertionError):
        # Full overlap (outer)
        pyvista.Plotter(shape=(4,4),groups=[(1,[1,2]),([0,3],np.s_[:])])

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_link_views():
    plotter = pyvista.Plotter(shape=(1, 4), off_screen=OFF_SCREEN)
    sphere = pyvista.Sphere()
    plotter.subplot(0, 0)
    plotter.add_mesh(sphere, smooth_shading=False, show_edges=False)
    plotter.subplot(0, 1)
    plotter.add_mesh(sphere, smooth_shading=True, show_edges=False)
    plotter.subplot(0, 2)
    plotter.add_mesh(sphere, smooth_shading=False, show_edges=True)
    plotter.subplot(0, 3)
    plotter.add_mesh(sphere, smooth_shading=True, show_edges=True)
    with pytest.raises(TypeError):
        plotter.link_views(views='foo')
    plotter.link_views([0, 1])
    plotter.link_views()
    with pytest.raises(TypeError):
        plotter.unlink_views(views='foo')
    plotter.unlink_views([0, 1])
    plotter.unlink_views(2)
    plotter.unlink_views()
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_orthographic_slicer():
    data = examples.load_uniform()
    data.set_active_scalars('Spatial Cell Data')

    slices = data.slice_orthogonal()

    # Orthographic Slicer
    p = pyvista.Plotter(shape=(2,2), off_screen=OFF_SCREEN)

    p.subplot(1,1)
    p.add_mesh(slices, clim=data.get_data_range())
    p.add_axes()
    p.enable()

    p.subplot(0,0)
    p.add_mesh(slices['XY'])
    p.view_xy()
    p.disable()

    p.subplot(0,1)
    p.add_mesh(slices['XZ'])
    p.view_xz(negative=True)
    p.disable()

    p.subplot(1,0)
    p.add_mesh(slices['YZ'])
    p.view_yz()
    p.disable()

    p.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_remove_actor():
    data = examples.load_uniform()
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_mesh(data, name='data')
    plotter.add_mesh(data, name='data')
    plotter.add_mesh(data, name='data')
    plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_image_properties():
    mesh = examples.load_uniform()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.show(auto_close=False) # DO NOT close plotter
    # Get RGB image
    _ = p.image
    # Get the depth image
    _ = p.get_image_depth()
    p.close()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.store_image = True
    assert p.store_image is True
    p.show() # close plotter
    # Get RGB image
    _ = p.image
    # Get the depth image
    _ = p.get_image_depth()
    p.close()

    # gh-920
    rr = np.array(
        [[-0.5, -0.5, 0], [-0.5, 0.5, 1], [0.5, 0.5, 0], [0.5, -0.5, 1]])
    tris = np.array([[3, 0, 2, 1], [3, 2, 0, 3]])
    mesh = pyvista.PolyData(rr, tris)
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh, color=True)
    p.renderer.camera_position = (0., 0., 1.)
    p.renderer.ResetCamera()
    p.enable_parallel_projection()
    assert p.renderer.camera_set
    p.show(interactive=False, auto_close=False)
    img = p.get_image_depth(fill_value=0.)
    rng = np.ptp(img)
    assert 0.3 < rng < 0.4, rng  # 0.3313504 in testing
    p.close()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_volume_rendering():
    # Really just making sure no errors are thrown
    vol = examples.load_uniform()
    vol.plot(off_screen=OFF_SCREEN, volume=True, opacity='linear')

    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.add_volume(vol, opacity='sigmoid', cmap='jet', n_colors=15)
    plotter.show()

    # Now test MultiBlock rendering
    data = pyvista.MultiBlock(dict(a=examples.load_uniform(),
                                   b=examples.load_uniform(),
                                   c=examples.load_uniform(),
                                   d=examples.load_uniform(),))
    data['a'].rename_array('Spatial Point Data', 'a')
    data['b'].rename_array('Spatial Point Data', 'b')
    data['c'].rename_array('Spatial Point Data', 'c')
    data['d'].rename_array('Spatial Point Data', 'd')
    data.plot(off_screen=OFF_SCREEN, volume=True, multi_colors=True, )

    # Check that NumPy arrays work
    arr = vol["Spatial Point Data"].reshape(vol.dimensions)
    pyvista.plot(arr, off_screen=OFF_SCREEN, volume=True, opacity='linear')

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_compar_four():
    # Really just making sure no errors are thrown
    mesh = examples.load_uniform()
    data_a = mesh.contour()
    data_b = mesh.threshold_percent(0.5)
    data_c = mesh.decimate_boundary(0.5)
    data_d = mesh.glyph()
    pyvista.plot_compare_four(data_a, data_b, data_c, data_d,
                              disply_kwargs={'color':'w'},
                              plotter_kwargs={'off_screen':OFF_SCREEN},)
    return

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_depth_peeling():
    mesh = examples.load_airplane()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.enable_depth_peeling()
    p.disable_depth_peeling()
    p.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
@pytest.mark.skipif(os.name == 'nt', reason="No testing on windows for EDL")
def test_plot_eye_dome_lighting():
    mesh = examples.load_airplane()
    mesh.plot(off_screen=OFF_SCREEN, eye_dome_lighting=True)
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.enable_eye_dome_lighting()
    p.show()

    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh)
    p.enable_eye_dome_lighting()
    p.disable_eye_dome_lighting()
    p.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_opacity_by_array():
    mesh = examples.load_uniform()
    opac = mesh['Spatial Point Data'] / mesh['Spatial Point Data'].max()
    # Test with opacity array
    mesh['opac'] = opac
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh, scalars='Spatial Point Data', opacity='opac',)
    p.show()
    # Test with uncertainty array (transparency)
    mesh['unc'] = opac
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh, scalars='Spatial Point Data', opacity='unc',
               use_transparency=True)
    p.show()
    # Test using mismatched arrays
    with pytest.raises(ValueError):
        p = pyvista.Plotter(off_screen=OFF_SCREEN)
        p.add_mesh(mesh, scalars='Spatial Cell Data', opacity='unc',)
        p.show()
    # Test with user defined transfer function
    opacities = [0,0.2,0.9,0.2,0.1]
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh, scalars='Spatial Point Data', opacity=opacities,)
    p.show()

def test_opacity_transfer_functions():
    n = 256
    mapping = pyvista.opacity_transfer_function('linear', n)
    assert len(mapping) == n
    mapping = pyvista.opacity_transfer_function('sigmoid_10', n)
    assert len(mapping) == n
    with pytest.raises(KeyError):
        mapping = pyvista.opacity_transfer_function('foo', n)
    with pytest.raises(RuntimeError):
        mapping = pyvista.opacity_transfer_function(np.linspace(0, 1, 2*n), n)
    foo = np.linspace(0, n, n)
    mapping = pyvista.opacity_transfer_function(foo, n)
    assert np.allclose(foo, mapping)
    foo = [0,0.2,0.9,0.2,0.1]
    mapping = pyvista.opacity_transfer_function(foo, n, interpolate=False)
    assert len(mapping) == n
    foo = [3, 5, 6, 10]
    mapping = pyvista.opacity_transfer_function(foo, n)
    assert len(mapping) == n

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_closing_and_mem_cleanup():
    n = 5
    for _ in range(n):
        for _ in range(n):
            p = pyvista.Plotter(off_screen=OFF_SCREEN)
            for k in range(n):
                p.add_mesh(pyvista.Sphere(radius=k))
            p.show()
        pyvista.close_all()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_above_below_scalar_range_annotations():
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(examples.load_uniform(), clim=[100, 500], cmap='viridis',
               below_color='blue', above_color='red')
    p.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_user_annotations_scalar_bar():
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(examples.load_uniform(), annotations={100.:'yum'})
    p.show()
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_volume(examples.load_uniform(), annotations={100.:'yum'})
    p.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_plot_string_array():
    mesh = examples.load_uniform()
    labels = np.empty(mesh.n_cells, dtype='<U10')
    labels[:] = 'High'
    labels[mesh['Spatial Cell Data'] < 300] = 'Medium'
    labels[mesh['Spatial Cell Data'] < 100] = 'Low'
    mesh['labels'] = labels
    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    p.add_mesh(mesh, scalars='labels')
    p.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_fail_plot_table():
    """Make sure tables cannot be plotted"""
    table = pyvista.Table(np.random.rand(50, 3))
    with pytest.raises(TypeError):
        pyvista.plot(table)
    with pytest.raises(TypeError):
        plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
        plotter.add_mesh(table)

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_bad_keyword_arguments():
    """Make sure bad keyword arguments raise an error"""
    mesh = examples.load_uniform()
    with pytest.raises(TypeError):
        pyvista.plot(mesh, foo=5, off_screen=OFF_SCREEN)
    with pytest.raises(TypeError):
        pyvista.plot(mesh, scalar=mesh.active_scalars_name, off_screen=OFF_SCREEN)
    with pytest.raises(TypeError):
        plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
        plotter.add_mesh(mesh, scalar=mesh.active_scalars_name)
        plotter.show()
    with pytest.raises(TypeError):
        plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
        plotter.add_mesh(mesh, foo="bad")
        plotter.show()

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_cmap_list():
    mesh = sphere.copy()

    n = mesh.n_points
    scalars = np.empty(n)
    scalars[:n//3] = 0
    scalars[n//3:2*n//3] = 1
    scalars[2*n//3:] = 2

    with pytest.raises(TypeError):
        mesh.plot(off_screen=OFF_SCREEN,
                  scalars=scalars, cmap=['red', None, 'blue'])

    mesh.plot(off_screen=OFF_SCREEN,
              scalars=scalars, cmap=['red', 'green', 'blue'])

@pytest.mark.skipif(NO_PLOTTING, reason="Requires system to support plotting")
def test_default_name_tracking():
    N = 10
    color = "tan"

    p = pyvista.Plotter(off_screen=OFF_SCREEN)
    for i in range(N):
        for j in range(N):
            center = (i, j, 0)
            mesh = pyvista.Sphere(center=center)
            p.add_mesh(mesh, color=color)
    n_made_it = len(p.renderer._actors)
    p.show()
    assert n_made_it == N**2

    # release attached scalars
    mesh.ReleaseData()
    del mesh

@pytest.mark.parametrize("as_global", [True, False])
def test_add_background_image(as_global):
    plotter = pyvista.Plotter()
    plotter.add_mesh(sphere)
    plotter.add_background_image(examples.mapfile, as_global=as_global)
    plotter.show()

def test_add_background_image_subplots():
    pl = pyvista.Plotter(shape=(2, 2))
    pl.add_background_image(examples.mapfile, scale=1, as_global=False)
    pl.add_mesh(examples.load_airplane())
    pl.subplot(1, 1)
    pl.add_background_image(examples.mapfile, scale=1, as_global=False)
    pl.add_mesh(examples.load_airplane())
    pl.remove_background_image()

    # should error out as there's no background
    with pytest.raises(RuntimeError):
        pl.remove_background_image()

    pl.add_background_image(examples.mapfile, scale=1, as_global=False)
    pl.show()

def test_add_remove_floor():
    pl = pyvista.Plotter()
    pl.add_mesh(sphere)
    pl.add_floor(color='b', line_width=2, lighting=True)
    pl.add_bounding_box()  # needed for update_bounds_axes
    assert len(pl.renderer._floors) == 1
    pl.add_mesh(sphere_b)
    pl.update_bounds_axes()
    assert len(pl.renderer._floors) == 1
    pl.show()

    pl = pyvista.Plotter()
    pl.add_mesh(sphere)
    pl.add_floor(color='b', line_width=2, lighting=True)
    pl.remove_floors()
    assert not pl.renderer._floors
    pl.show()

def test_reset_camera_clipping_range():
    pl = pyvista.Plotter()
    pl.add_mesh(sphere)

    default_clipping_range = pl.camera.GetClippingRange() # get default clipping range
    assert default_clipping_range != (10,100) # make sure we assign something different than default

    pl.camera.SetClippingRange(10,100) # set clipping range to some random numbers
    assert pl.camera.GetClippingRange() == (10,100) # make sure assignment is successful

    pl.reset_camera_clipping_range()
    assert pl.camera.GetClippingRange() ==  default_clipping_range
    assert pl.camera.GetClippingRange() != (10,100)

def test_index_vs_loc():
    # first: 2d grid
    pl = pyvista.Plotter(shape=(2, 3))
    # index_to_loc valid cases
    vals = [0, 2, 4]
    expecteds = [(0, 0), (0, 2), (1, 1)]
    for val,expected in zip(vals, expecteds):
        assert tuple(pl.index_to_loc(val)) == expected
    # loc_to_index valid cases
    vals = [(0, 0), (0, 2), (1, 1)]
    expecteds = [0, 2, 4]
    for val,expected in zip(vals, expecteds):
        assert pl.loc_to_index(val) == expected
        assert pl.loc_to_index(expected) == expected
    # failing cases
    with pytest.raises(TypeError):
        pl.loc_to_index({1, 2})
    with pytest.raises(TypeError):
        pl.index_to_loc(1.5)
    with pytest.raises(TypeError):
        pl.index_to_loc((1, 2))

    # then: "1d" grid
    pl = pyvista.Plotter(shape='2|3')
    # valid cases
    for val in range(5):
        assert pl.index_to_loc(val) == val
        assert pl.index_to_loc(np.int_(val)) == val
        assert pl.loc_to_index(val) == val
        assert pl.loc_to_index(np.int_(val)) == val


''' This code demonstrate how to play different tones on Buzzer '''

from picoder import BUZZERTONE  # Import the BUZZERTONE class from the picoder module
from time import sleep   # Import the sleep function from the time module

# Create an instance of the BUZZERTONE class
bzrtone = BUZZERTONE()

# Run an infinite loop
while 1:
    bzrtone.play(512,5000) #send frequency, loudness to play tone on Buzzer. Loudness -> 0-5000
    sleep(0.5)

    bzrtone.stop() #to stop buzzer
    sleep(0.5)


#!/usr/bin/python -u
import sys
import os
import random, time
from PIL import Image

def disable_stdout_buffering():
    import gc
    gc.garbage.append(sys.stdout)
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

disable_stdout_buffering()

def cap_gen():
    img = []
    sol = []
    for i in range(4):
        r = random.randint(65, 90)
        sol.append(chr(r))
        img.append('static/char(' + str(r) + ').png')

    images = map(Image.open, img)
    widths, heights = zip(*(i.size for i in images))

    total_width = sum(widths)
    max_height = max(heights)

    new_im = Image.new('RGB', (total_width, max_height))

    x_offset = 0
    for im in images:
        new_im.paste(im, (x_offset,0))
        x_offset += im.size[0]

    return new_im, ''.join(sol)

def p(txt):
    sys.stdout.write(txt + "\r\n")
    sys.stdout.flush()

p("Welcome to Captcha Forest")
p("In order to get the flag, you must cut through 200 captcha trees.")
p("I will send you captcha in png format (hex encoded), you must solve the captcha and give me correct answers to proceed further")
p("Hint: I have used Bill Cipher mappings for captchas, good luck :)")
raw_input("--- press Enter to continue ---\r\n")

for i in range(200):
    im, ans = cap_gen()
    nm = random.randint(10000, 100000)
    name = 'temp/' + str(nm) + '.png'
    im.save(name, 'PNG')
    print(open(name, 'rb').read().encode('hex'))
    os.remove(name)
    got = raw_input("--- Type Answer to provided captcha {} ---\r\n".format(i+1)).strip()
    if got == ans:
        p("Correct!")
        raw_input("--- press Enter to continue ---\r\n")
    else:
        p("Wrong, Bye bye!")
        sys.exit()

p(open('flag.txt', 'r').read())


from typing import List, Tuple, Union
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.models import Variable
from sqlalchemy.dialects.postgresql import insert
from datetime import datetime, date
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement

from plugins.db_models.models import HouseListing, PriceListing, Session
from plugins.firefox_driver.driver import RemoteFirefoxWebDriver
from plugins.firefox_driver.utils.helpers import get_web_elements
from plugins.geolocation.geolocation import get_geolocation
from plugins.utils.helpers import (
    extract_float,
    extract_integer,
    split_address,
)

def extract_house_data(
    marker: WebElement, driver: RemoteFirefoxWebDriver
) -> Tuple[Union[HouseListing, None], Union[PriceListing, None]]:
    try:
        marker.click()
        info: WebElement = get_web_elements(
            driver, By.CLASS_NAME, "top-line-container"
        )[0]
    except Exception as e:
        return None, None
    try:
        specs: List[WebElement] = info.find_elements(
            By.CLASS_NAME, "property-info-container"
        )
        children: List[WebElement] = specs[0].find_elements(By.TAG_NAME, "li")
        city, state, zip_code = split_address(
            info.find_element(By.CLASS_NAME, "property-city-state-zip").text
        )
        address = info.find_element(By.CLASS_NAME, "property-address").text
        if children != []:
            longitude, latitude = get_geolocation(address, city, state, zip_code)
            house = HouseListing(
                address=address,
                city=city,
                state=state,
                zip=zip_code,
                beds=extract_integer(children[0].text),
                baths=extract_float(children[1].text),
                sqft=extract_integer(children[2].text),
                longitude=longitude,
                latitude=latitude,
            )

            price = PriceListing(
                address=info.find_element(By.CLASS_NAME, "property-address").text,
                city=city,
                state=state,
                zip=zip_code,
                price=extract_integer(
                    info.find_element(By.CLASS_NAME, "property-price").text
                ),
                date=date.today(),
            )
            return house, price
    except Exception as e:
        return None, None

def insert_data(houses: HouseListing, pricing: PriceListing):
    session = Session()
    house_dicts = [
        {
            key: value
            for key, value in house.__dict__.items()
            if not key.startswith("_sa_")
        }
        for house in houses
    ]
    stmt_house = (
        insert(HouseListing)
        .values(house_dicts)
        .on_conflict_do_nothing(index_elements=["address", "city", "state", "zip"])
    )
    price_dicts = [
        {
            key: value
            for key, value in price.__dict__.items()
            if not key.startswith("_sa_")
        }
        for price in pricing
    ]
    stmt_pricing = (
        insert(PriceListing)
        .values(price_dicts)
        .on_conflict_do_nothing(
            index_elements=["address", "city", "state", "zip", "date"]
        )
    )

    try:
        session.execute(stmt_house)
        session.execute(stmt_pricing)
        session.commit()
    except Exception as e:
        print(e)
    finally:
        session.close()

def _scraper(url: str):
    houses: list[HouseListing] = []
    pricing: list[PriceListing] = []
    with RemoteFirefoxWebDriver() as driver:
        driver.get(url)
        markers: List[WebElement] = get_web_elements(
            driver, By.CLASS_NAME, "custom-pin-image"
        )
        for marker in markers:
            house, price = extract_house_data(marker, driver)
            if house and price:
                houses.append(house)
                pricing.append(price)
    insert_data(houses, pricing)

with DAG(
    "scrape_house_listings",
    start_date=datetime(2023, 9, 1),
    schedule_interval="@monthly",
    catchup=False,
) as dag:
    prev_task = None
    base_url = Variable.get("house_listing_url")
    for location in Variable.get("house_listing_locations").split(","):
        for size in Variable.get("house_listing_sizes").split(","):
            county, coords = location.split("?")
            url = f"{base_url}/{county}/{size}/?{coords}"

            scrape_task = PythonOperator(
                task_id=f"scrape_{county}_{size}",
                python_callable=_scraper,
                op_args=[url],
                provide_context=True,
            )

            if prev_task:
                prev_task >> scrape_task

            prev_task = scrape_task


import os
from openpyxl import load_workbook
import openpyxl

import argparse

def parce_folder():
    # Parse input params
    parser = argparse.ArgumentParser()
    parser.add_argument('--folder', type=str, help="Folder (path to results)")
    args, unknown = parser.parse_known_args()
    folder = getattr(args, 'folder')

    return folder

### Start
print('Use example: result_transform.py --folder="D:\Dropbox\Exchange\! ML new test results\btc"')

folder = parce_folder()
#cwd = os.getcwd()

column = 1

# Create the file
filepath = "{}/results_processed.xlsx".format(folder)
wb = openpyxl.Workbook()
wb.save(filepath)

wb = load_workbook(filepath)
ws = wb.get_active_sheet()

for filename in os.listdir(folder):
    if filename.endswith(".log") and filename.find('summary') > 0:
        print (filename)
        with open('%s\\%s' % (folder, filename), 'r+') as file:
            row = 1
            line_original = file.readline()
            ws.cell(row = row, column = column).value = line_original
            row += 1
            while line_original !="":
                line_original = file.readline()

                # Write converted where possible
                line = line_original.replace('\n', '').replace('\r', '')
                try:
                    line = float(line)
                except:
                    pass

                line = ws.cell(row = row, column = column).value = line
                row += 1
        column += 1

wb.save(filepath)


import imghdr
import pathlib
from typing import Optional, NamedTuple

class FilesEditionResult(NamedTuple):
    number_of_edits: int
    edited_files: list[pathlib.Path]

def fix_folders_images_extensions(
    folder: pathlib.Path, dry: bool = False
) -> FilesEditionResult:
    """
    Goes around folder and looks for images files which extension in name
    mismatch detected image extension and fixes that.

    :param folder: an folder path wrapped in pathlib.Path.
    :param dry: doesn't actually edit files names.
    :return: amount of edited files and which files has been edited.
    """
    edited_files_count: int = 0
    edited_files: list[pathlib.Path] = []

    if not folder.is_dir():
        raise ValueError("Must get an actual folder to fix images")

    for image in folder.iterdir():
        if not image.is_file():
            continue

        possible_extension: Optional[str] = imghdr.what(image)
        if possible_extension is None:
            continue

        file_extension_detected: str = f".{possible_extension}"
        if image.suffix != file_extension_detected:
            if not dry:
                try:
                    image.rename(image.with_suffix(file_extension_detected))

                except FileExistsError:
                    continue

            edited_files_count += 1
            edited_files.append(image)

    return FilesEditionResult(edited_files_count, edited_files)


# Problem 1 : Map and Lambda Function

#Solution 1
cube = lambda x:pow(x,3)
def fib(n):
    l = [0,1]
    for i in range(2,n):
        l.append(l[i-2] + l[i-1])
    return l[0:n]
print(list(map(cube,fib(int(input())))))
____________________________________________________________________________________________________________________________________________
# Problem 2 : Validating Email Addresses With a Filter

#Solution 1
def fun(s):
    s_prcocess = s.replace('@','.').split('.')
    order = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468-_'
    if len(s_prcocess) == 3 and all(s_items != '' for s_items in s_prcocess):
        if (len(s_prcocess[2]) <= 3 and s_prcocess[1].isalnum() and all(item in order for item in s_prcocess[0])):
            return True
    return False

def filter_mail(emails):
    return list(filter(fun, emails))

if __name__ == '__main__':
    n = int(input())
    emails = []
    for _ in range(n):
        emails.append(input())

filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)
____________________________________________________________________________________________________________________________________________
# Problem 3 : Reduce Function

#Solution 1
from fractions import Fraction
from functools import reduce

def product(fracs):
    t = reduce(lambda x, y : x * y, fracs)
    return t.numerator, t.denominator

if __name__ == '__main__':
    fracs = []
    for _ in range(int(input())):
        fracs.append(Fraction(*map(int, input().split())))
    result = product(fracs)
    print(*result)