Best Python code snippet using autotest_python
retino_dataset.py
Source:retino_dataset.py
1import os2import zipfile3from os import path4from typing import List, Tuple, Any, Dict, Union5import numpy6import sklearn as sklearn7from PIL import Image8from google.cloud.storage import Client9from numpy import asarray, full, ndarray10_TRAIN_URL = "https://storage.googleapis.com/face-mask-recognition-dataset/train.zip"11_TEST_URL = "https://storage.googleapis.com/face-mask-recognition-dataset/test.zip"12class RetimoDatasetConfigRecord:13 def __init__(self, dataset_name: str, name: str, gcs_path: str, labels: dict):14 self.dataset_name = dataset_name15 self.name = name16 self.gcs_path = gcs_path17 self.labels = labels18 self.local_path = None19 self.is_downloaded = False20 self.is_unzipped = False21 def add_local_path(self, local_path):22 self.local_path = local_path23 self.is_downloaded = True24 return self25 def unzipped(self):26 self.is_unzipped = True27 return self28 @property29 def unzipped_path(self):30 if not self.is_unzipped:31 raise Exception("Unzipped Path is not ready. Firstly unzip to downloaded files.")32 return f"{self.local_path}/unziped"33 @property34 def raw_path(self):35 if not self.is_downloaded and self.local_path is None:36 raise Exception("Row Path is not ready. Firstly download to local files.")37 return f"{self.local_path}/raw"38class RetimoDataset:39 cache_path = '.cache'40 def __init__(self, config_records: List[RetimoDatasetConfigRecord]):41 self.config_records = config_records42 self.storage_client = Client()43 def load(self, to_shuffle=True):44 self.config_records = [self._download(config_record) for config_record in self.config_records]45 self.config_records = [self._unzip(config_record) for config_record in self.config_records]46 arrays = dict(self._load_to_nparray(config_record) for config_record in self.config_records)47 if to_shuffle:48 values = arrays.values()49 y = {x for x in values}50 values_2 = values.values()51 shuffeled = sklearn.utils.shuffle()52 return arrays53 def _download(self, config_record: RetimoDatasetConfigRecord) -> RetimoDatasetConfigRecord:54 local_path = f"{self.cache_path}/{config_record.dataset_name}/{config_record.name}"55 os.makedirs(local_path, exist_ok=True)56 raw_path = f"{local_path}/raw"57 if not path.exists(raw_path):58 with open(raw_path, "w") as f:59 f.write("")60 print(f"Downloading raw data from {config_record.gcs_path} to {raw_path}")61 with open(raw_path, 'wb') as file_obj:62 self.storage_client.download_blob_to_file(config_record.gcs_path, file_obj)63 else:64 print(f"Downloading raw data for '{config_record.name}' not needed. Using cache '{raw_path}'")65 return config_record.add_local_path(local_path)66 def _unzip(self, config_record: RetimoDatasetConfigRecord) -> RetimoDatasetConfigRecord:67 unzipped_path = f"{config_record.local_path}/unziped"68 if not path.exists(unzipped_path):69 print(f"Unzipping file {config_record.raw_path} to {unzipped_path}")70 with zipfile.ZipFile(config_record.raw_path, 'r') as zip_ref:71 zip_ref.extractall(unzipped_path)72 else:73 print(f"Unzipping file for '{config_record.name}' not needed. Using cache '{unzipped_path}'")74 return config_record.unzipped()75 def _load_to_nparray(self, config_record: RetimoDatasetConfigRecord) -> Tuple[str, Dict[str, Union[ndarray, Any]]]:76 collector = {}77 for label in config_record.labels.keys():78 directory = f"{os.getcwd()}/{config_record.unzipped_path}/{config_record.name}/{label}/"79 dataset = numpy.asarray(80 [asarray(Image.open(f"{directory}/{image}"), dtype=numpy.uint8) for image in os.listdir(directory) if81 image.endswith('.jpg')])82 label_list = full((len(dataset)), fill_value=config_record.labels[label], dtype=numpy.uint8)83 collector['dataset'] = numpy.append(collector.get('dataset', numpy.empty(0)), dataset).reshape(84 dataset.shape[0] + collector.get('dataset', numpy.empty(0)).shape[0], *dataset.shape[1:])85 collector['label'] = numpy.append(collector.get('label', numpy.empty(0)), label_list)...
pos_coupon.py
Source:pos_coupon.py
1# -*- coding: utf-8 -*-2# Part of BrowseInfo. See LICENSE file for full copyright and licensing details.3from odoo import fields, models, api, _4from odoo.exceptions import Warning5import random6from datetime import date, datetime7class pos_gift_coupon(models.Model):8 _name = 'pos.gift.coupon'9 10 11 def print_report_coupons(self):12 return self.env.ref('pos_orders_all.action_gift_coupons').report_action(self)13 @api.multi14 def existing_coupon(self,code):15 coupon_code_record =self.search([('gift_coupen_code', '=',code)])16 if len(coupon_code_record) == 1:17 coupon_record = coupon_code_record[0]18 return True19 else:20 return False21 22 @api.multi23 def search_coupon(self, code):24 coupon_code_record = self.search([('gift_coupen_code', '=', code)])25 if coupon_code_record:26 return [coupon_code_record.id, coupon_code_record.amount, coupon_code_record.used, coupon_code_record.coupon_count, coupon_code_record.coupon_apply_times, coupon_code_record.expiry_date, coupon_code_record.partner_true,coupon_code_record.partner_id.id]27 @api.model28 def default_get(self, fields):29 pos_config_obj = self.env['pos.coupons.setting']30 if pos_config_obj.search_count([('active', '=',True)]) !=1 :31 raise Warning(_('Please configure gift coupons')) 32 33 rec = super(pos_gift_coupon, self).default_get(fields)34 config_obj = self.env['pos.coupons.setting']35 if config_obj.search_count([('active', '=',True)]) == 1:36 config_record = config_obj.search([('active', '=', True)])[0]37 if config_record:38 rec.update ({39 'amount': config_record.default_value ,40 }) 41 return rec42 @api.one43 @api.constrains('amount')44 def _check_amount(self):45 confing_obj = self.env['pos.coupons.setting']46 if confing_obj.search_count([('active', '=',True)]) == 1:47 config_record = confing_obj.search([('active', '=', True)])[0]48 if self.amount < config_record.min_coupan_value or self.amount > config_record.max_coupan_value:49 raise Warning(_( "Amount is wrong"))50 @api.model51 def create(self, vals):52 pos_config_obj = self.env['pos.coupons.setting']53 if pos_config_obj.search_count([('active', '=',True)]) !=1 :54 raise Warning(_('Please configure gift coupons')) 55 56 else:57 code =(random.randrange(1111111111111,9999999999999))58 if pos_config_obj.search_count([('active', '=',True)]) == 1:59 config_record = pos_config_obj.search([('active', '=', True)])[0]60 if config_record.default_availability != -1:61 if self.search_count([]) == config_record.default_availability:62 raise Warning(_('You can only create %d coupons ') % config_record.default_availability ) 63 config_record = config_record.search([('active', '=', True)])[0]64 if config_record:65 vals.update({'expiry_date':config_record.max_exp_date,66 'gift_coupen_code': str(code),67 68 })69 return super(pos_gift_coupon,self).create(vals) 70 71 72 name = fields.Char('Name')73 gift_coupen_code = fields.Char('Gift Coupon Code')74 user_id = fields.Many2one('res.users' ,'Created By',default = lambda self: self.env.user)75 issue_date = fields.Datetime(default = datetime.now(), )76 expiry_date = fields.Datetime('Expiry date')77 #validity = fields. Integer('Validity(in days)')78 #total_available = fields.Integer('Total Available')79 partner_true = fields.Boolean('Allow for Specific Customer')80 partner_id = fields.Many2one('res.partner')81 order_ids = fields.One2many('pos.order','coupon_id')82 active = fields.Boolean('Active')83 amount = fields.Float('Coupon Amount')84 description = fields.Text('Note')85 used = fields.Boolean('Used') 86 coupon_apply_times = fields.Integer('Coupon Code Apply Limit', default=1)87 coupon_count = fields.Integer('coupon count', default=1)88 89 ...
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!!