content
stringlengths
42
6.51k
def _correction(v, N): """protects input to ltqnorm""" # used to protect input to ltqnorm # v is assumed to be a probability between 0 and 1 if 0 < v < 1: return v elif N is None or v < 0 or v >1: raise ValueError('v should be >= 0 and <= 1') # at this point we know v must be 0 ...
def get_corners(cont): """ prep box coordinates for plotting """ out = [cont[0]+1j*cont[1], cont[2]+1j*cont[1], cont[2]+1j*cont[3], cont[0]+1j*cont[3], cont[0]+1j*cont[1]] return out
def bit_list_to_int(bitList): """ In input list LSB first, in result little endian ([0, 1] -> 0b10) """ res = 0 for i, r in enumerate(bitList): res |= (r & 0x1) << i return res
def extract_yaourt_pkgs_to_update(json: dict): """ Extract the list of yaourt's packages from the json passed in parameters. Keyword arguments: json - a dict that represent the json """ return json.get('yaourt')
def payoff_bull_spread(underlying, lower_strike, upper_strike, gearing=1.0): """payoff_bull_spread Buy call option with lower_strike :math:`K_{\mathrm{lower}}` and sell put option with upper_strike :math:`K_{\mathrm{upper}}`. As the name denotes, lower_strike is lower than upper_strike. Payoff formu...
def _parse_mods(mods): """ Parse modules. """ if isinstance(mods, str): mods = [item.strip() for item in mods.split(",") if item.strip()] return mods
def previous_key(tuple_of_tuples, key): """Processes a tuple of 2-element tuples and returns the key which comes before the given key. """ for i, t in enumerate(tuple_of_tuples): if t[0] == key: try: return tuple_of_tuples[i - 1][0] except IndexError: ...
def get_forward_content(paragraph): """ extract the content from paragraph between the head of paragraph or the index of symbols like '.', '!' which appear. """ res = [] for i, c in enumerate(paragraph): if i < 80: res.append(c) continue if c == '.' or c ==...
def generate_command(tup, etup=None): """ args: tup - Coordinate tuple. format: (r1, c1, r2, c2) etup - Erase cell tuple. format: (r, c) """ if (etup is not None): # erase a single cell. return 'ERASE_CELL ' + str(etup[0]) + ' ' + str(et...
def split_envvar(envvar): """Splits str formatted as `key=val` into [key, val] if string is missing an `=val` it will return [key, None] """ return (envvar.split('=', 1) + [None])[:2]
def is_close(a: float, b: float, relative_tolerance: float=1e-09, absolute_tolerance: float=0.0) -> bool: """ Same as ``math.isclose()`` but also works with Python versions before 3.5. """ return abs(a - b) <= max(relative_tolerance * max(abs(a), abs(b)), absolute_tolerance)
def make_space(space_padding=0): """ Return string with x number of spaces. Defaults to 0. """ space = '' for i in range(space_padding): space += ' ' return space
def variable(_printer, ast): """Prints a variable in an expression.""" name_str = ast["name"] return f'{name_str}'
def _extended_euclidean(q, r): """Return a tuple (p, a, b) such that p = aq + br, where p is the greatest common divisor. """ # see [Davenport], Appendix, p. 214 if abs(q) < abs(r): p, a, b = _extended_euclidean(r, q) return p, b, a Q = 1, 0 # noqa: N806 R = 0, 1 # noqa:...
def relu(x): """ Implements a rectified linear (ReLU) activation function. :param x: 2D numpy array equal to (the dot product of the input and hidden layer weights) + hidden layer bias :return: 2D numpy array that is zeroed out where x <= 0 and equal to the original value if x > 0 """ ...
def get_fabric_design(fabric_design_uri, rest_obj): """ Get the fabric design name from the fabric design uri which is returned from GET request :param fabric_design_uri: fabric design uri :param rest_obj: session object :return: dict """ fabric_design = {} if fabric_design_uri: ...
def dedupe_and_sort(sequence, first=None, last=None): """ De-dupe and partially sort a sequence. The `first` argument should contain all the items that might appear in `sequence` and for which the order (relative to each other) is important. The `last` argument is the same, but matching items will...
def _ensure_tuple(value): """Returns a tuple if `value` isn't one already""" if isinstance(value, int): if value == 1: return () else: return (value, ) elif isinstance(value, tuple): if value == (1,): return () return tuple(value) else:...
def format_bool(form_data, key): """ """ if key not in form_data: return None try: res = bool(int(form_data[key])) except: return None return res
def check_unique_possible_value(possible_value_, solution_): """ :param possible_value_: the dict of storing all possible numbers of each cell :param solution_: the list of existing solution For each cell, if there is only one possible number, update solution_ and remove from possible_value_ """ ...
def validate_pairs(password): """ It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps). """ for i in range(len(password) - 2): if password[i:i + 2] in password[i + 2:...
def merge_configs(*configs, differentiators=("type",)): """Merge configuration dictionaries following the given hierarchy Suppose function is called as merge_configs(A, B, C). Then any pair (key, value) in C would overwrite any previous value from A or B. Same apply for B over A. If for some pair (key...
def chunkify(seq, n): """Split seq into n roughly equally sized lists. https://stackoverflow.com/questions/2130016/splitting-a-list-of-arbitrary-size-into-only-roughly-n-equal-parts """ avg = len(seq) / float(n) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):in...
def urlmaker_sec(queryDic): """ Produces the URL, which can be entered into the search (Designed for SEC.gov) Parameters ---------- queryDic : dict searchText (str): Company name to be searched (Default: '*') formType (str): Type of the document to be retrieved (Default: '1') ...
def normalize(text): """Normalizes whitespace in a specified string of text.""" return " ".join(text.strip().split())
def to_list(data): """Convert data to a list. Args: data: Input data, with or without a python container. Returns: list: Replace python container with list or make input a list. """ if not isinstance(data, list): if isinstance(data, (tuple, set)): data = list(data...
def orderdictoffvalues(dict): """ Assuming each key has a value that is a number, split keys from values, put in lists, reorder with that """ keys = list(dict.keys()) values = list(dict.values()) # just in case the list is messeed up if len(keys) != len(values): newdict...
def quote_sql_string(value): """ If "value" is a string type, escapes single quotes in the string and returns the string enclosed in single quotes. Thank you to https://towardsdatascience.com/a-simple-approach-to-templated-sql-queries-in-python-adc4f0dc511 """ if isinstance(value, str): ...
def normalize_timestamp(timestamp): """ Normalize timestamp to seconces since epoch """ if (str(timestamp).find('E12') >= 0 or len(str(int(float(timestamp)))) == 13): timestamp = int(float(timestamp) / 1000.0) else: timestamp = int(float(timestamp)) return timestamp
def nth_fib(n): """Return the nth fibonacci number. Per the kata, f(1) is supposed to be 0 so the fibonacci sequence for this kata was not indexed at 0.""" a, b = 0, 1 for __ in range(n-1): a, b = b, a + b return a
def bottom_lift(f, args): """Calls f on the arguments, returns None if there is an error of any sort. USE WITH CAUTION Arguments: - `f`: a function - `args`: a tuple of arguments """ try: return f(*args) except Exception: return None
def get_minimal_representation(pos, ref, alt): """ ExAC - MIT License (MIT) Copyright (c) 2014, Konrad Karczewski, Daniel MacArthur, Brett Thomas, Ben Weisburd Get the minimal representation of a variant, based on the ref + alt alleles in a VCF This is used to make sure that multiallelic variants i...
def _listify(ids): """convert string to list of unit length""" if isinstance(ids, str): ids = [ids] return ids
def line_intersection(line1, line2): """ Finds the intersection coordinate between two lines Args: line1: `tuple` line 1 to calculate intersection coordinate (X, Y) [pix] line2: `tuple` line 2 to calculate intersection coordinate (X, Y) [pix] Returns: inter_coord: `tuple` intersect...
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificty). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positiv...
def does_classes_contain_private_method(classes, method): """ Check if at least one of provided classes contains a method. If one of the classes contains the method and this method has private access level, return true and class that contains the method. """ for class_ in classes: if ha...
def vanishing_line(n, focal): """ Returns the equation of the vanishing line given a normal """ return (n[0], n[1], n[2] * focal)
def group_from(type): """Get the group part of an event type name. E.g.:: >>> group_from('task-sent') 'task' >>> group_from('custom-my-event') 'custom' """ return type.split('-', 1)[0]
def _merge_strings(a, b, append=False): """ Merge two strings. """ merged = b if append: merged = a + b return merged
def correct_box(box, z): """Get good box limits""" x0, y0, x1, y1 = box new_x0 = max(0, min(x0, x1)) new_x1 = min(2**z - 1, max(x0, x1)) new_y0 = max(0, min(y0, y1)) new_y1 = min(2**z - 1, max(y0, y1)) return (new_x0, new_y0, new_x1, new_y1)
def _frontside_location(frontside_location): """ Location (for csv) """ if frontside_location == True: return 'Yes' else: return 'No'
def block_device_properties_root_device_name(properties): """get root device name from image meta data. If it isn't specified, return None. """ if 'root_device_name' in properties: return properties.get('root_device_name') elif 'mappings' in properties: return next((bdm['device'] fo...
def number_of_routes(max_i, max_j): """Pascal triangle implementation to compute combinations.""" routes = {} for i in range(1, max_i + 1): routes[(i, 0)] = 1 for j in range(1, max_j + 1): routes[(0, j)] = 1 for i in range(1, max_i + 1): for j in range(1, max_j + 1): ...
def xorNA(x): """Return x if x is not None, or return 'NA'.""" return str(x) if x is not None else 'NA'
def _APINameFromCollection(collection): """Get the API name from a collection name like 'api.parents.children'. Args: collection: str, The collection name. Returns: str: The API name. """ return collection.split('.')[0]
def thousands_separator(value): """ Using settings.THOUSANDS_SEPARATOR generic way has two problems: a) it then is not possible to use DATE_FORMAT as we want b) all the numbers have thousand separators not only amounts """ if value is None: return None value = float(value) retur...
def D(u, dfs_data): """The DFS-numbering function.""" return dfs_data['ordering_lookup'][u]
def expand_errors(data): """ Cleans up the error data of forms to enable proper json serialization """ res = {} for k, v in data.items(): tmp = [] for x in v: tmp.append(str(x)) res[k] = tmp return res
def van_der_corput(n_sample, base=2): """Van der Corput sequence. :param int n_sample: number of element of the sequence. :param int base: base of the sequence. :return: sequence of Van der Corput. :rtype: list (n_samples,) """ sequence = [] for i in range(n_sample): n_th_number...
def AppendPatternsToFilter(test_filter, positive_patterns=None, negative_patterns=None): """Returns a test-filter string with additional patterns. Args: test_filter: test filter string positive_patterns: list of positive patterns to add to string negative_patterns: list of ne...
def even_chars(st): """ Finds all the even characters in a string. :param st: string value. :return: a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid str...
def pluralize(word, count): """ Given a word and a count, return the pluralized version of the word. >>> pluralize('cat', 1) 'cat' >>> pluralize('cat', 2) 'cats' """ if count == 1: return word else: return word + "s"
def _make_extension_entry( name, description, url, enabled, core, latest_version, installed_version, status, pkg_type, installed=None, install=None, ): """Create an extension entry that can be sent to the client""" ret = dict( name=name, description=de...
def _is_string_like(obj): """Check whether obj behaves like a string.""" try: obj + '' except (TypeError, ValueError): return False return True
def feet_to_cm(feet, inches): """ Converts feet and inches to centimeters. """ if type(feet) is not int: feet = int(feet.replace("'", "")) if type(inches) is not int: inches = int(inches.replace('"', '')) return feet * 30.48 + inches * 2.54
def critical_pressure(Po, uni_comp_str, k): """ Calculates and returns the critical pressure given Uniaxial Compressive Strength, Pressure (Vertical/Overburden), and k value. """ return (2*Po-uni_comp_str)/(1+k)
def encode_topic_name(topic_names, to_byte=True): """Create topic name. Mainly used for creating a topic name for publisher. # Arguments topic_names: list a list of strings # Returns topic_name: byte string the topic name separated by "/" """ topic_name ...
def bar(x, greeting="hello"): """bar greets its input""" return f"{greeting} {x}"
def sum_digits(s): """Assumes s is a string Returns the sum of the decimal digits in s For example, if s is 'a2b3c' it returns 5""" sum = 0 for c in s: try: sum += int(c) except (TypeError, ValueError): continue return sum
def _reverse_task_map(task_map: dict) -> dict: """ Given a map {oozie_node: [airflow_node1, airflow_node2]} it returns reversed map {airflow_node1: oozie_node, airflow_node2: oozie_node}. :param task_map: oozie to airflow task map :return: reversed task map """ new_map = dict() for oozie...
def parse_repository_tag(repo_path): """Splits image identification into base image path, tag/digest and it's separator. Example: >>> parse_repository_tag('user/repo@sha256:digest') ('user/repo', 'sha256:digest', '@') >>> parse_repository_tag('user/repo:v1') ('user/repo', 'v1', ':') """ ...
def reconstruct_path(came_from, current_node): """Reconstruct the path from the end node back to the beginning using the mapping of previous nodes. """ total_path = [current_node] while current_node in came_from.keys(): current_node = came_from[current_node] total_path.insert(0, ...
def sequence_similarity_fraction(sequence, listofsequences, tolerance, aboveorbelow): """WEV this will count the number of sequences from the list which appear within the test insulating sequence""" totalnumberofsequences = len(listofsequences) numberofhits = 0 for seq in listofsequences: ...
def convert_to_tuples(features): """Convert feature dictionary to (image, label) tuples.""" return features["image"], features["label"]
def dict_merger(dict1, dict2): """ Merge recursively two nested python dictionaries and if key is in both digionaries tries to add the entries in both dicts. (merges two subdicts, adds lists, strings, floats and numbers together!) :param dict1: dict :param dict2: dict :return dict: Merged ...
def _split_name(name): """Splits given state name (model or optimizer state name) into the param_name, optimizer_key, view_num and the fp16_key""" name_split = name.split('_view_') view_num = None if(len(name_split) > 1): view_num = int(name_split[1]) optimizer_key = '' fp16_key = '' ...
def pixel_color(x, y): """ Given an x,y position, return the corresponding color. The Bayer array defines a superpixel as a collection of 4 pixels set in a square grid: R G G B `ds9` and other image viewers define the coordinate axis from the lower left c...
def inside_obstacle(node): """ This function check if the point is inside an obstacle Args: node: location of a node on map Returns: True, if not inside obstacles """ x = node[0] y = node[1] # Rectangle bar half plane conditions if y<=(8/5)*x+28 and y<=(-37/70)*x+(...
def equal_partitions(a,b): """ check whether two partitions represent the same grouping of students""" return set(frozenset(i) for i in a) == set(frozenset(i) for i in b)
def _clean_join(content): """ Joins a list of values together and cleans (removes newlines) :param content: A str or list of str to process :return: The joined/cleaned str """ if not isinstance(content, str): content = ''.join(content) if content else '' return content.replace('\n', ...
def _make_slice_object_a_tuple(slc): """ Fix up a slc object to be tuple of slices. slc = None returns None slc is container and each element is converted into a slice object Parameters ---------- slc : None or sequence of tuples Range of values for slicing data in each axis. ...
def build_update_mask(params): """Creates an update mask list from the given dictionary.""" mask = [] for key, value in params.items(): if isinstance(value, dict): child_mask = build_update_mask(value) for child in child_mask: mask.append('{0}.{1}'.format(key,...
def get_component_status(obj, module, component_name: str): """ get_component_status returns a boolean to indicate if a certain component is enabled or disabled. obj can be either a dict of a MCH CR, or a dict of a MCE CR. If the component_name is not existed in the spec.components list, will return Fal...
def is_tuple(value): """is value a tuple""" return isinstance(value, tuple)
def _remove_none_values(dictionary): """ Remove dictionary keys whose value is None.""" return list(map(dictionary.pop, [i for i in dictionary if dictionary[i] is None]))
def gcd(a, b): """Compute the greatest common divisor (gcd) using the Euclid algorithm""" if a == b: return a if a > b: return gcd(a - b, b) elif b > a: return gcd(a, b - a)
def leading_zero(in_string): """Add a leading zero to a string with only one character. :param in_string: string of min length 1 and max length 2 :return: string with length of 2 and with leading zero where applies """ len_string = len(in_string) if (len_string >...
def SerializeProfiles(profiles): """Returns a serialized string for the given |profiles|. |profiles| should be a list of (field_type, value) string pairs. """ lines = [] for profile in profiles: # Include a fixed string to separate profiles. lines.append("---") for (field_type, value) in profil...
def suffix(num: int) -> str: """ Returns the suffix of an integer """ num = abs(num) # Suffix only depends on last 2 digits tens, units = divmod(num, 10) tens %= 10 # suffix is always 'th' unless the tens digit # is not 1 and the units is either 1, 2 or 3 if tens != 1: ...
def allowed_file(filename): """Returns `True` if file extension is `.tar`""" return '.' in filename and filename.rsplit('.', 1)[1] in ['tar']
def _undefined_pattern(value, fn, undefined): """ If ``fn(value) == True``, return `undefined`, else `value`. """ if fn(value): return undefined return value
def get_body(data): """ Turns snake's body data into a coordinate list :param data: :return: list of all snake body coordinates """ body = [] for coord in data['you']['body']: body.append((coord['x'], coord['y'])) return body
def set_param(input_param): """Converts input param to a dict of param_name: init value""" new_param = {} for k, v in input_param.items(): if type(v) == list: new_param.update({k: v[0]}) # First value is default. else: new_param.update({k: v['init']}) return new...
def maybe_singleton(py_object): """Returns `True` if `py_object` might be a singleton value . Many immutable values in python act like singletons: small ints, some strings, Bools, None, the empty tuple. We can't rely on looking these up by their `id()` to find their name or duplicates. This function chec...
def format_job_matrix_collection_specification(specification): """Formatter function for creating a format for new settings of job matrix :param dict specification: dictionary containging section, name and setting value :return: dictionary containing formatted units information """ output = [] ...
def convert_args_list_to_float(*args_list): """ Converts inputs to floats, returns a list in the same order as the input""" try: args_list = [float(arg) for arg in args_list] except ValueError: raise ValueError("Unable to convert inputs to floats") return args_list
def SOD(fp): """Parse an SOD marker segment. SOD - Start of data segment 0xFF 0x93 Last marker in a tile-part header. Bitstream data between a SOD and the next SOT or EOC shall be a multiple of 8 bits. """ info = {} return info
def character_frequency(filename): """counts the frequency of each character in the given file""" #first try open the file characters={} try: f=open(filename) except FileNotFoundError: # first most detailed exception print("File not found") characters=None except OSError...
def ds2423(rd_val): """Converts the counter.ALL file value of the DS2423 dual counter to an A and a B counter reading. """ a_ct, b_ct = rd_val.split(',') return [ (int(a_ct), 'A'), (int(b_ct), 'B') ]
def true_report(report): """Converts a boolean report into a string for output Only used when the --boolean option is used. Converts the boolean report into a string that is every key in the boolean report that has a True value, joined by linebreaks (\\n) Arguments: report (list): the it...
def combine_periods_and_elements(periods, elements): """ combine information on periods and orbital elements """ missing = set(periods.keys()) - set(elements.keys()) if len(missing) > 0: raise KeyError('missing orbital elements for: {:}'.format(missing)) all_data = dict() for (id_, ...
def celciusToFarenheit(celcius): """ Convert a temperatur in Celcius to Farenheit """ if celcius is None: return None else: return float(celcius) * 1.8 + 32.0
def get_all_tunables(search_space_json): """ Query Autotune API for the application_name, direction, hpo_algo_impl, id_, objective_function, tunables and value_type, and return them. Parameters: search_space_json (json array): A JSON array containing the input search space to hyperparameter optimiz...
def _get_request_uri(environ): """Returns REQUEST_URI from WSGI environ Environ variable REQUEST_URI is not specified in PEP 333 but provided by most servers. This function tries the server generated value and fallbacks to reconstruction from variables specified in PEP 333. """ try: rv...
def euclidean_dist_vec(y1, x1, y2, x2): """ Calculate Euclidean distances between pairs of points. Vectorized function to calculate the Euclidean distance between two points' coordinates or between arrays of points' coordinates. For accurate results, use projected coordinates rather than decimal de...
def get_bits(register, index, length=1): """ Get selected bit(s) from register while masking out the rest. Returns as boolean if length==1 :param register: Register value :type register: int :param index: Start index (from right) :type index: int :param length: Number of bits (default 1...
def createLoghostUndoConfig(IMCDevRunCfg, LOGHOST_DEFAULT_ADRESS): """ creates a syntax list with all non compliant ntp imc_server """ deviceLoghostUndoConfig = list() for idx, loghost in enumerate(IMCDevRunCfg.splitlines()): if "info-center loghost " in loghost and LOGHOST_DEFAULT_ADRESS no...
def _regroup(args, fmt): """Reconstruct the structured arguments based on the flattened version. Parameters ---------- args : NDArray, Symbol, or (nested) list of Symbol or NDArray We allow None inside the args. fmt : (nested) list of ints Stores the format information of the origin...
def to_bool(value): """Take a value and convert it to a boolean type. :param value: string or int signifying a bool :type value: str :returns: converted string to a real bool """ positive = ("yes", "y", "true", "t", "1") if str(value).lower() in positive: return True negative = ...
def reformat_n(n): """ reformat_n(n) Returns reformatted n argument, converting ranges to lists. Required args: - n (str): number or range (e.g., "1-1", "all") Returns: - n (str or list): number or range (e.g., [1, 2, 3], "all") """ if isinst...