Best Python code snippet using autotest_python
checar
Source:checar  
1#!/usr/bin/python2# -*- coding: utf-8 -*-3import os4import glob5import subprocess6import sys7import argparse8##########################################################################9#Já que não dá pra usar ctrl-c pra parar o script isso simula o getch do C10##########################################################################11class _Getch:12    """Gets a single character from standard input.  Does not echo to the13screen."""14    def __init__(self):15        try:16            self.impl = _GetchWindows()17        except ImportError:18            self.impl = _GetchUnix()19    def __call__(self): return self.impl()20    21class _GetchUnix:22    def __init__(self):23        import tty, sys24    def __call__(self):25        import sys, tty, termios26        fd = sys.stdin.fileno()27        old_settings = termios.tcgetattr(fd)28        try:29            tty.setraw(sys.stdin.fileno())30            ch = sys.stdin.read(1)31        finally:32            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)33        return ch34        35class _GetchWindows:36    def __init__(self):37        import msvcrt38    def __call__(self):39        import msvcrt40        return msvcrt.getch()41        42#############################43#Cria as opções de argumentos44#############################45parser = argparse.ArgumentParser(description='Esse script auxilia no controle de qualidade ' \46	'dos projetos facilitando o processo, principalmente quando o controle é feito para múltiplos sujeitos.')47parser.add_argument('-p', '--project', help='Nome do projeto (completo ou abreviado). Esse argumento é obrigatório.', \48	dest='proj', action='store', required=True)49parser.add_argument('-v', '--visit', help='Especifica o número do diretório visit. Se não for especificado ' \50	'por default, será visit1. Utilize -v 0 caso não haja nenhum diretório visit no projeto.', \51	dest='vis', action='store', type=int, default=1, metavar='[1]')52parser.add_argument('-s','--subject', help='Especifica o(s) sujeito(s) para realizar o controle de qualidade. ' \53	'Se não for especificado, por default, todos serão usados.', \54	dest='subj', nargs='*',default=[])55parser.add_argument('-t', '--task', help='Especifica a(s) tarefa(s) para realizar o controle de qualidade. ' \56	'Se não for especificado, por default, todas serão usadas.', \57	dest='task', nargs='*',default=[])58parser.add_argument('-r', '--review', help='Especifica o tipo de controle de qualidade entre as opções ' \59	'[basic/driver/commands]. Se não for especificado, por default, será usado o [basic].', \60	choices=[ 'basic', 'driver', 'commands' ], dest='rvw', default='basic')61parser.add_argument('-a', '--analise', help='Especifica o tipo de análise ' \62	'[corregistro/ativacao]. Se não for especificado, nenhum é feito.', \63	choices=[ 'corregistro', 'ativacao' ], dest='ana')64args = parser.parse_args()65##############################66#Lista de variáveis aceitáveis67##############################68if args.proj == 'SCH' or args.proj == 'SCHOOLS':69	args.proj = 'SCHOOLS'70	sigla = 'SCH'71	72if args.proj == 'COC' or args.proj == 'PFERREIRA':73	args.proj = 'PFERREIRA'74	sigla = 'COC'75	76if args.proj == 'OB' or args.proj == 'OBESIDADE':77	args.proj = 'OBESIDADE'78	sigla = 'OB'79if args.proj == 'AMBAC':80	sigla = 'AMBAC'81	82if args.proj == 'RWM' or args.proj == 'Rohde_WM':83	args.proj = 'Rohde_WM'84	sigla = 'RWM'85if args.proj == 'CAT' or args.proj == 'MCRUCIUS':86	args.proj = 'MCRUCIUS'87	sigla = 'CAT'88if args.rvw == 'basic':89	args.rvw = 'dados'90elif args.rvw == 'driver':91	args.rvw = 'tcsh @ss_review_driver'92else:93	args.rvw = 'dados-full'94if os.path.isdir("/media/DATA/%s" % args.proj): # Verifica se o projeto existe em DATA95	print ('\nAbrindo '+args.proj+'...')96else:97	print "\n-> Erro: O projeto especificado não existe.\n"98	exit(-1)99#########################################100#Verifica os argumentos e roda os reviews101#########################################102if not args.subj:103	if args.vis == 0:104		tasks = sorted(glob.glob('/media/DATA/'+args.proj+'/'+sigla+'*''/PROC''*'))105		if not tasks:106			print '\nErro -> '+args.proj+' deve conter um diretório visit ou não deve possuir\ndados processados. Verifique.\n'107			exit(-1)108		else:109			for task_paths in tasks:110				print task_paths111	else:112		subjs_paths = sorted(glob.glob('/media/DATA/'+args.proj+'/'+sigla+'*''/visit%d' % +args.vis))113		if not subjs_paths:114			print '\nErro -> '+args.proj+' não possui o diretório visit especificado.'115			print 'OBS: Se não há diretório visit para '+args.proj+', considere usar -v 0.\n'116			exit(-1)117		else:118			for subj_path in subjs_paths:119##################################################################################################################120				if args.ana:121					for task in args.task:122						tasks = sorted(glob.glob(subj_path+'/PROC.'+task+'*'))123						if not tasks:124							print ('\nErro -> Não existe PROC.'+task+' em '+subj_path+'\n')125					for task in args.task:126						tasks = sorted(glob.glob(subj_path+'/PROC.'+task+'*'))127						for task_paths in tasks:128							print ('\nAbrindo review em '+task_paths)129							os.chdir(task_paths)130  							subprocess.call(args.ana,shell=True)131  							print "Pressione uma tecla para continuar ou 'q' para sair."132  							getch = _Getch()133  							if getch.impl() in ('q', 'Q'):134  								sys.exit(0)135  							else:136  								pass137##################################################################################################################138				if not args.task:139					tasks = sorted(glob.glob(subj_path+'/PROC''*'))140					if not tasks:141						print ('\nErro -> Não há dados processados em' +subj_path+'\n')142						exit(-1)143					else:144						for task_paths in tasks:145							print ('\nAbrindo review em '+task_paths)146							os.chdir(task_paths)147  							subprocess.call(args.rvw, shell=True)148  							print "Pressione uma tecla para continuar ou 'q' para sair."149  							getch = _Getch()150  							if getch.impl() in ('q', 'Q'):151								sys.exit(0)152							else:153								pass							154				else:155					for task in args.task:156						tasks = sorted(glob.glob(subj_path+'/PROC.'+task+'*'))157						if not tasks:158							print ('\nErro -> Não existe PROC.'+task+' em '+subj_path+'\n')159					for task in args.task:160						tasks = sorted(glob.glob(subj_path+'/PROC.'+task+'*'))161						for task_paths in tasks:162							print ('\nAbrindo review em '+task_paths)163							os.chdir(task_paths)164  							subprocess.call(args.rvw, shell=True)165  							print "Pressione uma tecla para continuar ou 'q' para sair."166  							getch = _Getch()167  							if getch.impl() in ('q', 'Q'):168  								sys.exit(0)169  							else:170  								pass171elif args.subj:172	for subjs in args.subj:173		print 'For loop'174		path = glob.glob('/media/DATA/'+args.proj+'/'+sigla+'*'+subjs)175		caminho1 = ''.join(path)176		if not os.path.isdir(caminho1):177			print ('\nErro -> '+sigla+'*'+subjs+' não existe! Verifique.\n')178			exit(-1)179		else:180			if args.vis == 0:181				caminho2 = glob.glob('/media/DATA/'+args.proj+'/'+sigla+'*'+subjs)182				subjs_paths = ''.join(caminho2)183				if not os.path.isdir(subjs_paths):184					print '\nErro -> '+sigla+'*'+subjs+' não possui o diretório visit especificado.'185					print 'OBS: Se não há diretório visit para '+sigla+'*'+subjs+', considere usar -v 0.\n'186					exit(-1)187				else:188					tasks = sorted(glob.glob('/media/DATA/'+args.proj+'/'+sigla+'*'+subjs+'/PROC''*'))189					if not tasks:190						print '\nErro -> '+subjs+' deve conter um diretório visit. Verifique.\n'191					else:192						for tasks_path in tasks:193							print tasks_path194							if args.ana:195								for task in args.task:196									tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))197									if not tasks:198										print ('\nErro -> Não existe '+task+ ' em '+subjs+'\n')199										exit(-1)200								for task in args.task:201									tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))202									for tasks_path in tasks:203										print ('\nAbrindo '+task+' em '+subjs+'...')204										os.chdir(tasks_path)205		  								subprocess.call(args.ana,shell=True)206		  								print "Pressione uma tecla para continuar ou 'q' para sair."207		  								getch = _Getch()208		  								if getch.impl() in ('q', 'Q'):209		  									sys.exit(0)210		  								else:211		  									pass212							if not args.task:213								tasks = sorted(glob.glob(subjs_paths+'/PROC''*'))214								if not tasks:215									print ('\nErro -> Não há dados processados em '+subjs+'\n')216								else:217									for tasks_path in tasks:218										print ('\nAbrindo '+tasks_path+' em '+subjs+'...')219										os.chdir(tasks_path)220										subprocess.call(args.rvw, shell=True)221		  								print "Pressione uma tecla para continuar ou 'q' para sair."222		  								getch = _Getch()223		  								if getch.impl() in ('q', 'Q'):224		  									sys.exit(0)225		  								else:226		  									pass227							else:228								for task in args.task:229									tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))230									if not tasks:231										print ('\nErro -> Não existe '+task+ ' em '+subjs+'\n')232										exit(-1)233								for task in args.task:234									tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))235									for tasks_path in tasks:236										print ('\nAbrindo '+task+' em '+subjs+'...')237										os.chdir(tasks_path)238		  								subprocess.call(args.rvw, shell=True)239		  								print "Pressione uma tecla para continuar ou 'q' para sair."240		  								getch = _Getch()241		  								if getch.impl() in ('q', 'Q'):242		  									sys.exit(0)243		  								else:244		  									pass245			else:246				caminho2 = glob.glob('/media/DATA/'+args.proj+'/'+sigla+'*'+subjs+'/visit%d' % +args.vis)247				subjs_paths = ''.join(caminho2)248				if not os.path.isdir(subjs_paths):249					print '\nErro -> '+sigla+'*'+subjs+' não possui o diretório visit especificado.'250					print 'OBS: Se não há diretório visit para '+sigla+'*'+subjs+', considere usar -v 0.\n'251					exit(-1)252				else:253##############################################################################################################254					if args.ana:255						for task in args.task:256							tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))257							if not tasks:258								print ('\nErro -> Não existe '+task+ ' em '+subjs+'\n')259								exit(-1)260							for task in args.task:261								tasks = sorted(glob.glob(subj_path+'/PROC.'+task+'*'))262								for tasks_path in tasks:263									print ('\nAbrindo '+task+' em '+subjs+'...')264									os.chdir(tasks_path)265	  								subprocess.call(args.ana,shell=True)266	  								print "Pressione uma tecla para continuar ou 'q' para sair."267	  								getch = _Getch()268	  								if getch.impl() in ('q', 'Q'):269	  									sys.exit(0)270	  								else:271	  									pass272############################################################################################################## 273					if not args.task:274						tasks = sorted(glob.glob(subjs_paths+'/PROC''*'))275						if not tasks:276							print ('\nErro -> Não há dados processados em '+subjs+'\n')277						else:278							for tasks_path in tasks:279								print ('\nAbrindo '+tasks_path+' em '+subjs+'...')280								os.chdir(tasks_path)281								subprocess.call(args.rvw, shell=True)282  								print "Pressione uma tecla para continuar ou 'q' para sair."283  								getch = _Getch()284  								if getch.impl() in ('q', 'Q'):285  									sys.exit(0)286  								else:287  									pass288					else:289						for task in args.task:290							tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))291							if not tasks:292								print ('\nErro -> Não existe '+task+ ' em '+subjs+'\n')293								exit(-1)294						for task in args.task:295							tasks = sorted(glob.glob(subjs_paths+'/PROC.'+task+'*'))296							for tasks_path in tasks:297								print ('\nAbrindo '+task+' em '+subjs+'...')298								os.chdir(tasks_path)299  								subprocess.call(args.rvw, shell=True)300  								print "Pressione uma tecla para continuar ou 'q' para sair."301  								getch = _Getch()302  								if getch.impl() in ('q', 'Q'):303  									sys.exit(0)304  								else:...inat.py
Source:inat.py  
1# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"). You4# may not use this file except in compliance with the License. A copy of5# the License is located at6#7#     http://aws.amazon.com/apache2.0/8#9# or in the "license" file accompanying this file. This file is10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF11# ANY KIND, either express or implied. See the License for the specific12# language governing permissions and limitations under the License.13import os14from collections import defaultdict15import json16from .dataset import ClassificationTaskDataset17class iNat2018Dataset(ClassificationTaskDataset):18    """iNaturalist 2018 Dataset19    Parameters20    ----------21    path : str (default None)22        path to dataset23        if None, search using DATA environment variable24    split : str (train|test)25        load provided split26    task_id : int (default 0)27        id of task28    level : str (default 'order')29        what level of taxonomy to create tasks30    metadata : dict (default empty)31        extra arbitrary metadata32    transform : callable (default None)33        Optional transform to be applied on a sample.34    target_transform : callable (default None)35        Optional transform to be applied on a label.36    """37    CATEGORIES_FILE = 'categories.json'38    TASKS_FILE = 'tasks.json'39    CLASS_TASKS_FILE = 'classes_tasks.json'40    TRAIN_2018_FILE = 'train2018.json'41    ORDER = 'order'42    CLASS = 'class'43    POSSIBLE_LEVELS = [ORDER, CLASS]44    TRAIN_SPLIT = 'train'45    VAL_SPLIT = 'val'46    POSSIBLE_SPLITS = [TRAIN_SPLIT, VAL_SPLIT]47    def __init__(self, root, split=TRAIN_SPLIT, task_id=0, level=ORDER,48                 metadata={}, transform=None, target_transform=None):49        assert isinstance(root, str)50        path = os.path.join(root, 'inat2018')51        assert os.path.exists(path), path52        assert split in iNat2018Dataset.POSSIBLE_SPLITS, split53        assert isinstance(task_id, int)54        assert level in iNat2018Dataset.POSSIBLE_LEVELS, level55        self.split = split56        # load categories57        with open(os.path.join(path, iNat2018Dataset.CATEGORIES_FILE)) as f:58            self.categories = json.load(f)59        # load or create set of tasks (corresponding to classification inside orders)60        tasks_path = os.path.join(path, iNat2018Dataset.TASKS_FILE) if level == 'order' else os.path.join(path,61                                                                                                          iNat2018Dataset.CLASS_TASKS_FILE)62        if not os.path.exists(tasks_path):63            self._create_tasks(tasks_path, path, level=level)64        with open(tasks_path) as f:65            self.tasks = json.load(f)66        annotation_file = os.path.join(path, "{}2018.json".format(split))67        assert os.path.exists(annotation_file), annotation_file68        with open(annotation_file) as f:69            j = json.load(f)70        annotations = j['annotations']71        images_list = [img['file_name'] for img in j['images']]72        # get labels73        task = self.tasks[task_id]74        species_ids = task['species_ids']75        species_ids = {k: i for i, k in enumerate(species_ids)}76        labels_list = [species_ids.get(a['category_id'], -1) for a in annotations]77        # throw away images we are not training on (identified by label==-1)78        images_list = [img for i, img in enumerate(images_list) if labels_list[i] != -1]79        labels_list = [l for l in labels_list if l != -1]80        # get label names81        label_names = {task['label_map'][str(l)]: n for l, n in zip(task['species_ids'], task['species_names'])}82        task_name = self.tasks[task_id]['name']83        super(iNat2018Dataset, self).__init__(images_list,84                                              labels_list,85                                              label_names=label_names,86                                              root=path,87                                              task_id=task_id,88                                              task_name=task_name,89                                              metadata=metadata,90                                              transform=transform,91                                              target_transform=target_transform)92    def _create_tasks(self, tasks_path, root, level=ORDER):93        """Create tasks file.94        Post-conditions:95            Creates a file96        Parameters97        ----------98        tasks_path : str99            path to tasks file to write100        root : str101            root folder to train file102        level : str (default 'order')103            what level of taxonomy to create tasks104        """105        assert level in iNat2018Dataset.POSSIBLE_LEVELS, level106        with open(os.path.join(root, iNat2018Dataset.TRAIN_2018_FILE)) as f:107            annotations = json.load(f)108        annotations = annotations['annotations']109        level_samples = defaultdict(list)110        for r in annotations:111            level_samples[self.categories[r['category_id']][level]].append(r['image_id'])112        tasks = []113        for i, (level_name, _) in enumerate(sorted(level_samples.items(), key=lambda x: len(x[1]), reverse=True)):114            species_in_level = sorted([(c['name'], c['id']) for c in self.categories if c[level] == level_name],115                                      key=lambda x: x[0])116            species_ids = {k: i for i, (_, k) in enumerate(species_in_level)}117            tasks.append({118                'id': i,119                'name': level_name,120                'species_names': [n for (n, i) in species_in_level],121                'species_ids': [i for (n, i) in species_in_level],122                'label_map': species_ids123            })124        with open(tasks_path, 'w') as f:...cli.py
Source:cli.py  
1import click2from linum import SvgRenderer3from linum.excel_renderer.excel_renderer import ExcelRenderer4from linum.txt_renderer.console_renderer import ConsoleRenderer5from linum.txt_renderer.txt_renderer import TxtRenderer6@click.command()7@click.argument('tasks_path', type=click.Path(exists=True))8@click.option('-o', '--out', type=click.Path(writable=True),9              help='Output file. If not specified then linum creates new file in current directory.')10@click.option('-r', '--renderer', default='CONSOLE', type=click.Choice(['CONSOLE', 'TXT', 'XLSX', 'SVG'], ),11              help="Renderer to use. "12                   "'CONSOLE' - for console printing. "13                   "'TXT' - for rendering txt file. "14                   "'XLSX' - for rendering xlsx file. "15                   "'SVG' - for rendering svg file. "16                   "Default is 'CONSOLE'.")17@click.option('-c', '--context', type=click.Path(exists=True),18              help="Context for renderer. It is YAML file with render settings. "19                   "If not specified then default settings will be applied.")20def cli(tasks_path, out, renderer, context):21    """ Command line interface for linum. """22    if renderer == 'CONSOLE':23        renderer = ConsoleRenderer(tasks_path, context)24    elif renderer == 'TXT':25        renderer = TxtRenderer(tasks_path, context, out)26    elif renderer == 'XLSX':27        renderer = ExcelRenderer(tasks_path, context, out)28    elif renderer == 'SVG':29        renderer = SvgRenderer(tasks_path, context, out)30    renderer.render()31if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
