Best Python code snippet using slash
fit_parameter.py
Source:fit_parameter.py  
1import numpy2import copy3from orangecontrib.wonder.util import congruence4PARAM_FIX		= 1 << 05PARAM_SYS		= 1 << 16PARAM_REF		= 1 << 27PARAM_HWMIN		= -numpy.finfo('d').max8PARAM_HWMAX		= numpy.finfo('d').max9PARAM_ERR		= numpy.finfo('d').max10class Boundary:11    def __init__(self, min_value = PARAM_HWMIN, max_value = PARAM_HWMAX):12        congruence.checkGreaterOrEqualThan(max_value, min_value, "Max Value", "Min Value")13        self.min_value = min_value14        self.max_value = max_value15class FitParameter:16    def __init__(self,17                 value=None,18                 parameter_name="",19                 boundary=None,20                 fixed=False,21                 function = False,22                 function_value = "",23                 step=PARAM_ERR,24                 error=None,25                 input_parameter = False,26                 output_parameter = False):27        self.parameter_name = parameter_name28        self.value = value29        self.fixed = fixed30        self.function = function31        self.function_value = function_value32        self.error = error33        if self.function:34            if self.function_value is None: raise ValueError("Function Value cannot be None")35            if self.function_value.strip() == "": raise ValueError("Function Value cannot be an empty string")36            self.fixed = False37            self.boundary = None38        if self.fixed:39            self.boundary = Boundary(min_value=self.value, max_value=self.value + 1e-12) # just a trick, to be done in a better way40        else:41            if boundary is None: self.boundary = Boundary()42            else: self.boundary = boundary43        if step is None:44            self.step = PARAM_ERR45        else:46            self.step = step47        self.input_parameter = input_parameter48        self.output_parameter = output_parameter49    def set_value(self, value):50        self.value = value51        self.check_value()52    def rescale(self, scaling_factor = 100):53        if not self.value is None: self.value *= scaling_factor54        if not self.boundary is None:55            if self.boundary.min_value != PARAM_HWMIN: self.boundary.min_value *= scaling_factor56            if self.boundary.max_value != PARAM_HWMAX: self.boundary.max_value *= scaling_factor57    def check_value(self):58        if self.value is None: raise ValueError("Parameter Value cannot be None")59        if self.function:60            if self.function_value is None: raise ValueError("Function Value cannot be None")61            if self.function_value.strip() == "": raise ValueError("Function Value cannot be an empty string")62        else:63            if not self.fixed:64                if self.boundary is None: self.boundary = Boundary()65                if self.boundary.min_value != PARAM_HWMIN:66                    if self.value < self.boundary.min_value:67                        self.value = self.boundary.min_value + (self.boundary.min_value - self.value)/268                if self.boundary.max_value != PARAM_HWMAX:69                    if self.value > self.boundary.max_value:70                        self.value = max(self.boundary.min_value,71                                         self.boundary.max_value - (self.value - self.boundary.max_value)/2)72            else:73                if self.boundary is None: self.boundary = Boundary(min_value=self.value, max_value=self.value + 1e-12)74    def __str__(self):75        if self.function:76            text = self.to_python_code() + " = " + str(self.value)77        else:78            text = self.parameter_name + " " + str(self.value)79            if self.fixed:80                text += ", fixed"81            else:82                if not self.boundary is None:83                    if not self.boundary.min_value == PARAM_HWMIN:84                        text += ", min " + str(self.boundary.min_value)85                    if not self.boundary.max_value == PARAM_HWMAX:86                        text += ", max " + str(self.boundary.max_value)87        if self.is_variable() and not self.error is None:88            text += ", sd = \u00B1 " + str(self.error)89        return text90    def to_parameter_text(self):91        return self.parameter_name + " = " + str(self.value)92    def to_python_code(self):93        if not self.function:94            raise ValueError("Fit parameter " + self.parameter_name + "is not a function")95        return self.parameter_name + " = " + self.function_value96    def duplicate(self):97        return copy.deepcopy(self)98    def is_variable(self):99        return not self.fixed and not self.function100class ParametersList:101    @classmethod102    def get_parameters_prefix(cls):103        return ""104    def duplicate(self):105        return copy.deepcopy(self)106class FreeInputParameters(ParametersList):107    def __init__(self):108        self.parameters_dictionary = {}109    110    def _check_dictionary(self):111        if not hasattr(self, "parameters_dictionary"):112            self.parameters_dictionary = {}113    def get_parameters_names(self):114        self._check_dictionary()115        return self.parameters_dictionary.keys()116    def get_parameters_count(self):117        self._check_dictionary()118        return len(self.parameters_dictionary)119    def set_parameter(self, name, value):120        self._check_dictionary()121        self.parameters_dictionary[name] = value122    def get_parameter(self, name):123        self._check_dictionary()124        return self.parameters_dictionary[name]125    def append(self,parameters_dictionary):126        if not parameters_dictionary is None:127            for name in parameters_dictionary.keys():128                self.set_parameter(name, parameters_dictionary[name])129    def to_text(self):130        text = "FREE INPUT PARAMETERS\n"131        text += "-----------------------------------\n"132        if not self.parameters_dictionary is None:133            for name in self.parameters_dictionary.keys():134                text += name + " = " + str(self.get_parameter(name)) + "\n"135        text += "-----------------------------------\n"136        return text137    def as_parameters(self):138        parameters = []139        if not self.parameters_dictionary is None:140            for name in self.parameters_dictionary.keys():141                fit_parameter = FitParameter(value=self.parameters_dictionary[name],142                                             parameter_name=name,143                                             fixed=True,144                                             input_parameter=True)145                parameters.append(fit_parameter)146        return parameters147    def parse_values(self, text):148        self.parameters_dictionary.clear()149        is_empty = False150        try:151            congruence.checkEmptyString(text, "")152        except:153            is_empty = True154        if not is_empty:155            lines = text.splitlines()156            for i in range(len(lines)):157                is_line_empty = False158                try:159                    congruence.checkEmptyString(lines[i], "")160                except:161                    is_line_empty = True162                if not is_line_empty:163                    data = lines[i].strip().split("=")164                    if len(data) != 2: raise ValueError("Free Output Parameters, malformed line:" + str(i+1))165                    name  = data[0].strip()166                    value = float(data[1].strip())167                    self.set_parameter(name, value)168    def to_python_code(self):169        python_text = ""170        for name in self.parameters_dictionary.keys():171            python_text += name + " = " + str(self.get_parameter(name)) + "\n"172        return python_text173class FreeOutputParameter:174    def __init__(self, expression=None, value=None):175        self.expression = expression176        self.value = value177    178    def duplicate(self):179        return copy.deepcopy(self)180        return FreeOutputParameter(expression=self.expression, value=self.value)181    182class FreeOutputParameters(ParametersList):183    def __init__(self):184        self.parameters_dictionary = {}185    def _check_dictionary(self):186        if not hasattr(self, "parameters_dictionary"):187            self.parameters_dictionary = {}188    def get_parameters_count(self):189        self._check_dictionary()190        return len(self.parameters_dictionary)191    def set_parameter(self, name, parameter=FreeOutputParameter()):192        self._check_dictionary()193        if parameter is None:194            raise ValueError("Parameter object cannot be None")195        self.parameters_dictionary[name] = parameter196    def set_parameter_expression(self, name, expression):197        self._check_dictionary()198        try:199            self.parameters_dictionary[name].expression = expression200        except:201            self.parameters_dictionary[name] = FreeOutputParameter(expression=expression)202    def set_parameter_value(self, name, value):203        self._check_dictionary()204        try:205            self.parameters_dictionary[name].value = value206        except:207            self.parameters_dictionary[name] = FreeOutputParameter(value=value)208    def get_parameter_expression(self, name):209        self._check_dictionary()210        try:211            return self.parameters_dictionary[name].expression212        except:213            raise ValueError("Key " + name + " not found")214    def get_parameter_value(self, name):215        self._check_dictionary()216        try:217            return self.parameters_dictionary[name].value218        except:219            raise ValueError("Key " + name + " not found")220    def get_parameter_formula(self, name):221        self._check_dictionary()222        try:223            return name + " = " + self.parameters_dictionary[name].expression224        except:225            raise ValueError("Key " + name + " not found")226    def get_parameter_full_text(self, name):227        self._check_dictionary()228        try:229            return name + " = " + self.parameters_dictionary[name].expression + " = " + str(self.parameters_dictionary[name].value)230        except:231            raise ValueError("Key " + name + " not found")232    def set_formula(self, formula):233        self._check_dictionary()234        tokens = formula.split("=")235        if len(tokens) != 2: raise ValueError("Formula format not recognized: <name> = <expression>")236        self.set_parameter(name=tokens[0].strip(),237                           parameter=FreeOutputParameter(expression=tokens[1].strip()))238    def append(self, free_output_parameters):239        if not free_output_parameters is None and not free_output_parameters.parameters_dictionary is None:240            for name in free_output_parameters.parameters_dictionary.keys():241                self.set_parameter(name, free_output_parameters.parameters_dictionary[name])242    def parse_formulas(self, text):243        self.parameters_dictionary.clear()244        is_empty = False245        try:246            congruence.checkEmptyString(text, "")247        except:248            is_empty = True249        if not is_empty:250            lines = text.splitlines()251            for i in range(len(lines)):252                is_line_empty = False253                try:254                    congruence.checkEmptyString(lines[i], "")255                except:256                    is_line_empty = True257                if not is_line_empty:258                    data = lines[i].strip().split("=")259                    if len(data) != 2: raise ValueError("Free Output Parameters, malformed line:" + str(i+1))260                    name       = data[0].strip()261                    expression = data[1].strip()262                    self.set_parameter_expression(name, expression)263    def to_python_code(self):264        text = ""265        if not self.parameters_dictionary is None:266            for name in self.parameters_dictionary.keys():267                text += self.get_parameter_formula(name) + "\n"268        return text269    def to_text(self):270        text = "FREE OUTPUT PARAMETERS\n"271        text += "-----------------------------------\n"272        if not self.parameters_dictionary is None:273            for name in self.parameters_dictionary.keys():274                text += self.get_parameter_full_text(name) + "\n"275        text += "-----------------------------------\n"276        return text277    def as_parameters(self):278        if not self.parameters_dictionary is None:279            keys = self.parameters_dictionary.keys()280            parameters = numpy.full(len(keys), None)281            i = 0282            for name in keys:283                parameter = self.parameters_dictionary[name]284                parameters[i] = FitParameter(value=parameter.value,285                                             parameter_name=name,286                                             function=True,287                                             function_value=parameter.expression,288                                             output_parameter=True)289                i += 1290            return parameters291        else:292            return []293    def get_functions_data(self):294        self._check_dictionary()295        parameters_dictionary = {}296        python_code = ""297        for parameter_name in self.parameters_dictionary.keys():298            parameters_dictionary[parameter_name] = numpy.nan299            python_code += self.get_parameter_formula(parameter_name) + "\n"300        return parameters_dictionary, python_code301    def set_functions_values(self, parameters_dictionary):302        for parameter_name in self.parameters_dictionary.keys():...make_config_data.py
Source:make_config_data.py  
...29		else:30			break31	32	return indent_str33def is_line_empty(line):34	return line_base[0] == '#' or len(line_base.strip()) == 035def get_config_key(line):36	return line[:line.find(':')].strip()37def get_config_type(line):38	return line[line.find(":")+1:line.find("=")].strip()39def get_config_key_default(line):40	return line[line.find('=')+1:].strip()41def indent_lines(lines, indent):42	tmp = indent + lines.replace('\n', '\n' + indent)43	# Remove indent from last lines44	tmp = tmp[:tmp.rfind('\n')+1]45	return tmp46for line in config_data_skeleton:47	if line.count("%CONFIG_VARIABLES%"):48		print("Substituting %CONFIG_VARIABLES% with content...")49		indent_str = get_indent(line)50		for line_base in config_data_base:51			# If line is a comment, don't do any logic52			if not is_line_empty(line_base):53				config_key = get_config_key(line_base)54				config_type = get_config_type(line_base)55				line_base = eval(f'f"""{config_data_snippet}"""')56			print(f"|{line_base}", end='')57			config_data.append(indent_lines(line_base, indent_str))58	elif line.count("%CONFIG_VARIABLES_DEFAULTS%"):59		print("Substituting %CONFIG_VARIABLES_DEFAULTS% with content...")60		indent_str = get_indent(line)61		for line_base in config_data_base:62			# If line is a comment, don't do any logic63			if is_line_empty(line_base):64				continue65			else:66				config_key = get_config_key(line_base)67				config_key_default = get_config_key_default(line_base)68				line_base = eval(f'f"""{config_data_defaults_snippet}"""')69			print(f"|{line_base}", end='')70			config_data.append(indent_lines(line_base, indent_str))71	elif line.count("%CONFIG_VARIABLES_SETGET%"):72		print("Substituting %CONFIG_VARIABLES_SETGET% with content...")73		indent_str = get_indent(line)74		for line_base in config_data_base:75			# If line is a comment, don't do any logic76			if is_line_empty(line_base):77				continue78			else:79				config_key = get_config_key(line_base)80				line_base = eval(f'f"""{config_data_setget_snippet}"""')81			print(f"|{line_base}", end='')82			config_data.append(indent_lines(line_base, indent_str))83	elif line.count("%CONFIG_VARIABLES_LOAD%"):84		print("Substituting %CONFIG_VARIABLES_LOAD% with content...")85		indent_str = get_indent(line)86		for line_base in config_data_base:87			# If line is a comment, don't do any logic88			if is_line_empty(line_base):89				continue90			else:91				config_key = get_config_key(line_base)92				config_key_default = get_config_key_default(line_base)93				line_base = eval(f'f"""{config_data_load_snippet}"""')94			print(f"|{line_base}", end='')95			config_data.append(indent_lines(line_base, indent_str))96	elif line.count("%CONFIG_VARIABLES_SAVE%"):97		print("Substituting %CONFIG_VARIABLES_SAVE% with content...")98		indent_str = get_indent(line)99		for line_base in config_data_base:100			# If line is a comment, don't do any logic101			if is_line_empty(line_base):102				continue103			else:104				config_key = get_config_key(line_base)105				line_base = eval(f'f"""{config_data_save_snippet}"""')106			print(f"|{line_base}", end='')107			config_data.append(indent_lines(line_base, indent_str))108	else:109		config_data.append(line)110config_data_file.writelines(config_data)111config_data_file.close()112config_data_base_file.close()...check_empty_lines.py
Source:check_empty_lines.py  
...24    """25    #keep track of the current indentation26    #need only to know if level of indent is zero or not27    line_indent_zero = True28    def is_line_empty(l):29        return len(l.strip(" \t\n\r\f")) == 030    #check all lines except last line31    for i in range(len(file_lines) - 1):32        line = file_lines[i]33        former_line = file_lines[i - 1] if i > 0 else ""34        next_line = file_lines[i + 1] if i < len(file_lines) - 1 else ""35        def is_next_indent_zero():36            """37            Checks the indentation of the next non-empty line38            return True if it is at zero-level indentation39            """40            for j in range(i + 1, len(file_lines)):41                if not is_line_empty(file_lines[j]):42                    return re.match(r'(\s+)(\S+)', file_lines[j]) == None43            return True44        next_indent_zero = is_next_indent_zero()45        #if empty line46        if is_line_empty(line):47            #check if line is not needed48            #if the line before it was empty (two consecutive white space lines)49            if is_line_empty(former_line) and not line_indent_zero and not next_indent_zero:50                log_warning(filename, i + 1, "unneeded empty line (two or more consecutive empty lines)")51            #if the line before it was a block beginning52            elif re.search(r'\{(\s*)$', former_line):53                log_warning(filename, i + 1, "unneeded empty line (block begins with empty line)")54            #if the line after it is a block end55            elif re.match(r'(\s*)\}', next_line):56                log_warning(filename, i + 1, "unneeded empty line (block ends with empty line)")57        else:58            #if non-empty line: check if line is at zero indentation59            #if the line contains one or more white-space characters followed by60            #one or more non white-space characters61            line_indent_zero = re.match(r'(\s+)(\S+)', line) == None62    #if file does not end with an empty line: give warning63    if re.search(r'\n$', file_contents) == None:...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!!
