content
stringlengths
42
6.51k
def isnumber(v): """Return true if we can treat v as a number""" try: return v==0 or v!=0 except TypeError: return False
def silent_none(value): """ Return `None` values as empty strings """ if value is None: return '' return value
def make_file_prefix(run, component_name): """ Compose the run number and component name into string prefix to use with filenames. """ return "{}_{}".format(component_name, run)
def transform_entity_bmes_labels_to_spans(label_sequence, classes_to_ignore=None): """ Given a sequence of BMES-{entity type} labels, extracts spans. """ spans = [] classes_to_ignore = classes_to_ignore or [] index = 0 while index < len(label_sequence): label = label_sequence[index] ...
def expand_1D(x, num_years): """ Expand the given data to account for the given number of budget years. Expanded entries are None by default """ if len(x) >= num_years: return list(x) else: ans = [None] * num_years ans[:len(x)] = x return ans
def remove_duplicate_tracks(titles): """Workaroud for stupid DVDs, that have identical copies of the same tracks. Might throw away some false positives, since only title duration and tracks are compared. This only detects duplicate titles directly one after another.""" ret = [] last = None f...
def even_or_odd(value: int) -> bool: """ BIG-O Notation = O(1) """ return value % 2 == 0
def process_custom_fields(customfields): """Perform some minor processing on customfields dictionaries so that they spread out into csv columns more conveniently. Arguments: customfields (dict): A similar to customfields from Netbox. Returns: dict: The post-process customfields. "...
def driver_cap(req): """butter volumes are local to the active node. They only exist as snapshots on the remote nodes. """ return {"Capabilities": {"Scope": "local"}}
def upper_letter_drive(file_path): """ makes the letter drive upper case""" if file_path[1] == ":": return file_path[0].upper() + file_path[1:] return file_path
def scale_pt(p, scale): """Scales p=(x,y) by scale""" return (p[0] * scale[0], p[1] * scale[1])
def gamma_moments_burden(mean, sd): """Calculates the moments of a gamma distribution based on mean and sd as they are more intuitive inputs More info on gamma: https://en.wikipedia.org/wiki/Gamma_distribution Inputs: mean - a float - the chosen mean of the distribution sd...
def create_dict(*idxes): """ create nested dictionary with the given idxes """ height = len(idxes) output = {} stack = [output] for depth in range(height): stack_temp = [] while len(stack) > 0: cur_elmt = stack.pop() for idx in idxes[depth]: ...
def _json_add_scanedge_filter(json, value): """ Add EdgeOfFlightLine Filter element and return """ json['pipeline'].insert(0, { 'type': 'filters.range', 'limits': 'EdgeOfFlightLine[{0}:{0}]'.format(value) }) return json
def hex_from_integer(the_integer): """ Encode a hexadecimal string from an arbitrarily big integer. Like hex() but output has: an even number of digits, no '0x' prefix, no 'L' suffix. """ # THANKS: Mike Boers code, http://stackoverflow.com/a/777774/673991 hex_string = hex(the_integer)[2:].rst...
def done(state): """ Are we done? """ for row in state: for cell in row: if isinstance(cell, set): return False return True
def replace_arcs_suffix(src, suffix = ""): """Cleans up the given file name, and replaces the .arcs extension with the provided suffix.""" # For references to files in other build targets, extract the filename: # //src/wasm/tests:manifest.arcs -> manifest.arcs if src.startswith("//"): src = s...
def split_ticker_information(ticker): """ Split a ticker into a (source_code, source_ticker) pair. DEPRECATED: use ticker.py For now, no error handling... :param ticker: str :return: tuple """ # Leave this off for now. # logging.warning('split_ticker_information() is deprecated.') ...
def zip_toggle(xs): """[[x1, ...], [x2, ...], [x3, ...]] --> [(x1, x2, .., xn) ...]; [(x1, x2, .., xn) ...] --> [[x1, ...], [x2, ...], [x3, ...]]""" assert isinstance(xs, list) return list(zip(*xs))
def get_subnet_cidr_suffix(ips_count, cidr_suffix_ips_number_mapping): """Get subnet cidr suffix Args: ips_count (integer): Ips count cidr_suffix_ips_number_mapping (dict): Cidr suffix ips number mapping Returns: string: subnet cidr suffix """ ...
def indent(text, indent=" "): """ Indent text by the given indentation string. """ return "\n".join(indent + line for line in text.splitlines())
def tokenize_doc(json_data): """ Tokenize a document and return its bag-of-words representation. doc - a string representing a document. returns a dictionary mapping each word to the number of times it appears in doc. """ words = {} for w in json_data['ingredients']: if w not in wor...
def create_output_filename_from_args(sub=None, ses=None, task=None, acq=None, run=None, desc=None, recording=None): """ Creates filename for the model output """ output_expr = ['sub-{}'.format(sub) if sub else None, 'ses-{}'.format(ses) if ses else None, ...
def read_one_AD(box, ADnumber): # required by Whand """ Input driver for numbers in Whand. Scans one input at a time The current Raspy hardware does not support analog input called by whand_io box is 0 to Boxes-1 ADnumber identifies the analog input ...
def is_matrix_square(M): """Verify that a matrix is square. Parameters ---------- M : list[list[float]] The matrix. Returns ------- bool True if the length of every row is equal to the number of rows. False otherwise. Examples -------- >>> M = identity_...
def skip_command_response(text: str) -> int: """ Skip specified number of lines from the beginning of a text string. :param text: Text string with zero or many '\n' in. :return: Return position of the first character after the command response is skipped. """ l = len(...
def getattr_safe(obj, name, default=None): """ A safe implementation of :func:`getattr <python3:getattr>`. If an attr exists, but calling getattr raises an error, this implementation will silence the error and return the ``default`` value. Parameter --------- obj : object Any obje...
def _apply_filters(filters, traces): """ Here we make each trace go through the filters configured in the tracer. There is no need for a lock since the traces are owned by the AgentWriter at that point. """ if filters is not None: filtered_traces = [] for trace in traces: ...
def global_max(col_vals, index): """Returns the global maximum and minimum""" max_col, min_col = zip(*col_vals) return max(max_col), min(min_col)
def rjust(string, amt): """Right-align the value by the amount specified. Equivalent to Djangos' rjust. Args: string (str): The string to adjust. amt (int): The amount of space to adjust by. Returns: str: The padded string. """ return string.rjust(amt)
def rhs_hidden_from_state_dict(state): """Determine the hidden argument for RHS from the state dictionary """ import re pattern = re.compile('rhs\.mlp\.(\d)\.bias') sizes = {} for key, val in state.items(): m = pattern.search(key) if m: step = int(m.group(1)) ...
def flatten(l): """Expands list""" return [item for sublist in l for item in sublist]
def read_le(value): """Interpret multi-byte value from file as little-endian value""" result = 0 shift = 0 for byte in value: result += byte << shift shift += 8 return result
def filter_root_objects(objects): """Get root objects (objects without parents) in Blender scene""" root_objects = [] for obj in objects: if obj.parent is None: root_objects.append(obj) return root_objects
def getNamePrefix(name): """For Cylinder.001 returns string "Cylinder" """ try: location = len(name) - "".join(reversed(name)).index(".") # index is never used, but this line ensures that the index is an int. index = int(name[location:]) prefix = name[:location-1] except Exce...
def reverses_transpose(trans1, trans2, dim=None): """Checks if one transpose reverses another. If a dim is provided then look if the transpose sequence produces an equivalent dim to cope with 1s in dimensions.""" if trans1 is None or trans2 is None: return False if dim and dim.layout_shape =...
def compute_degrees(edges): """ Compute the degree of vertices. @param edges list of tuple @return dictionary {key: degree} """ res = {} for a, b in edges: res[a] = res.get(a, 0) + 1 res[b] = res.get(b, 0) + 1 return res
def get_full_indices(dim): """ The indices for converting the symmetric storage to the full storage. """ return { 2 : [[0, 2], [2, 1]], 3 : [[0, 3, 4], [3, 1, 5], [4, 5, 2]], }[dim]
def get_new_snp(vcf_file): """ Gets the positions of the new snp in a vcf file :param vcf_file: py_vcf file :return: list of new snp """ new_snp = [] for loci in vcf_file: if "gff3_notarget" in loci.FILTER: new_snp.append(loci) return(new_snp)
def pa11y_counts(results): """ Given a list of pa11y results, return three integers: number of errors, number of warnings, and number of notices. """ num_error = 0 num_warning = 0 num_notice = 0 for result in results: if result['type'] == 'error': num_error += 1 ...
def is_kind_of_class(obj, a_class): """ Return True if the object is an instance of the specified class Args: obj: the object to be tested a_class: the class to be tested against Returns: True if the object is an instance or inherited instance of the specified class ...
def member_to_index(m_name, members): """ Given a member name, return the index in the members dict @param m_name The name of the data member to search for @param members The dict of members @return Index if found, -1 not found Note we could generate an index when processing the original input ...
def no_augmentation(x, y=None, epoch=0, rng=None, **kwargs): """If the trainer isn't supplied a function for data augmentation, use this blank function instead.""" if y is None: return x else: return x, y
def point_in_polygon(pnt, poly): #pnt_in_poly(pnt, poly): # """Point is in polygon. ## fix this and use pip from arraytools """ x, y = pnt N = len(poly) for i in range(N): x0, y0, xy = [poly[i][0], poly[i][1], poly[(i + 1) % N]] c_min = min([x0, xy[0]]) c_max = max(...
def cap_item(tag, data): """Creates a new CAP item""" if len(data) > 0xffff: raise ValueError("Data is too long") return bytes([tag, len(data) >> 8, len(data) & 0xff]) + data
def _read_tagmap(data, separator=';', comment='#', joiner=' ', tag_column=0, unicode_column=1): """Read a tag map from file data.""" chr2tag = {} for line in data.decode('utf-8').splitlines(): if line.startswith(comment): continue columns = line.split(separator) if len(co...
def uid_byte(byte: int) -> int: """Calculate CRC for single byte. Keyword arguments: byte - byte to calculate CRC """ for _ in range(8): byte = (byte >> 1) ^ 0xA001 if byte & 1 else byte >> 1 return byte
def makeGeometryUpdate(hsX, hsY): """ Prepare a message containing the field geometry info """ return { 'messageType': 'geometry', 'payload': { 'halfSizeX': hsX, 'halfSizeY': hsY, }, }
def notification(alert=None, ios=None, android=None, winphone=None): """Create a notification payload. :keyword alert: A simple text alert, applicable for all platforms. :keyword ios: An iOS platform override, as generated by :py:func:`ios`. :keyword android: An Android platform override, as generated ...
def removespeed(videofile): """some of my files are suffixed with datarate, e.g. myfile_3200.mp4; this trims the speed from the name since it's irrelevant to my sprite names (which apply regardless of speed); you won't need this if it's not relevant to your filenames""" videofile = videofile.strip() ...
def get_failed_conditions(conditions): """Get a comma separated string for the conditions that failed.""" if conditions is None: return '' return ', '.join([c.condition.name for c in conditions if not c.nominal])
def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index v &= ~mask if x: v |= mask return v
def are_equal(a, b): """compare the values of two arrays""" length = len(a) if length != len(b): raise ValueError('Compared arrays should have same length!') if sum([(a[k]-b[k])**2 for k in range(0,length)]) > 1: return False else: return True
def lowercase_range(code1, code2): """ If the range of characters from code1 to code2-1 includes any upper case letters, return the corresponding lower case range. """ code3 = max(code1, ord('A')) code4 = min(code2, ord('Z') + 1) if code3 < code4: d = ord('a') - ord('A') ...
def convert_length_in_minutes_to_hr_min_str(length_minutes=0): """ Convert minutes into something like 02h03m if given 123. Note that both hr and min are 0-padded """ hour = length_minutes // 60 minutes = length_minutes % 60 return "%02dh%02dm" % (hour, minutes)
def strip_extra_slashes(value: str) -> str: """Combine multiple trailing slashes to a single slash""" if value.endswith('//'): return value.rstrip('/') + '/' return value
def _get_vector_identifier(line): """Return the identifier from the vector string. """ return line.split()[0]
def process_exit_code(retval): """Process a waitpid returned exit code. :return: The exit code if it exit'd, the signal if it died from signalling. """ # If it got a signal, return the signal that was sent. if retval & 0xff: return (retval & 0xff) << 8 # Otherwise, return its exit code...
def get_name_from_vararg(full_name): # type: (str) -> str """ Extract the vararg name from the name given with full_name. Part before "*". :param full_name: Complete vararg name. :return: The vararg name """ return full_name.split('*')[1]
def sup_str_to_num(support_str): """Converts a support string into usable numbers.""" mn = -1.0 if support_str == "-1->1" else 0.0 mx = 255.0 if support_str == "0->255" else 1.0 return mn, mx
def is_pc(note): """check if note has the same format as pc, return boolean""" return note in range(12)
def get_list_index(ls_object=[], find_str=""): """ find a string index from list provided. :param ls_object: <list> the list to find the string frOpenMaya. :param find_str: <str> the string to find inside the list. :return: <int> the found index. -1 if not found. """ try: return ls_o...
def remove_short_transition(transition_sites,thresh=120): """ removes transitions that are too close from others. """ if len(transition_sites) < 4: return transition_sites for i in range(len(transition_sites) - 1): forward_difference = transition_sites[i+1] - transition_sites[i] ...
def disable_option(value): """Converts a boolean option to a CMake ON/OFF switch""" return 'OFF' if value else 'ON'
def reverse_transcribe(seq): """reverse transcribes a dna sequence (does not convert any non-atcg/ATCG characters)""" watson_crick = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g'} return ''.join([watson_crick.setdefault(c, c) for c in seq[::-1]])
def kesirKarsilastirma(kesir1, kesir2): """ kesir1 ve kesir2, [pay, payda] seklinde tutulan iki elemanli listelerdir. Buyukten kucuge, ya da kucukten buyuge siralama yaparken iki kesrin karsilastirilmasini bu fonksiyon blogunda tanimlayiniz: Kodunuzu bu satirdan itibaren yaziniz, verilen satirlari silmeden istedi...
def permute_by_indices(list_of_things, *list_of_index_transpositions): """Given a list_of_things and a list of pairs of transpositions of indices [(i, j), (k, m), ...], return the list_of_things with the i-th an j-th values swapped, the k-th- and m-th values swapped, and so on. Examples -------- ...
def gcd(a, b): """ a, b: two positive integers Returns the greatest common divisor of a and b """ if b == 0: return a return gcd(b, a % b)
def solution(A): # O(N) """ Given an array find the first non-repeating integers in the array >>> solution([3, 2, 3, 2, 5, 4, 3, 4]) 5 >>> solution([3, 2, 3, 2, '%', 5, 4, 'd', 3, 4]) 5 >>> solution([3, 2, 3, 2, 5, 4, 3, 4, 8]) 5 >>...
def LCS(A, B): """ Solver for LCS(Longest common subseqeunce problem), DP solution :param A: string A :param B: string B :return: the length of LCS """ n = len(A) m = len(B) if m == 0 or n == 0: return -1 c = [[0 for _ in range(m + 1)] for _ in range(n + 1)] for i in ...
def make_all_author_patches_query(project, owner, status='status:open'): """ Make a query string for fetching all patches on a project that belong to author. The default status is open. returns: Query string containing all """ ret = 'project:' + project ret += ' AND ' + status r...
def try_key(dictionary, default, *keys): """ Tries to get all keys in a nested dictionary. """ try: res = dictionary for k in keys: res = res[k] return res except (KeyError, IndexError) as e: return default
def clean_quotes(row): """ Handle unquoted quotes in fields from CANVAS. """ if row[8].startswith('WINDOWS MISSING OR CRACKED BEYOND') or row[8].startswith('SUSPENSION MODIFIED BEYOND'): fixed_cols = row[8].replace('"', '').split('$') row = row[:8] + fixed_cols + row[9:] return row
def check_answer(d: dict, answer_key: str) -> bool: """ """ return d['correct'] == answer_key
def factorial(n): """ for loop implementation 0, 1 ==> 1 """ ret = 1 for i in range(2, n+1): ret *= i return ret
def get_id_from_ns_name(ns_name): """Parses identifier from prefix-identifier :param ns_name: The name of a namespace :returns: Identifier or None if there is no - to end the prefix """ dash_index = ns_name.find('-') if 0 <= dash_index: return ns_name[dash_index + 1:]
def format_time(time): """Formats the time to a human-readable expression.""" m, s = divmod(round(time), 60) h, m = divmod(m, 60) return 'Hours: %s, Minutes: %s, Seconds: %s' % (h, m, s)
def __parse_ogp(metas): """ Extract meta tag contents data having `property`. Arguments: metas: Extracted meta tag data having `contents` Return: [dict] results: Extracted meta tag contents data having `property` """ ogps = list(filter(lambda x: x.has_attr('property'), metas)) ...
def create_star_tmp(tmp_path:str, tmp_name:str='STAR'): """ Ensure the specified directory is ready for use as the temp directory for STAR. In particular, it ensures that tmp_path exists and that tmp_path/tmp_name does not exist (so STAR can create it). N.B. This function *does not* use sophi...
def lcs(a, b): """ Return the list of the LCS of two lists. """ lengths = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)] # row 0 and column 0 are initialized to 0 already for i, x in enumerate(a): for j, y in enumerate(b): if x == y: lengths[i+1][j+1]...
def configs_conflict(a, b): """Given two configurations, determine whether they overlap (i.e., have nonzero parameters for at least one site in common). """ a_dict = dict(a) b_dict = dict(b) assert a_dict.keys() == b_dict.keys() for ident, a_param in a_dict.items(): if a_param and b...
def filter_none(lst): """Removes None elements from the list.""" lst = [el for el in lst if el is not None] return lst
def _get_train_steps(num_examples, train_epochs, train_batch_size): """Determine the number of training steps.""" return num_examples * train_epochs // train_batch_size + 1
def default_colors(keys, colors=None, reverse=False): """Generates a repeating color pallette A list of colors can be passed to the `colors` arg. The `reverse` arg, if `True`, reverses `colors` before building the dictionary. """ if colors == None: colors = ['#232C65', '#840032', '#...
def lookup_prev_stage_start(stage_boundaries, t): """ Returns the previous stage start timestamp from a list/set of stage boundaries and current time. """ return max([0] + [x for x in stage_boundaries if x <= t])
def matchRatings(data): """matches ratings data to lables""" matchedData = [] lable = [] lable.append("5-star") matchedData.append(data.count(5)) lable.append("4-star") matchedData.append(data.count(4)) lable.append("3-star") matchedData.append(data.count(3)) lable.append("2-star...
def check_filename(filename): """ Checks if filename adheres to the correct format. """ if '.txt' in str(filename[0]) or '.vtk' in str(filename[0]): return True else: return False
def leak_decay(A, B, lambda_1, m): """ Eq. (9) of Wood Gambetta 2018. A ~= L2/ (L1+L2) B ~= L1/ (L1+L2) + eps_m lambda_1 = 1 - L1 - L2 """ return A + B * lambda_1 ** m
def conv_grid_coords(x, y): """Converts portrait grid coords into landscape grid coords""" return 5-y, x
def calculateMean(interval, wrapAt=360.): """Calculates the mean point of an interval.""" if wrapAt is None: return (interval[0] + (interval[1] - interval[0]) / 2.) else: return ((interval[0] + ((interval[1] - interval[0]) % wrapAt) / 2.) % wrapAt)
def solve1(a, b, EPS=1e-6): """ Returns root of equation a*x + b = 0. """ # a*x + b = 0 if abs(a) < EPS: return () else: return (complex(-b/a),)
def quarter_start_month(quarter): """month that starts quarter for Gregorian calendar: Jan, Apr, Jul, Oct""" if quarter not in range(1, 5): raise ValueError("invalid quarter") return {1: 1, 2: 4, 3: 7, 4: 10}[quarter] # return 3 * quarter - 2
def create_cloudwatch_event( detail_type: str, detail: str, source: str, resources: list = [], additional_args: dict = {}, ) -> dict: """Create a simple cloudwatch event""" return { "Source": source, "DetailType": detail_type, "Resources": resources, "Detail":...
def next_player_who_has_cards(players_to_check_in_order, hands): """ Find the next player who still has cards """ for player in players_to_check_in_order: if hands[player]: return player return None
def filter_tags(tag_list, *args): """ - Filters a tag set by exclusion - variable tag keys given as parameters, tag keys corresponding to args are excluded RETURNS TYPE: list """ clean = tag_list.copy() for tag in tag_list: for arg in args: if a...
def _get_attr(original): """Get a friendly name from an object header key.""" key = original.replace('-', '_') key = key.replace('x_object_meta_', '') return key
def uniquify_list(seq): """ Uniquify a list by preserving its original order """ seen = set() return [i for i in seq if i not in seen and not seen.add(i)]
def map_code_to_status(http_code: int): """Maps HTTP code to human-readable descriptive string""" if 100 <= http_code <= 199: return 'INFO' elif 200 <= http_code <= 299: return 'SUCCESS' elif 300 <= http_code <= 399: return 'REDIRECT' elif 400 <= http_code <= 499: ret...
def obj_to_dict(obj): """Converts XML object to an easy to use dict.""" if obj is None: return None res = {} res['type'] = obj.tag res['id'] = obj.get('id') res['version'] = int(obj.get('version')) res['deleted'] = obj.get('visible') == 'false' if obj.tag == 'node' and 'lon' in o...
def luhn10_check(number): """Return True if the number passes the Luhn checksum algorithm.""" sum = 0 while number: r = number % 100 number //= 100 z = r % 10 r = r // 10 * 2 sum += r // 10 + r % 10 + z return 0 == sum % 10