How to use attr_val method in localstack

Best Python code snippet using localstack_python

generate_tables.py

Source:generate_tables.py Github

copy

Full Screen

1import os2import click3from tower_cli import get_resource4from tower_cli.cli import types5from collections import OrderedDict6try:7 unicode8except NameError:9 unicode = str10 basestring = str11ATTR_TO_SHOW = [12 'name',13 'type',14 'help_text',15 'read_only',16 'unique',17 'filterable',18 'required',19]20CLI_TYPE_MAPPING = {21 unicode: 'String',22 str: 'String',23 types.Related: (lambda x: 'Resource ' + str(getattr(x, 'resource_name', 'unknown'))),24 click.Choice: (lambda x: 'Choices: ' + ','.join(getattr(x, 'choices', [])))25}26def convert_type(attr_val):27 if attr_val in CLI_TYPE_MAPPING:28 return CLI_TYPE_MAPPING[attr_val] \29 if isinstance(CLI_TYPE_MAPPING[attr_val], str) \30 else CLI_TYPE_MAPPING[attr_val](attr_val)31 elif type(attr_val) in CLI_TYPE_MAPPING:32 return CLI_TYPE_MAPPING[type(attr_val)] \33 if isinstance(CLI_TYPE_MAPPING[type(attr_val)], str) \34 else CLI_TYPE_MAPPING[type(attr_val)](attr_val)35 try:36 return attr_val.__name__37 except Exception:38 return str(attr_val)39def convert_to_str(field, attr, attr_val):40 if attr == 'help_text' and not attr_val:41 return 'The %s field.' % field.name42 elif attr == 'type':43 return convert_type(attr_val)44 elif not isinstance(attr_val, basestring):45 if attr_val in (True, False, None):46 return str(attr_val)47 else:48 return 'TODO'49 return attr_val50def get_content(res_name):51 res = get_resource(res_name)52 content = OrderedDict()53 for field in res.fields:54 for attr in ATTR_TO_SHOW:55 content.setdefault(attr, [])56 attr_val = getattr(field, attr, 'N/A')57 attr_val = convert_to_str(field, attr, attr_val)58 content[attr].append(attr_val)59 return content60def render_table(content):61 delimiter = ['+']62 titles = ['|']63 values = []64 for attr_name in content:65 column_len = max(len(attr_name), max([len(x) for x in content[attr_name]])) + 166 delimiter.append('-' * column_len + '+')67 titles.append(attr_name + ' ' * (column_len - len(attr_name)) + '|')68 for i in range(len(content[attr_name])):69 val = content[attr_name][i]70 if len(values) <= i:71 values.append(['|'])72 values[i].append(val + ' ' * (column_len - len(val)) + '|')73 delimiter = ''.join(delimiter)74 titles = ''.join(titles)75 values = [''.join(x) for x in values]76 table = [delimiter]77 table.append(titles)78 table.append(delimiter.replace('-', '='))79 for val in values:80 table.append(val)81 table.append(delimiter)82 return '\n' + '\n'.join(table) + '\n\n'83def insert_table(rst_path, table):84 insert_checkpnt = '.. <table goes here>\n'85 with open(rst_path) as f:86 file_content = f.read()87 start = file_content.find(insert_checkpnt) + len(insert_checkpnt)88 end = file_content.rfind(insert_checkpnt)89 if start >= 0 and end >= 0:90 with open(rst_path, 'w') as f:91 f.write(file_content[: start] + table + file_content[end:])92def process_resource(res_name, rst_path):93 content = get_content(res_name)94 table = render_table(content)95 insert_table(rst_path, table)96def main():97 for root, dirs, files in os.walk('resources/'):98 for file_ in files:99 if not file_.endswith('.rst'):100 continue101 process_resource(file_[: -len('.rst')], os.path.join(root, file_))102if __name__ == '__main__':...

Full Screen

Full Screen

attr_parse.py

Source:attr_parse.py Github

copy

Full Screen

1import datetime2import safrs3import sqlalchemy456def parse_attr(column, attr_val):7 """8 Parse the supplied `attr_val` so it can be saved in the SQLAlchemy `column`910 :param attr: SQLAlchemy column11 :param attr_val: jsonapi attribute value12 :return: processed value13 """14 if attr_val is None and column.default:15 attr_val = column.default.arg16 return attr_val1718 if attr_val is None:19 return attr_val2021 if getattr(column, "python_type", None):22 """23 It's possible for a column to specify a custom python_type to use for deserialization24 """25 attr_val = column.python_type(attr_val)2627 try:28 column.type.python_type29 except NotImplementedError as exc:30 """31 This happens when a custom type has been implemented, in which case the user/dev should know how to handle it:32 override this method and implement the parsing33 https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError :34 In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.35 => simply return the attr_val for user-defined classes36 """37 safrs.log.debug(exc)38 return attr_val3940 # skip type coercion on JSON columns, since they could be anything41 if type(column.type) is sqlalchemy.sql.sqltypes.JSON:42 return attr_val4344 """45 Parse datetime and date values for some common representations46 If another format is used, the user should create a custom column type or custom serialization47 """48 if attr_val and column.type.python_type == datetime.datetime:49 date_str = str(attr_val)50 try:51 if "." in date_str:52 # str(datetime.datetime.now()) => "%Y-%m-%d %H:%M:%S.%f"53 attr_val = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S.%f")54 else:55 # JS datepicker format56 attr_val = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")57 except (NotImplementedError, ValueError) as exc:58 safrs.log.warning('Invalid datetime.datetime {} for value "{}"'.format(exc, attr_val))59 attr_val = datetime.datetime.now()60 elif attr_val and column.type.python_type == datetime.date:61 try:62 attr_val = datetime.datetime.strptime(str(attr_val), "%Y-%m-%d")63 except (NotImplementedError, ValueError) as exc:64 safrs.log.warning('Invalid datetime.date {} for value "{}"'.format(exc, attr_val))65 attr_val = datetime.datetime.now()66 elif attr_val and column.type.python_type == datetime.time: # pragma: no cover (todo)67 try:68 date_str = str(attr_val)69 if "." in date_str:70 # str(datetime.datetime.now()) => "%H:%M:%S.%f"71 attr_val = datetime.datetime.strptime(str(attr_val), "%H:%M:%S.%f").time()72 else:73 # JS datepicker format74 attr_val = datetime.datetime.strptime(str(attr_val), "%H:%M:%S").time()75 except (NotImplementedError, ValueError, TypeError) as exc:76 safrs.log.warning('Invalid datetime.time {} for value "{}"'.format(exc, attr_val))77 attr_val = column.type.python_type()78 else:79 attr_val = column.type.python_type(attr_val)80 ...

Full Screen

Full Screen

dataset_ffhq.py

Source:dataset_ffhq.py Github

copy

Full Screen

1from io import BytesIO2import lmdb3from PIL import Image4from torch.utils.data import Dataset5import numpy as np6from torchvision import utils, transforms7import torch8import os9class MultiResolutionDataset(Dataset):10 def __init__(self, path, transform, resolution, exp_setting):11 self.env = lmdb.open(12 path,13 max_readers=32,14 readonly=True,15 lock=False,16 readahead=False,17 meminit=False,18 )19 if not self.env:20 raise IOError('Cannot open lmdb dataset', path)21 self.resolution = resolution22 self.transform = transform23 self.distance_dir = './distances'24 self.exp_setting = exp_setting25 id_path = os.path.join(self.distance_dir, f'index_{self.exp_setting}.txt')26 self.id_list = np.loadtxt(id_path)27 self.length = len(self.id_list)28 self.attr_val = {}29 attr_dict = {attr_name: f'{attr_name}_LARGE.txt' for attr_name in ['age', 'pose', 'glasses', 'hairlong', 'haircolor', 'smile', 'gender']}30 for attr in attr_dict.keys():31 self.attr_val[attr] = np.loadtxt(os.path.join(self.distance_dir, attr_dict[attr]))32 def __len__(self):33 return self.length34 def __getitem__(self, index):35 raw_index = index36 index = int(self.id_list[index])37 with self.env.begin(write=False) as txn:38 key = f'{self.resolution}-{str(index).zfill(5)}'.encode('utf-8')39 img_bytes = txn.get(key)40 buffer = BytesIO(img_bytes)41 img = Image.open(buffer)42 img = self.transform(img)43 if self.exp_setting == 'glassessmileage':44 return img, index, self.attr_val['glasses'][index], self.attr_val['age'][index], self.attr_val['smile'][index]45 elif self.exp_setting == 'haircolorhairlonggender':46 return img, index, self.attr_val['haircolor'][index], self.attr_val['hairlong'][index], self.attr_val['gender'][index]47 elif self.exp_setting == 'glassesagepose':...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful