content
stringlengths
42
6.51k
def inherit_docstrings(cls): """Inherit docstrings from parent class""" from inspect import getmembers, isfunction for name, func in getmembers(cls, isfunction): if func.__doc__: continue for parent in cls.__mro__[1:]: if hasattr(parent, name): func.__doc__ = geta...
def tokenize(s): """ Converts a string to list of tokens. """ return s.replace('(', ' ( ').replace(')', ' ) ').split()
def sanitize_command_options(options): """ Sanitizes command options. """ multiples = [ 'badges', 'exclude_badges', ] for option in multiples: if options.get(option): value = options[option] if value: options[option] = [v for v in ...
def checkBuildingType(line): """Checks if the building type is a house, or if the item is being bought or sold""" if " is buying " in line: return "buy" elif " is selling " in line: return "sell" else: return "house"
def convertToBase10(numList, base): """ Parses numList and returns the total base 10 value in the list. """ negative = False # If numList contains a negative, then remove it... # and indicate it is negative so the algorithm can continue. if numList[0] == '-': numList.remove('-') negative = True numList ...
def get_tree_leaf(element, branch): """ Return the nested leaf element corresponding to all dictionnary keys in branch from element """ if isinstance(element, dict) and len(branch) > 0: return get_tree_leaf(element[branch[0]], branch[1:]) else: return element
def nifty_power_of_ten(num): """Return 10^n: 10^n > num; 10^(n-1) <= num.""" result = 10 while result <= num: result *= 10 return result
def get_proxy_column_names(protected_columns, noise_param, noise_index=''): """Gets proxy column names.""" return [ 'PROXY' + noise_index + '_' + '%0.2f_' % noise_param + column_name for column_name in protected_columns ]
def _wrap_metric(metric_name: str) -> str: """Put a newline on "::" for metric names. Args: metric_name: metric name. Returns: wrapped metric name. """ if "::" in metric_name: return "<br>".join(metric_name.split("::")) else: return metric_name
def getattr_call(obj, attr_name, *args, **vargs): """ Call the getter for the attribute `attr_name` of `obj`. If the attribute is a property, pass ``*args`` and ``**kwargs`` to the getter (`fget`); otherwise, ignore them. """ try: return getattr(type(obj),attr_name).fget(obj,*args,**vargs) ...
def readFile(fileName): """Read all file lines to a list and rstrips the ending""" try: with open(fileName) as fd: content = fd.readlines() content = [x.rstrip() for x in content] return content except IOError: # File does not exist return []
def create_table_sql(flds2keep, table): """ Arguments: - `flds`: - `table`: """ fld_names = ["[{}]".format(x) for x in flds2keep] fld_list = ", ".join(fld_names) sql = "create table tmp as select {} from [{}];".format(fld_list, table) return sql
def reduce_multiline(string): """ reduces a multiline string to a single line of text. args: string: the text to reduce """ string = str(string) return " ".join([item.strip() for item in string.split("\n") if item.strip()])
def _check_if_contr_in_dict(consecutive, sent, contractions): """ Args: - consecutive = a list of consecutive indices at which sent contains contractions. - sent = a (word, pos_tag) list, whereby the words make up a sentence. - contractions = the contractions dict...
def artf_in_scan(scan, width, img_x_min, img_x_max, verbose=False): """return precise artefact angle and distance for lidar & camera combination""" if scan is None: return 0, 0 # the scan is already in mm, so angle is modified to int deg*100, ready to send x_min, x_max = img_x_min, img_x_max ...
def number_to_base(n, base): """Function to convert any base-10 integer to base-N.""" if base < 2: raise ValueError('Base cannot be less than 2.') if n < 0: sign = -1 n *= sign elif n == 0: return [0] else: sign = 1 digits = [] while n: digits....
def count_paths_recursive(graph, node_val, target): """A more conventional recursive function (not a recursive generator)""" if node_val >= target: return 1 total = 0 for next_node in graph[node_val]: total += count_paths_recursive(graph, next_node, target) return total
def compare_server_id(x,y): """Comparison function for use with builtin 'sorted'. Sorts the server serverId in numeric order.""" ccard_x = int(x['serverId'].split('/')[0]) ccard_y = int(y['serverId'].split('/')[0]) return ccard_x - ccard_y
def fail_message(user, msg, groups): """ The message to be displayed to the user when they fail the LDAP validation Override this method if you want your own custom message Args: user (str): The user ID that was used for the LDAP search msg (errbot.backends.base.Message): The message f...
def _extract_git_revision(prerelease): """Extracts the git revision from the prerelease identifier. This is assumed to be the last `.` separated component. """ return prerelease.split(".")[-1]
def human_check(string): """ The API is actually terribly unreliable at providing information on whether an entity is human or corporate. What is consistent is that companies are provided in UPPER CASE and humans provided in the format "SURNAME, Othernames". This takes advantage of this to iden...
def get_source_name(module_type, name, prefix_override, suffix, alternative_suffix): """Generate source file name by type.""" if (module_type == 'lib' or module_type == 'lib64') and not prefix_override: if not name.startswith('lib'): name = 'lib' + name al...
def GetSyslogConfMultiHomedHeaderString(WorkspaceID): """ Return the header for the multi-homed section from an rsyslog conf file """ return '# OMS Syslog collection for workspace ' + WorkspaceID
def row(row_no) -> slice: """Returns slice object for appropriate row. Note: Can this be memoised? Would it help in any way? """ start = 0 + row_no * 9 stop = 9 + row_no * 9 return slice(start, stop)
def add_commas(number): """1234567890 ---> 1,234,567,890""" return "{:,}".format(number)
def sanitize_branch_name(branch_name: str) -> str: """ replace potentially problematic characters in provided string, a branch name e.g. copr says: Name must contain only letters, digits, underscores, dashes and dots. """ # https://stackoverflow.com/questions/3411771/best-way-to-replace-mul...
def key_for_issues(issue): """Generate a string search key for a Jira issues.""" return u' '.join([ issue['key'], issue['summary']])
def list_diff(list_a, list_b): """ Return the items from list_b that differ from list_a """ result = [] for item in list_b: if item not in list_a: result.append(item) return result
def selection_sort(nums_array: list) -> list: """ Selection Sort Algorithm :param nums_array: list :return nums_array: list """ for i in range(len(nums_array)): min_index = i for j in range(i + 1, len(nums_array)): if nums_array[j] < nums_array[min_index]: ...
def merge_dict(data, *override): """ Merges any number of dictionaries together, and returns a single dictionary Usage:: >>> util.merge_dict({"foo": "bar"}, {1: 2}, {"Tx": "erpa"}) {1: 2, 'foo': 'bar', 'Tx': 'erpa'} """ result = {} for current_dict in (data,) + override: ...
def is_prime(x): """Given a number x, returns True if it is prime; otherwise returns False""" num_factors = 0 if type(x) != int: return False for n in range(2,x+1): if x%n == 0: num_factors +=1 if num_factors == 1: return True return False
def fuel_requirement(module_mass): """ Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. :param module_mass: :return: fuel_requirement """ return module_mass // 3 - 2
def cumulative_sum(array): """Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].""" res = [] val = 0 for elem in ...
def grow(string, start, end): """ starts with a 0 or 1 length palindrome and try to grow bigger """ while (start > 0 and end < len(string) and string[start - 1].upper() == string[end].upper()): start -= 1; end += 1 return (start, end)
def xyzs2xyzfile(xyzs, filename=None, basename=None, title_line=''): """ For a list of xyzs in the form e.g [[C, 0.0, 0.0, 0.0], ...] convert create a standard .xyz file :param xyzs: List of xyzs :param filename: Name of the generated xyz file :param basename: Name of the generated xyz file without...
def countName(dictname): """Return the underlying key used for access to the number of items in the dictlist named dictname. """ return (dictname,"N")
def IsInRangeInclusive(a, low, high): """ Return True if 'a' in 'low' <= a >= 'high' """ return (a >= low and a <= high)
def combinatrix(combos): """ pass """ dias_visualizacion= [ #Lunes,Martes,mierc,jueves,viernes,sabado 1 ,2 ,3 ,4 ,5 ,6, #8-9 7 ,8 ,9 ,10 ,11 ,12, 13 ,14 ,15 ,16 ,17 ,18, 19 ,20 ,21 ,22 ,23 ,24,#11...
def __color(mode, string, color): """ mode escape sequence code for background or foreground color string string to be formatted color used color """ if isinstance(color, int): escape = "\x1b[{0}8:5:{1}m".format(mode, color) elif isinstance(color, tuple): r, g, b = color ...
def _func_worker_ranks(workers): """ Builds a dictionary of { (worker_address, worker_port) : worker_rank } """ return dict(list(zip(workers, range(len(workers)))))
def mapToRightLanguageCode(languageField, languageIsoCodesDictionary): """ map the language codes to the right ISO 639 3 letter codes. """ if languageField in languageIsoCodesDictionary: langIso = languageIsoCodesDictionary[languageField] else: langIso = languageField l...
def sizeof(num, suffix='B'): """ Utility method to convert a file size in bytes to a human-readable format Args: num (int): Number of bytes suffix (str): Suffix for 'bytes' Returns: str: The formatted file size as a string, eg. ``1.21 GB`` """ for unit in ['', 'K', 'M', ...
def tuple_get(string, count=None): """ Parse a tuple string like "(1024;768)" and return strings of the elements """ if not string: return None string = string.strip() assert string.startswith("(") and string.endswith(")") string = string[1:-1] res = [x.strip() for x in string.sp...
def _are_scopes_sufficient(authorized_scopes, sufficient_scopes): """Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from...
def subplot_shape(size): """ Get the most square shape for the plot axes values. If only one factor, increase size and allow for empty slots. """ facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0] # re-calc for prime numbers larger than 3 to get better shape while ...
def permissions_string(permissions, known_permissions): """Return a comma separated string of permission changes. :param permissions: A list of strings, or ``None``. These strings can exclusively contain ``+`` or ``-`` prefixes, or contain no prefixes at all. When prefixed, the resulting string w...
def func_ab(a=2, b=3): """func. Parameters ---------- a, b: int, optional Returns ------- None, None a, b: int None, None, None, None """ return None, None, a, b, None, None, None, None
def IsImageVersionStringComposerV1(image_version): """Checks if string composer-X.Y.Z-airflow-A.B.C is Composer v1 version.""" return (not image_version or image_version.startswith('composer-1.') or image_version.startswith('composer-latest'))
def update_position(xc, yc, vxc, vyc, tstep): """Returns the new position after a time step""" xc = xc+vxc*tstep yc = yc+vyc*tstep return xc, yc
def binary_search(array, query, key=lambda a: a, start=0, end=-1): """Python's 'in' keyword performs a linear search on arrays. Given the circumstances of storing sorted arrays, it's better for Nyx to use a binary search. Arguments: key - filter for objects in the array start - 0-indexed st...
def convert_params_to_string(params: dict) -> str: """ Create a string representation of parameters in PBC format """ return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()])
def device_id(obj): """Get the device ID Parameters ---------- obj : dict A grow or data "object" Returns ------- id : str Device id """ return obj['device_id']
def pick(seq, func, maxobj=None): """Picks the object obj where func(obj) has the highest value.""" maxscore = None for obj in seq: score = func(obj) if maxscore is None or maxscore < score: (maxscore, maxobj) = (score, obj) return maxobj
def ensure_prefix(string, prefix): """Ensure, that a string is prefixed by another string.""" if string[:len(prefix)] == prefix: return string return prefix + string
def points_to_list(points): """Make array of dictionaries as a list. Args: points: array of dictionaries - [{'x': x_coord, 'y': y_coord}]. Returns: list: points as a list. """ points_list = [] for point in points: points_list.append([int(point['x']), int(point['y'])]) ...
def fpow0(x, n): """ Perform recursive fast exponentiation by squaring. :param x: the base number :param n: the target power value, an integer :return: x to the power of n """ if n < 0: return fpow0(1 / x, -n) if n == 0: return 1 if x == 0: return 0 asse...
def _matrix(n, m, value=None): """Utility function to create n x m matrix of a given value""" el = value if callable(value) else lambda i, j: value matrix = [] for i in range(n): row = [] matrix.append(row) for j in range(m): row.append(el(i, j)) return matrix
def _default_axis_names(n_dims): """Name of each axis. Parameters ---------- n_dims : int Number of spatial dimensions. Returns ------- tuple of str Name of each axis. Examples -------- >>> from landlab.grid.base import _default_axis_names >>> _default_axis...
def create_notify_payload(host, nt, usn, location=None, al=None, max_age=None, extra_fields=None): """ Create a NOTIFY packet using the given parameters. Returns a bytes object containing a valid NOTIFY request. The NOTIFY request is different between IETF SSDP and UPnP SSDP. In IETF, the 'location...
def get_cell_from_label(label): """ get cell name from the label (cell_name is in parenthesis) it """ cell_name = label.split("(")[1].split(")")[0] if cell_name.startswith("loopback"): cell_name = "_".join(cell_name.split("_")[1:]) return cell_name
def parse_time_params(age_birth, age_death): """ Converts simple statements of the age at which an agent is born and the age at which he dies with certaintiy into the parameters that HARK needs for figuring out the timing of the model. Parameters ---------- age_birth : int Age at wh...
def flexdefault(arg): """Convert string argument to a slice.""" # We want four cases for indexing: None, int, list of ints, slices. # Use [] as default, so 'in' can be used. if isinstance(arg, str): arg = eval('np.s_['+arg+']') return [arg] if isinstance(arg, int) else arg
def work_strategy1(l, Ve, Vr, Vf, wf, wr): """ a function that returns the work done by a swimmer if they choose to escape from a rip current via strategy 1 """ W1 = ((Ve+Vr)**3)*((l-wf)/Ve) # Calculates work for section swimming in rip channel ...
def update(context, uri=None): """ *musicpd.org, music database section:* ``update [URI]`` Updates the music database: find new files, remove deleted files, update modified files. ``URI`` is a particular directory or song/file to update. If you do not specify it, every...
def to_upper_snake_case(s: str) -> str: """Converts a string from a MixedCaseString to a UPPER_SNAKE_CASE_STRING.""" s = s.upper() r = '' for i in range(0, len(s)): r += s[i] if s[i].isalnum() else '_' return r
def to_internal_byte_order(rpc_byte_order): """ Returns a given RPC byte order hash (bytes) to the format expected by Bitcoin primitives (blocks, transactions, etc.) """ return rpc_byte_order[::-1]
def text_card_generator(card_details): """ Stub card generator monkeypatched into the flight module for testing boarding card printing :param card_details: Boarding card details """ return "\n".join(card_details.values())
def generate_freq_list(d): # dict """ Generate a frequency list from a dictionary """ total = sum(d.values()) freq_list = sorted(d.items(), key=lambda x: x[1], reverse=True) return [(index+1, key, value, round(value/total, 2)) for index, (key, value) in enumerate(freq_list)]
def format_pydantic_error_message(msg): """Format pydantic's error message field.""" # Replace shorthand "str" with "string". msg = msg.replace("str type expected", "string type expected") return msg
def bubble_sort(array): """ Input : list of values Note : Compares neighbouring elements and sortes them. Loops through the list multiple times until list is sorted. Returns : sorted list of values """ is_sorted = False while not is_sorted: is_sorted = True ...
def sample_fib(x): """Calculate fibonacci numbers.""" if x == 0 or x == 1: return 1 return sample_fib(x - 1) + sample_fib(x - 2)
def get_email_value(operation_definition): """Assuming format like: { GetUserByEmail(email: "someemail") { ... } }""" text_after_email = operation_definition.split('email:')[1] unquoted_tokens = text_after_email.split('"') return unquoted_tokens[1]
def eager(x): """Force eager evaluation of a Thunk, and turn a Tuple into a dict eagerly. This forces that there are no unbound variables at parsing time (as opposed to later when the variables may be accessed). Only eagerly evaluates one level. """ if not hasattr(x, 'items'): # The Thunk has been eva...
def flatten(captions_list): """ Flatten all the captions into a single list """ caption_list = [ caption for captions in captions_list for caption in captions ] return caption_list
def isIsomorphic(s,t): """ Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characte...
def shorten(name: str): """Oryza_sativa -> osat""" split = name.lower().split("_") return split[0][0] + split[1][:3]
def two_level_to_single_level_dict(two_level_dict): """ Converts a two-level dictionary to a single level dictionary dict[meeting][speaker] --> dict[speaker] """ assert isinstance((next(iter(two_level_dict.values()))), dict) single_level_dict = {} for _, value1 in two_level_dict.item...
def flatten(lst): """Returns a flattened version of lst. >>> flatten([1, 2, 3]) # normal list [1, 2, 3] >>> x = [1, [2, 3], 4] # deep list >>> flatten(x) [1, 2, 3, 4] >>> x = [[1, [1, 1]], 1, [1, 1]] # deep list >>> flatten(x) [1, 1, 1, 1, 1, 1] """ new_list = [] ...
def euclids_formula(m, n): """ """ assert type(m) is int, "" assert type(n) is int, "" a = m*m - n*n b = 2*m*n c = m*m + n*n return (min(a, b), max(a, b), c)
def mergesort(_list): """ merge sort works by recursively spliting a list down to a binary comparison and then sorting smaller values to the left """ if not isinstance(_list, list): raise TypeError # Need a recursive function that splits a list # in half until a list of length n has n lists of 1...
def bbox_to_extent(bbox): """Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N] args: bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N] returns: extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N] """ return (bb...
def format_special_results(special_results=[]): """ Takes special_results, which is a list of dictionaries, returns a list of election years. Round odd years up to even. Example: [2008, 2000] """ senate_specials = [] for result in special_results: # Round odd years up to even ye...
def scenicToWebotsPosition(pos, y=0): """Convert a Scenic position to a Webots position.""" x, z = pos return [x, y, -z]
def make_time_bc(constraints, bc_terminal): """ Makes free or fixed final time boundary conditions. :param constraints: List of constraints. :param bc_terminal: Terminal boundary condition. :return: New terminal boundary condition. """ time_constraints = constraints.get('independent', []) ...
def _align_chunks(chunks, alignment): """Compute a new chunking scheme where chunk boundaries are aligned. `chunks` must be a dask chunks specification in normalised form. `alignment` is a dictionary mapping axes to an alignment factor. The return value is a new chunking scheme where all chunk sizes, e...
def get_first_defined(data, keys, default_value=None): """ Get the first defined key in data. :param data: :type data: :param keys: :type keys: :param default_value: :type default_value: :return: :rtype: """ for key in keys: if key in data: return data...
def hamming_distance(s1, s2): """ https://en.wikipedia.org/wiki/Hamming_distance#Algorithm_example Return the Hamming distance between equal-length sequences """ if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") s1 = ''.join("{0:08b}".format(ord(c)) fo...
def dhcp_option119(fqdn): """Convert a FQDN to an hex-encoded DHCP option 119 (DNS search domain list, RFC 3397). >>> dhcp_option119("tx1.blade-group.net") '037478310b626c6164652d67726f7570036e657400' """ result = "" for component in fqdn.split("."): result += "{:02x}{}".format(len(compo...
def test_quadruple_args_in_call(x): """Test that duplicated arguments still cause no problem even if there are four of them.""" def g(a, b, c, d): return a * b * c * d return g(x, x, x, x)
def get_kahan_queue_id(output: list): """ obtains the kahan queue id from the output of the qsub command :param output list with all the output lines from kahan server """ return output[0] if len(output) > 0 and output[0].isdigit() else None
def _cmpTop(a, b, what='top 250 rank'): """Compare function used to sort top 250/bottom 10 rank.""" av = int(a[1].get(what)) bv = int(b[1].get(what)) if av == bv: return 0 return (-1, 1)[av > bv]
def sstrip(s, suffix): """Suffix strip >>> sstrip('foo.oof', '.oof') 'foo' >>> sstrip('baroof', '.oof') 'baroof' """ i = - len(suffix) if s[i:] == suffix: return s[:i] return s
def is_folder(url): """ Checks whether a url points to a folder with resources """ if 'mod/folder/' in url: return True else: return False
def generate_checks(container, address, check_ports): """Generates the check dictionary to pass to consul of the form {'checks': []}""" checks = {} checks['checks'] = [] for p in check_ports: checks['checks'].append( {'id': '{}-port{}'.format(container, p), 'name': 'Chec...
def get_data_shapes_resize(masks): """Generating data shapes with img resizing for tensorflow datasets depending on if we need to load the masks or not outputs: data shapes with masks = output data shapes for (images, ground truth boxes, ground truth labels, masks, mask id labels) data shapes wi...
def check_index_file_type(file_name: str) -> str: """ Get the index file type based on the extension of given `file_name` :param file_name: index file name :return: file type """ if file_name.endswith(".fa.gz"): return "fasta" elif file_name.endswith(".json.gz"): return "js...
def head(_b, _x): """Determine the number of leading b's in vector x. Parameters ---------- b: int Integer for counting at head of vector. x: array Vector of integers. Returns ------- head: int Number of leading b's in x. """ # Initialize counter _h...
def _get_space(space): """Verify requested colorspace is valid.""" space = space.lower() if space in ('hpluv', 'hsluv'): space = space[:3] if space not in ('rgb', 'hsv', 'hpl', 'hsl', 'hcl'): raise ValueError(f'Unknown colorspace {space!r}.') return space
def _make_list(obj): """Returns list corresponding to or containing obj, depending on type.""" if isinstance(obj, list): return obj elif isinstance(obj, tuple): return list(obj) else: return [obj]
def _tags_to_dict(s): """ "k1=v1,k2=v2" --> { "k1": "v1", "k2": "v2" } """ return dict(map(lambda kv: kv.split('='), s.split(",")))