content
stringlengths
42
6.51k
def temp(input_temp): """ Formats input temperature with "+" or "-" sign :param input_temp: :return: formated temperature """ decimal = 0 temp2 = float(input_temp) if temp2 < 0: temp_sign = '' elif temp2 > 0: temp_sign = '+' else: temp_sign = '' de...
def disable_system_recovery_tools(on=0): """Desabilita as Ferramentas de Restauracao do Sistema e Configuracoes DESCRIPTION A restauracao do sistema permite aos usuarios reverter configuracoes do Windows para um ponto anterior (chamados "Pontos de Restauracao"). Esta entrada pode ser u...
def find_previous(element, l): """ find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2 """ length = len(l) for index, cur...
def sanitize_path(raw_path): """ Replace spaces with backslashes+spaces """ return raw_path.replace(" ", "\\ ")
def transform_chw(transform, lst): """Convert each array in lst from CHW to HWC""" return transform([x.transpose((1, 2, 0)) for x in lst]) #return transform(lst.transpose((1, 2, 0)))
def deep_update(source, overrides): """ Update a nested dictionary or similar mapping. Modify ``source`` in place. From Nate Glenn, user2709610, charlax, surjikal https://stackoverflow.com/a/18394648 https://stackoverflow.com/a/30655448 """ for key, value in overrides.items(): ...
def gray_to_binary(gray_value): """Convert a Gray-code value to binary. :param gray_value: Gray-code value :type gray_value: int :returns: Value in regular encoding. :rtype: int """ mask = gray_value >> 1 while mask != 0: gray_value = gray_value ^ mask mask = mask >> 1 ...
def compare_workflows( ancestor_workflows, current_workflows ): """Determine if ancestor_workflows is the same as current_workflows or if ancestor_workflows is a subset of current_workflows.""" if len( ancestor_workflows ) <= len( current_workflows ): for ancestor_workflow_tup in ancestor_workflows: ...
def get_parent(index: int) -> int: """Returns the parent of the heap node For a heap array, this function returns the address of the parent node Parameters ---------- index : int Child node to get the parent of Returns ------- int Address of the parent node, or the nod...
def reorder_sorted_pvalues_list_dict(sorted_pvalues_list_dict): """ Takes in the final list-dictionary with corrected p-values and replaces pvalue "list" value with the original list index value so the list-dictionary can be re-sorted to match the original list order. : Param sorted_pvalues_l...
def line(length: int = 100, char: str = "=") -> str: """ Helper function """ return "".join([char for x in range(length)])
def measure_counts_qobj_nondeterministic(shots, hex_counts=True): """Measure test circuits reference counts.""" targets = [] if hex_counts: # 2-qubit measure |++> targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) # 3...
def lustre_mdt_id(fsname, mdt_index): """ Return the Lustre client ID """ return "%s:%s" % (fsname, mdt_index)
def plasma_parameter(N_particles, N_grid, dx): """ Estimates the plasma parameter as the number of particles per step. Parameters ---------- N_particles : int, float Number of physical particles N_grid : int Number of grid cells dx : float grid step size """ ...
def hadamard_product(m1, m2): """ Return a vector where each entry is the product of the corresponding entries in m1 and m2 """ m = {} for (name, value) in m1.items(): m[name] = value * m2.get(name, 0.0) return m
def delimited_to_camelcase(string, d='_', remove=None): """Convert string from delimiter_separated to CamelCase.""" if d not in string: # no delimiter if string[0].isupper(): return string return string.title() string = string.title() if remove: string = string.repla...
def humanize_seconds(value): """ Returns the given seconds in hours, minutes humanized. """ hours, remainder = divmod(value, 3600) minutes, seconds = divmod(remainder, 60) finalStr = "" # store final sentence tmpStr = "" # store singular/plural of hour/minute hasHours = False # used t...
def calc_alpha(dx, dv, nstars): """ Assuming we have identified 100% of star mass with a 1 M_sun missing mass offset, and that average star mass is 1 M_sun. alpha>1: gravitationally unbound, it is expanding. alpha<1: gravitationally bound, it is collapsing. Calculated alpha is unitless ...
def mean(numbers, precision=2): """return mean of a list, a basic function that is bafflingly absent""" return round(float(sum(numbers)) / max(len(numbers), 1), precision)
def remove_lines(lines, remove=('[[back to top]', '<a class="mk-toclify"')): """Removes existing [back to top] links and <a id> tags.""" if not remove: return lines[:] out = [] for l in lines: if l.startswith(remove): continue out.append(l) return out
def tokens_ngram(doc, ngrams=2): """Extract tokens from doc. This uses a simple regex to break strings into tokens. For a more principled approach, see CountVectorizer or TfidfVectorizer. """ doc = doc.replace('\n', ' ') words_list = [w.lower().strip() for w in doc.split(' ')] words_list = ...
def rounding_precision(expected): """ Helper tool for ensuring all equations tested fairly according to given rounding precision. """ return eval('10E-{}'.format(len(str(expected).split('.')[1]) + 1))
def create_key_index(key_values): """ return list of dict with key/value pairs """ index = {} for key_value in key_values: index[key_value['key']] = key_value return index
def create_bool_select_annotation( keys_list, label, true_label, false_label, description=None): """Creates inputex annotation to display bool type as a select.""" properties = { 'label': label, 'choices': [ {'value': True, 'label': true_label}, {'value': False, 'label': fals...
def class_attributes (cls): """ Return all class attributes (usually class constants) """ return {attr: getattr (cls, attr) for attr in dir (cls) if not callable (attr) and not attr.startswith ("__")}
def parse_bin(n: bytes) -> int: """convert a C string representing binary to an unsigned integer""" # this is written in a highly imperative style # to make it easy to translate to MIPS p = 0 i = 0 while True: c = n[i] if c == ord('1'): p |= 1 elif c == ord('0'): pass # |= 0 elif c == 0: # null ...
def encode(in_bytearray): """ Encodes a bytearray into COBS. Does not include the start-of-frame or end-of-frame bytes. """ out = bytearray() if len(in_bytearray) == 0: return b'\x01' while len(in_bytearray) > 0: next_zero = in_bytearray.find(b'\x00') if next_zero < 0: chunk_length = l...
def _default_row_base(row_def, row): """ Returns default row definition updated with the contents of `row`. Parameters ---------- row_def: dict Definition for the row row: dict Dictionary describing the row Returns ------- dict default dictionary updated...
def get_env_from_directory(directory_name): """Determine environment name from directory name.""" if directory_name.startswith('ENV-'): return directory_name[4:] return directory_name
def is_url_valid(url: str): """ URL validator inspired by Django's URL validator. :param url: URL to validate :return: True if the URL is in good format, False if it is not """ from re import compile, IGNORECASE, match regex = compile( r'^(?:http)s?://' # http:// or https:// ...
def init(i): """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ return {'return':0}
def select_valid_choices(choices, choice_set): """Select valid choices. Examples -------- >>> select_valid_choices(list("abcde"), (1, 0, 1, 0, 1)) ['a', 'c', 'e'] >>> select_valid_choices(list("abc"), (0, 1, 0, 1, 0)) ['b'] """ return [x for i, x in enumerate(choices) if choice_set...
def _extract_email(data): """ {'elements': [{'handle': 'urn:li:emailAddress:319371470', 'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]} """ ret = '' elements = data.get('elements', []) if len(elements) > 0: ret = elements[0].get('handle~', {}).get('emailAddres...
def find_site_in_cameras(site_no, cameras): """ Helper method that scans a list of cameras for a site ID Returns the site dictionary or an empty dictionary if none is found. """ for site_camera in cameras: if site_no in site_camera['SiteId']: return site_camera return {}
def evalMultiRefToken(mref, ixname, val): """Helper function for evaluating multi-reference tokens for given index values.""" return eval(mref.replace(ixname, str(val)), {}, {})
def getRecipients(test_data): """ Returns, as a string, the email addresses of the student's parents for the given test """ recipients = [] if test_data["MotherEmail"] != "": recipients.append(test_data["MotherEmail"]) if test_data["FatherEmail"] != "": recipie...
def methods_of(obj): """Get all callable methods of an object that don't start with underscore. Returns a list of tuples of the form (method_name, method). """ result = [] for i in dir(obj): if callable(getattr(obj, i)) and not i.startswith('_'): result.append((i, getattr(obj, i...
def lowercase_text(text): """Lowercase a string. Args: text (str): String to lowercase. Return: Lowercased text. """ return text.lower()
def envValToBool(rawVal): """ Return env val as native bool value. Returns False if not recognized. """ result = False if rawVal: try: # value from os.environ is a string but it may be a digit result = bool(int(rawVal)) except ValueError: resu...
def _check_rain(rain): """Checks if it is raining in searched city.""" if "rain" not in rain: return "" return rain
def check_bracket_sequence(bracket_sequence: str) ->bool: """ Checks bracket sequence is correct or not. :param bracket_sequence: string sequence of brackets :return: True if sequence is correct, e.g. each open bracket has its closed variant, else False """ opening_brackets = ['(', '[', '{'] ...
def get_kleast(lst: list, k: int) -> list: """ get k least numbers from the given list. Parameters ----------- lst: the given list k: the num of least numbers Returns --------- out: the k least number list Notes ------ the container could be list, dict or tree (max he...
def make_iterables(values): """ Create a list of iterables (``list`` and ``tuple``) containing each of the values passed as a parameter. It was designed to be used when defining types in the configuration schema. For example make_iterables([str, ContextVale]) will return [[str], (str,), [ContextVal...
def flatten (*objs): """ Return: a single-level list of all atoms in `*objs' in original order. Any object type other than a sequence, dictionary or Indexable type is considered atomic by this function. SeeAlso: `sys.setrecursionlimit' to increase recursion limit if need be. """ ## Test cas...
def condition(condition_attributes, reference): """ Evaluates a condition. """ conditions = [] if 'variable' in condition_attributes: variables = condition_attributes['variable'].split(" ") for variable in variables: conditions.append(variable in reference) if 'type...
def promote_maximally(x): """Return copy of x with high precision dtype. Converts input of 'f2', 'f4', or 'f8' to 'f8'. Please don't pass f16. f16 is misleading and naughty. Converts input of 'u1', 'u2', 'u4', 'u8' to 'u8'. Converts input of 'i1', 'i2', 'i4', 'i8' to 'i8'. Naturally, this c...
def site(coord, size, xperiodic): """ numbering the square lattice sites Parameters -------------- site : (x, y) (x, y) coordinate of the site size : (int, int) -> (nx, ny) linear size of the square lattice xperiodic : boolean indicates PBC along x """ nx, ny...
def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
def parse_float(float_string): """Try to parse the string into a float. :param float_string: :return: """ try: return float(float_string) except ValueError: return None
def merge_optional_trees(tree, big_tree): """Merge two MacroConditionTrees when one or both objects may be `None`.""" if tree is not None: if big_tree is None: return tree else: return big_tree.merge(tree) else: return big_tree
def add_numbers(x, y): """Add numbers together""" if type(x) != int or type(y) != int: return None return x + y
def from_mongo(data): """ Translates the MongoDB dictionary format into the format that's expected by the application. """ if not data: return None data['id'] = str(data['_id']) return data
def __isLeft(p0,p1,p2): """Returns a float indicating if p2 is left or right of line from p0 and p1 p0,p1,p2: tuples representing point coordinates return: float > 0 if p2 is left < 0 if p2 is right = 0 if p2 is on line""" p0x = p0[0] p0y = p0[1] ...
def caseInsensitiveDictLookup(key, dictionary): """ Do a case insensitive dictionary lookup. Return the dictionary value if found, or None if not found. """ for entry in dictionary: ...
def _extract_deps(bazel_rule): """Gets list of deps from from a bazel rule""" return list(sorted(bazel_rule['deps']))
def is_palindrome(string: str) -> bool: """Return whether string is a palindrome or not.""" if "".join(reversed(string)).lower() == string.lower(): return True return False
def flatten_a_record (rec, prefix='', sep='.'): """ Flatten the given record (dictionary) into a list of key/value tuples and return the tuple list. Arguments: rec: the dictionary to be flattened. prefix: the prefix key "path" at this level of flattening. If provided, must already include th...
def parse_limit(val): """Convert a textual representation of a number of bytes into an integer NOTE: If val is None then None is returned Args: val (str): number of bytes Format: <num><unit> where <num> - is a float <unit> is...
def J_int_yt(yt, membrane_geometry): """ Jacobian using yt = 1. - rt coordination Note that the coordination definition for y is not consist between [1] and [2]. """ J = 1. - yt if (membrane_geometry=='FMM' or membrane_geometry=='FMS'): J = 1. return J
def _from_rgb(rgb): """translates an rgb tuple of int to a tkinter friendly color code """ return "#%02x%02x%02x" % rgb
def GetFullPathForJavaFrame(function): """Uses java function package name to normalize and generate full file path. Args: function: Java function, for example, 'org.chromium.CrAct.onDestroy'. Returns: A string of normalized full path, for example, org/chromium/CrAct.java """ return '%s.java' % '/'.j...
def count_examples(taxonomy): """ Get taxonomy, count examples in every node and return sum. :param taxonomy: taxonomy :return: sum of examples """ count = 0 keys = [x for x in list(taxonomy.keys()) if x != "data"] for i in keys: if set(taxonomy[i]) == set(list({"data"})): ...
def is_abbreviation(nm: str): """ Determine if something is an abbreviation. Otherwise if text ends with "." we'll conclude so. Examples: Ala. YES Ala NO S. Bob NO -- abbreviated, yes, but this is more like a contraction. S. B. YES :param nm: textual...
def _join(lst, key, sep=";"): """Auxiliary function to join same elements of a list of dictionaries if the elements are not None. """ return sep.join([d[key] for d in lst if d[key]])
def _zip_layer_sequence(layers, tensors, **kwargs): """Applies a sequence of layers to a sequence of tensors of the same size.""" return [layer(tensor, **kwargs) for layer, tensor in zip(layers, tensors)]
def _neighbor_keys_from_bond_keys(key, bnd_keys): """ Determine neighbor keys of an atom from the bond keys """ nkeys = [] for bnd_key in bnd_keys: if key in bnd_key: nkey, = bnd_key - {key} nkeys.append(nkey) return frozenset(nkeys)
def median(a): """Calculates and returns the median of a list of numbers. a - list to calculate median of""" b = sorted(a) n = len(b) if n % 2 == 0: return (b[n//2-1] + b[n//2]) / 2 return b[n//2]
def format_class_dict(d): """ removes the __ artifact from class to dict conversion """ out = {} for k, v in d.items(): if isinstance(v, dict): v = format_class_dict(v) out_key = k.split('__', 1)[-1] out[k.replace(k, out_key)] = v return out
def dice_coefficient(a, b, case_insens=True): """ :type a: str :type b: str :type case_insens: bool dice coefficient 2nt/na + nb. https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Dice%27s_coefficient#Python >>> dice_coefficient('hallo', 'holla') 0.25 >>> dice_coefficien...
def StringToAdjListDict(AdjListString): """Convert AdjListString to it's dict representation""" assert isinstance(AdjListString, str) AdjListDict = eval(AdjListString, {'__builtins__':{}}) assert isinstance(AdjListDict, dict) return AdjListDict
def to_numpy(tensors): """Converts tf.Tensors to numpy array. Parameters ---------- tensors : tf.Tensor | dict | list Returns ------- arrays : np.array | dict | list """ if type(tensors) == list: return [to_numpy(t) for t in tensors] if type(tensors) == dict: r...
def extract_power(term): """ Returns the degree of a single term in a polynomial. Symengine stores these as (coefficient, (delta, exponent)). This is helpful for sorting polynomials which are not sorted by default. """ if not "args" in dir(term): return 0 if term.args == (): ...
def get_matches(match_id="GET",game_id="GET"): """Retrieve a match or all matches. Return match details and status.""" # If no match_id or game_id then return info for all matches # If match_id then return info for that match # If game_id then return info for the match that game is part of result = ...
def sgn(el): """The standard sgn function. :param el: float input :return: sign of the number """ if el < 0: return -1 elif el == 0: return 0 else: return 1
def _EdgeColor(data): """Helper callback to set default edge colors.""" flow = data.get("flow") if flow == "control" or flow == "backward_control": return "blue" elif flow == "data" or flow == "backward_data": return "red" elif flow == "call" or flow == "backward_call": return "green" else: ...
def checksum(number): """Calculate the checksum. A valid number should have a checksum of 1.""" check = 5 for n in number: check = (((check or 10) * 2) % 11 + int(n)) % 10 return check
def kib_to_gib(size: float) -> float: """Convert disk space unit from KiB to GiB.""" return round(size / 2 ** 20, 2)
def assert_number_of_revolutions_not_negative(M): """ Checks if the number of revolutions is zero or positive, that is, it does not have a negative value. Parameters ---------- M: int Number of revolutions """ if M < 0: raise ValueError("Number of revolutions must be e...
def preprocess_text8(data): """ Text8 dataset contains a lot of single-letter words. We have to remove those letters before working with the dataset """ words = [w for w in data.split(" ") if len(w) > 1] words.append('a') words.append('i') return ' '.join(words)
def Pn(n): """ Pentagonal numbers.""" return n * (3 * n - 1) // 2
def scrape_indices(filenames): """ Function to get patient IDs from .h5 files listed as 'Reference_idx_ID_Time_block_1.h5' :param filenames: [list[string]] filenames of .h5 files :returns: [list[string]] corresponding patient IDs """ ids = [] for fname in filenames: start = fname.find('Reference_idx_') + len('...
def solution(n, array): """ Returns n counters after the increment and max operations coded in array """ counters = [0] * n # Current greatest value calculated so far max_count = 0 for i in range(len(array)): if array[i] == n + 1: # max_count = max(counters) counters = [max_count] * n...
def parse_filesize(filesize): """ Parse a human readable filesize string into a integer. Only the suffixes 'k' and 'M' are supported. """ try: if filesize.endswith('k'): return int(filesize[:-1]) * 1024 if filesize.endswith('M'): return int(filesize[:-1]) * 1048576 ...
def iso_string_to_sql_date_sqlite(x: str) -> str: """ Provides SQLite SQL to convert a column to a ``DATE``, just by taking the date fields (without any timezone conversion). The argument ``x`` is the SQL expression to be converted (such as a column name). """ return f"DATE(SUBSTR({x}, 1, 10))"
def biggerIsGreater(w): """ Your code goes here. """ # We note that if there is only one unique letter, it will fail anyway if len(set(w)) == 1: return "no answer" # We reverse the string backwards = "".join(list(reversed(w))) # The indices to cut the string # They are row...
def fast_mean_variance_update(new_sample, old_mean, old_variance, k): """ Return the new mean and variance if one new sample is added. """ new_mean = (k * old_mean + new_sample)/(k+1) new_variance = (k-1) * old_variance / k + (new_sample - old_mean)**2/(k+1) return new_mean, new_variance
def split_elem_def(path): """Get the element name and attribute selectors from an XPath path.""" path_parts = path.rpartition('/') elem_spec_parts = path_parts[2].rsplit('[') # chop off the other ']' before we return return (elem_spec_parts[0], [part[:-1] for part in elem_spec_parts[1:]])
def process_line(data): """ Processor to parse each individual config file line :param data: the line read from the file :returns: None if it is a line we don't wish to handle, otherwise : : a list containing each individual token. """ command_list = [] temp = data.strip() if len(temp) == 0: return Non...
def median(s): """Returns the median of the _already__sorted list s""" size = len(s) index = size // 2 return s[index] if size % 2 else (s[index] + s[index - 1]) / 2
def printable_value_record(value_record): """Prints a GPOS ValueRecord.""" if value_record is None: return "<NULL>" if vars(value_record).keys() == ["XAdvance"]: return "%d" % value_record.XAdvance output_list = [] for key in ["XPlacement", "YPlacement", "XAdvance", "YAdvance"]: ...
def boundaries(x, x_change, x_max, x_img_size, padding = 0): """ Arguments: x - int, current positon of rocket x_change - int, differnce in pixels x_img_size - int, size of image in pixels padding - int, optional, additional padding Re...
def get_state(module, key, default=None): """Gets key from `module`'s state hooks.""" return getattr(module, '_state_hooks', {}).get(key, default)
def vadd(v, w): """Add two vectors.""" try: return tuple(i + j for i, j in zip(v, w)) except TypeError: return v + w
def get_new_version(version, current_version): """ Bump the version """ if version in ('micro', 'minor', 'major'): version_parts = current_version.split('.') version_parts = [int(part) for part in version_parts] if version == 'micro': version_parts[2] += 1 elif versio...
def get_spec(nodeid: str) -> str: """Get callspec from item nodeid.""" tokens = nodeid.split("[", 1) return "[" + tokens[1].strip() if len(tokens) > 1 else ""
def nestedSplit(astring, sep=None, *subsep): """nestedSplit(astring, sep=None, *subsep): given astring, and one or more split strings, it splits astring hierarchically. The first split key is the higher level one. Ex.: nestedSplit("a b\nc d", "\n", " ") => [['a', 'b'], ['c', 'd']] """ if subsep: ...
def SplitNodePath(nodePath): """Splits a Wiretap Browser node path into a Wiretap server name and node ID. @details A "node path" combines a Wiretap server name and a node ID, yielding a single string. When splitting a node path, this function assumes that the text before the...
def ft2m(feet: float) -> float: """ Convert feet to meters. :param float feet: feet :return: elevation in meters :rtype: float """ if not isinstance(feet, (float, int)): return 0 return feet / 3.28084
def slova_k(list): """ funkce hleda v seznamu zvirata zacinajici na "k" """ vysledek = [] for slovo in list: if slovo[0].lower() == "k": vysledek.append(slovo) return vysledek
def crc8(byteData): """ Generate 8 bit CRC of supplied string """ CRC = 0 # for j in range(0, len(str),2): for b in byteData: # char = int(str[j:j+2], 16) # print(b) CRC = CRC + b CRC &= 0xFF return CRC