How to use __defaults method in pyatom

Best Python code snippet using pyatom_python

recipe-578173.py

Source:recipe-578173.py Github

copy

Full Screen

1"""Provide an easy method to manage program options among multiple versions.2This module contains two classes used to store application settings in such a3way that multiple file versions can possibly coexist with each other. Loading4and saving settings is designed to preserve as much data between versions. An5error is generated on loading if saving would lead to any data being lost."""6__author__ = 'Stephen "Zero" Chappell <Noctis.Skytower@gmail.com>'7__date__ = '4 July 2012'8__version__ = 1, 0, 29################################################################################10import pickle11import pickletools12import zlib13################################################################################14class Namespace:15 "Namespace(**defaults) -> Namespace instance"16 def __init__(self, **defaults):17 "Initializes instance varaibles and checks defaults while loading."18 self.__defaults, self.__changes, self.__master = {}, {}, None19 for key, value in defaults.items():20 if isinstance(value, Namespace):21 if value.__master is not None:22 raise ValueError(repr(key) + ' may not have a master!')23 value.__master = self24 self.__defaults[key] = value25 elif isinstance(value, Parameter):26 self.__defaults[key] = value27 else:28 raise TypeError(repr(key) + ' has unacceptable type!')29 def __setattr__(self, name, value):30 "Sets attributes after validating that they are allowed."31 if name in {'_Namespace__defaults',32 '_Namespace__changes',33 '_Namespace__master'}:34 super().__setattr__(name, value)35 elif '.' in name:36 head, tail = name.split('.', 1)37 self[head][tail] = value38 else:39 if name not in self.__defaults:40 raise AttributeError(name)41 attr = self.__defaults[name]42 if not isinstance(attr, Parameter):43 raise TypeError(name)44 attr.validate(value)45 self.__update_change(name, value, attr)46 def __getattr__(self, name):47 "Gets current value of attributes and unpacks if necessary."48 if '.' in name:49 head, tail = name.split('.', 1)50 return self[head][tail]51 if name not in self.__defaults:52 raise AttributeError(name)53 if name in self.__changes:54 return self.__changes[name].value55 attr = self.__defaults[name]56 if isinstance(attr, Parameter):57 return attr.value58 return attr59 __setitem__ = __setattr__60 __getitem__ = __getattr__61 def save(self, path):62 "Saves complete namespace tree to file given by path."63 if self.__master is None:64 state = self.__get_state()65 data = zlib.compress(pickletools.optimize(pickle.dumps(state)), 9)66 with open(path, 'wb') as file:67 file.write(data)68 else:69 self.__master.save(path)70 def load(self, path):71 "Loads complete namespace tree from file given by path."72 if self.__master is None:73 with open(path, 'rb') as file:74 data = file.read()75 klass, state = pickle.loads(zlib.decompress(data))76 if klass is Namespace:77 self.__set_state(state)78 else:79 self.__master.load(path)80 def __get_state(self):81 "Gets state of instance while takings changes into account."82 state, changes = {}, self.__changes.copy()83 for database in self.__defaults, changes:84 for key, value in database.items():85 if database is not changes:86 value = changes.pop(key, value)87 if isinstance(value, Namespace):88 state[key] = value.__get_state()89 else:90 state[key] = Parameter, value.value91 return Namespace, state92 def __set_state(self, state):93 "Sets state of instance while validating incoming state."94 for key, (klass, value) in state.items():95 if klass is Namespace:96 self.__set_namespace(key, value)97 elif klass is Parameter:98 self.__set_parameter(key, value)99 def __set_namespace(self, key, value):100 "Takes namespace and attempts to update internal state."101 if key in self.__defaults:102 attr = self.__defaults[key]103 if isinstance(attr, Namespace):104 attr.__set_state(value)105 else:106 raise ResourceWarning(repr(key) + ' is not a Namespace!')107 else:108 attr = self.__changes[key] = Namespace()109 attr.__master = self110 attt.__set_state(value)111 def __set_parameter(self, key, value):112 "Takes parameter and attempts to update internal state."113 if key in self.__defaults:114 attr = self.__defaults[key]115 if isinstance(attr, Parameter):116 try:117 attr.validate(value)118 except (TypeError, ValueError):119 raise ResourceWarning(repr(key) + ' value failed tests!')120 else:121 self.__update_change(key, value, attr)122 else:123 raise ResourceWarning(repr(key) + ' is not a Parameter!')124 else:125 self.__changes[key] = Parameter(value)126 def __update_change(self, key, value, attr):127 "Takes key/value pair and updates change database as needed."128 if value != attr.value:129 self.__changes[key] = Parameter(value)130 elif key in self.__changes:131 del self.__changes[key]132################################################################################133class Parameter:134 "Parameter(value, validator=lambda value: True) -> Parameter instance"135 def __init__(self, value, validator=lambda value: True):136 "Initializes instance variables and validates the value."137 self.__value, self.__validator = value, validator138 self.validate(value)139 def validate(self, value):140 "Verifies that the value has the same type and is considered valid."141 if not isinstance(value, type(self.value)):142 raise TypeError('Value has a different type!')143 if not self.__validator(value):144 raise ValueError('Validator failed the value!')145 @property146 def value(self):147 "Returns the value that is associated with this Parameter instance."...

Full Screen

Full Screen

GADialog.py

Source:GADialog.py Github

copy

Full Screen

1import tkinter2from tkinter import *3from gui.GAdialog.GADefaults import CrossingOverMethod4class GADialog:5 def __init__(self, defaults):6 self.__defaults = defaults7 self.window = tkinter.Tk()8 self.window.attributes('-topmost', 'true')9 self.window.title(defaults.windowName)10 self.__sliderTablesCount = self.__getSlider(0, defaults.minTablesCount, defaults.maxTablesCount, defaults.runTablesCount, defaults.sliderNameTablesCount)11 self.__sliderPopulationSize = self.__getSlider(1, defaults.minPopulationSize, defaults.maxPopulationSize, defaults.runPopulationSize, defaults.sliderNamePopulationSize)12 self.__sliderMutation = self.__getSlider(2, defaults.minMutation, defaults.maxMutation, defaults.runMutation, defaults.sliderNameMutation)13 self.__sliderGenerationsNumber = self.__getSlider(3, defaults.minGenerationsNumber, defaults.maxGenerationsNumber, defaults.runGenerationsNumber, defaults.sliderNameGenerationsNumber)14 self.__sliderInfoFold = self.__getSlider(4, defaults.minGenerationsNumber, defaults.maxGenerationsNumber, defaults.runInfoFold, defaults.sliderInfoFold)15 self.__sliderElitism = self.__getSlider(5, defaults.minElitism, defaults.maxElitism, defaults.runElitism, defaults.sliderElitismName)16 self.__radioSelectionMethodValue = IntVar()17 self.__radioSelectionMethodValue.set(self.__defaults.runSelectionMethod)18 self.__getRadioButton(6, defaults.defSelectionMethods, self.__radioSelectionMethodValue, defaults.radioSelectionMethodName)19 self.__radioCrossingOverMethodValue = IntVar()20 self.__radioCrossingOverMethodValue.set(self.__defaults.runCrossingOverMethod)21 self.__getRadioButton(8, defaults.defCrossingOverMethods, self.__radioCrossingOverMethodValue, defaults.radioCrossingOverMethodName)22 self.__radioMutationMethodValue = IntVar()23 self.__radioMutationMethodValue.set(self.__defaults.runMutationMethod)24 self.__getRadioButton(12, defaults.defMutationMethods, self.__radioMutationMethodValue, defaults.radioMutationMethodName)25 self.__buttonDefaults = self.__getButton(15, 0, W, defaults.buttonDefaultsName, self.__setDefaults)26 self.__buttonStart = self.__getButton(15, 1, E, defaults.buttonStartName, self.__getAllValues)27 self.window.mainloop()28 29 def __getSlider(self, rowNum, minVal, maxVal, runVal, labText):30 label = Label(self.window, text = labText)31 label.grid(row = rowNum, column = 0, sticky = S + W, padx = 5, pady = 5)32 slider = Scale(self.window, variable = IntVar(), from_ = minVal, to = maxVal, orient=HORIZONTAL, length = 200)33 slider.grid(row = rowNum, column = 1, sticky = E, padx = 5, pady = 3)34 slider.set(runVal)35 return slider36 def __getButton(self, rowNum, colNum, stickPos, btnText, action):37 button = Button(self.window, text = btnText, command = action)38 button.grid(row = rowNum, column = colNum, stick = stickPos, columnspan = 2, padx=60, pady=5)39 return button40 def __getRadioButton(self, rowNum, methods, variable, labText):41 label = LabelFrame(self.window, text = labText)42 label.grid(row=rowNum, column=0, columnspan=2, padx=5, pady=5, sticky=W)43 rowNum += 144 iteration = 045 for text, mode in methods:46 radio = Radiobutton(label, text = text, variable = variable, value = mode)47 radio.grid(row = rowNum, column = iteration % 2, sticky = W, padx = 5, pady = 3)48 rowNum += iteration % 249 iteration += 150 def __setDefaults(self):51 self.__sliderTablesCount.set(self.__defaults.defTablesCount)52 self.__sliderPopulationSize.set(self.__defaults.defPopulationSize)53 self.__sliderMutation.set(self.__defaults.defMutation)54 self.__sliderGenerationsNumber.set(self.__defaults.defGenerationsNumber)55 self.__sliderInfoFold.set(self.__defaults.defInfoFold)56 self.__sliderElitism.set(self.__defaults.defElitism)57 self.__radioSelectionMethodValue.set(self.__defaults.defSelectionMethod)58 self.__radioCrossingOverMethodValue.set(self.__defaults.defCrossingOverMethod)59 self.__radioMutationMethodValue.set(self.__defaults.defMutationMethod)60 def __getAllValues(self):61 self.__defaults.runTablesCount = self.__sliderTablesCount.get()62 self.__defaults.runPopulationSize = self.__sliderPopulationSize.get()63 self.__defaults.runMutation = self.__sliderMutation.get()64 self.__defaults.runGenerationsNumber = self.__sliderGenerationsNumber.get()65 self.__defaults.runInfoFold = self.__sliderInfoFold.get()66 self.__defaults.runElitism = self.__sliderElitism.get()67 self.__defaults.runSelectionMethod = self.__radioSelectionMethodValue.get()68 self.__defaults.runCrossingOverMethod = self.__radioCrossingOverMethodValue.get()69 self.__defaults.runMutationMethod = self.__radioMutationMethodValue.get()...

Full Screen

Full Screen

settings.py

Source:settings.py Github

copy

Full Screen

1import pathlib2from typing import Dict3from typing import Optional, Union4import numpy as np5import yaml6class MetaSettings(type):7 """Metaclass to inherit class with class properties8 Classes constructed with this metaclass have a :attr:`__defaults`9 class attribute that can be accessed as a property :attr:`defaults`10 from the class.11 """12 __defaults: Dict[str, str] = {}13 @property14 def defaults(cls):15 return cls.__dict__[f"_{cls.__name__}__defaults"]16class Settings(dict, metaclass=MetaSettings):17 """Class to expose and handle configuration18 Inherits from :py:class:`MetaSettings` to allow access to the class19 attribute :py:attr:`__defaults` as a property :py:attr:`defaults`.20 Also derived from basic type :py:class:`dict`.21 The user can sublclass this class :py:class:`Settings` to provide e.g.22 a different set of default values as :py:attr:`__defaults`.23 """24 # Defaults shared by all instances of this class25 # Name-mangling allows different defaults in subclasses26 __defaults = {27 'default_cnn_cutoff': "1",28 'default_cnn_offset': "0",29 'default_radius_cutoff': "1",30 'default_member_cutoff': "2",31 'default_fit_policy': "conservative",32 'default_predict_policy': "conservative",33 'float_precision': 'sp',34 'int_precision': 'sp',35 }36 @property37 def defaults(self):38 """Return class attribute from instance"""39 return type(self).__defaults40 __float_precision_map = {41 'hp': np.float16,42 'sp': np.float32,43 'dp': np.float64,44 }45 __int_precision_map = {46 'qp': np.int8,47 'hp': np.int16,48 'sp': np.int32,49 'dp': np.int64,50 }51 @property52 def int_precision_map(cls):53 return cls.__int_precision_map54 @property55 def float_precision_map(cls):56 return cls.__float_precision_map57 @property58 def cfgfile(self):59 return self._cfgfile60 def __init__(self, *args, **kwargs):61 super().__init__()62 self.update(type(self).__defaults)63 self.update(*args, **kwargs)64 self._cfgfile = None65 def __setitem__(self, key, val):66 if key in type(self).__defaults:67 super().__setitem__(key, val)68 else:69 print(f"Unknown option: {key}")70 def update(self, *args, **kwargs):71 for k, v in dict(*args, **kwargs).items():72 self[k] = v73 def configure(74 self, path: Optional[Union[pathlib.Path, str]] = None,75 reset: bool = False):76 """Configuration file reading77 Reads a yaml configuration file ``.corerc`` from a given path or78 one of the standard locations in the following order of79 priority:80 - current working directory81 - user home directory82 Args:83 path: Path to a configuration file.84 reset: Reset to defaults. If True, `path` is ignored85 and no configuration file is read.86 """87 if reset:88 self.update(type(self).__defaults)89 else:90 if path is None:91 path = []92 else:93 path = [path]94 path.extend([pathlib.Path.cwd() / ".cnnclusteringrc",95 pathlib.Path.home() / ".cnnclusteringrc"])96 places = iter(path)97 # find configuration file98 while True:99 try:100 cfgfile = next(places)101 except StopIteration:102 self._cfgfile = None103 break104 else:105 if cfgfile.is_file():106 with open(cfgfile, 'r') as ymlfile:107 self.update(yaml.load(108 ymlfile, Loader=yaml.SafeLoader109 ))110 self._cfgfile = cfgfile...

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 pyatom 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