content
stringlengths
42
6.51k
def rebuild_optional(matched_group: str) -> str: """ Rebuild `Union[T, None]` as `Optional[T]`. Arguments: matched_group: The matched group when matching against a regular expression (by the parent caller). Returns: The rebuilt type string. """ brackets_level = 0 for char i...
def total_after(integer_number): """Returns the total number of grains on the chess board for given number of squares. See README file for how it is calculated. The calculation is essentially a Geometric series where a=1, r=2 and the sum of such a series is given by a(1-r**n) ...
def get_features_json_file_path(input_image_path): """Get the appropriate features JSON output path for a given image input. Effectively appends "--features" to the original image file and places it within the same directory. Parameters ----------- input_file_path: str Path to input i...
def zap_blank_lines(text): """Return blank line compressed string.""" if not text: # Early out return empty text return "" non_blanks = (line for line in text.splitlines() if not line.isspace()) return '\n'.join(non_blanks) + '\n'
def nested_dict_retrieve(data, keys, dflt): """ Used to get a value deep in a nested dictionary structure For example .. code-block:: python data = {"one": {"two": {"three": "four"}}} nested_dict_retrieve(data, ["one", "two", "three"], 6) == "four" nested_dict_retrieve(data,...
def fake_telegram_me(*args, **kwargs): """Return a fake telegram user.""" return { "id": 0, "first_name": "Test", "is_bot": True, "username": "YOUR_TELEGRAM_BOT", }
def calc_workload_dis_factor(target_workload_pair, workload_pair): """Calculate the distance factor of the workload to the target workload. If two workloads are not compatible at all (i.e., different compute DAG or function), then the distance factor is "inf". Otherwise, we calculate the factor by traversin...
def change_same_starting_points(flaglist): """Gets points at which changes begin""" change_points = [] same_points = [] in_change = False if flaglist and not flaglist[0]: same_points.append(0) for x, flag in enumerate(flaglist): if flag and not in_change: change_po...
def stripQuote(s): """stripquote(s) - strips start & end of string s of whitespace then strips " or ' from start & end of string if found - repeats stripping " and ' until none left.""" if s != str: return s s = str(s).strip() while len(s) > 0 and (s[0] in ["'", '"'] and s[-1] in ["'", '"']): ...
def divide(items, divider): """Divide a list in two depending on the divider method >>> divide([0, 1, 2, 3], lambda x: x < 1) == ([0], [1, 2, 3]) True """ trues = [] falses = [] for item in items: if divider(item): trues.append(item) else: falses.appe...
def _extract_bike_location(bike, lon_abbrev='lon'): """ Standardize the bike location data from GBFS. Some have extra fields, and some are missing fields. Arguments: bike (dict[str, str]): A GBFS bike object as it appears in free_bike_status.json lon_abbrev (str): The abbreviation used for `longitude` ...
def link_entries(entries): """ link entries to 'Section' back references, and file references into sections """ for id in entries.keys(): entry = entries[id] if entry.is_file(): continue for child_id in entry.children.keys(): # for each of this entry's children, see if it # exists in the main entry...
def is_valid_persal_no(persal_no): """A very basic persal_no validation check""" return len(persal_no) >= 1
def make_bed_from_node_name(node_name): """ :param node_name: takes standard node that is bed3 format and returns bed string. :return: """ node_name = node_name.split("_") chrom = "_".join(node_name[0:-2]) start = node_name[-2] stop = node_name[-1] return [chrom,start,stop]
def group_actions(actions): """Reformat the actions into a format more suitable for apply to an existing SQL script that creates tables. """ # Table name to column name. primary_keys = {} # Table name to list of (column, table, name_in_table) foreign_keys = {} for action in actions: ...
def get_emotion_dict(emo_metrics): """Returns a dictionary in which keys are emotions and values are confidences. Args: emo_metrics: A list of dictionaries, which each have the keys 'name' and 'confidence', describing emotions detected from FeelNet. Returns: A dictionary as described above. """ ...
def bytes_to_int(byteseq): """Convert a sequence of up to 4 bytes to a single integer.""" result = 0 for byte in byteseq: result = result << 8 result += byte return result
def UniqueElements(x: list) -> list: """Returns unique elements of a list (not order preserving).""" keys = {} for e in x: keys[e] = 1 return list(keys.keys())
def create_bullet_string(file_list): """From the list of files for a single toc, create a bullet point string.""" toc_string = "" for f in file_list[0:3]: toc_string += "- [](" + f + ")\n" if len(file_list) > 3: toc_string += "\nAnd more... \n" return toc_string
def SubStringExistsIn(substring_list, string): """Return true if one of the substring in the list is found in |string|.""" for substring in substring_list: if substring in string: return True return False
def calc_fuel_for_mass(mass: int): """ fuel required is is mass divided by 3, rounded down, minus 2 """ return (mass // 3) - 2
def getReplyID(tweet): """ If properly included, get the ID of the user the tweet replies to """ if 'in_reply_to_user_id' in tweet and \ tweet['in_reply_to_user_id'] is not None : return tweet['in_reply_to_user_id'] else : return None
def get_nb_element_per_dimension(recipe): """Count the number of element to stack for each dimension ('r', 'c' and 'z'). Parameters ---------- recipe : dict Map the images according to their field of view, their round, their channel and their spatial dimensions. Only contain the key...
def add_number(phone_numbers: dict, name: str, num) -> dict: """Function to add/update number to the list (dictionary).""" name.capitalize() # if statement checks if the number entered is numeric and 10 digits long - if num.isnumeric() and num.__len__() == 10: phone_numbers.update({name: num})...
def convert_set_to_ranges(charset): """Converts a set of characters to a list of ranges.""" working_set = set(charset) output_list = [] while working_set: start = min(working_set) end = start + 1 while end in working_set: end += 1 output_list.append((start, end - 1)) working_set.differ...
def _RemoveFlagsPrecedingCompiler( flags ): """Assuming that the flag just before the first flag starting with a dash is the compiler path, removes all flags preceding it.""" for index, flag in enumerate( flags ): if flag.startswith( '-' ): return ( flags[ index - 1: ] if index > 1 else ...
def permission_to_04_acls(permissions): """ Legacy acl format kept for bw. compatibility :param permissions: :return: """ acls = [] for perm in permissions: if perm.type == "user": acls.append((perm.user.id, perm.perm_name)) elif perm.type == "group": ...
def format_field(relation_name, field): """Util for formatting relation name and field into sql syntax.""" return "%s.%s" % (relation_name, field)
def trim(s, prefixes, suffixes): """ naive function that trims off prefixes and suffixes """ for prefix in prefixes: if s.startswith(prefix): s = s[len(prefix):] for suffix in suffixes: if s.endswith(suffix): s = s[:-len(suffix)] return s
def add(a, b): """ Adds two numbers using only bit manipulations. The algorithm is called Kogge-Stone adder: http://en.wikipedia.org/wiki/Kogge-Stone_adder Params: a: int, first number, can be negative b: int, second number, can be negative Returns: int, sum of the the two num...
def normalize_time(time_format, time_duration): """ Takes a 'time_format' tuple and a 'time_duration' list and calculates the proper duration of time_duration so it respects time_format specifications """ if not time_format or not time_duration: raise RuntimeError('Mising or \'None\' argumen...
def genomic_dup3_abs_38(genomic_del3_dup3_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.cQATJ6a1uGwXOHu-advv8lRsMgjNLKul", "subject": genomic_del3_dup3_loc, "copies": {"type": "Number", "value": 2} }
def scl_map(x_elem): """Maps one element from x to the given class on our standard Parameters: x_elem (int): class value from the scl Returns: int: class number in the classification format """ if x_elem == 4: return 2 if x_elem == 5: return 1 if x_elem == 6: ...
def sanitize_key(dct, kname): """Returns copy of the `dct` without `kname` field from the given `dct` and all it's subdct's. """ # Support for custom types with dict API type_ = type(dct) new_dct = type_() for key, val in dct.items(): if isinstance(val, type_): new_dct[k...
def append(prev: str, new: str) -> str: """ Concatenates two strings, adding a new line character between the two strings if the first string is not empty. """ if prev: return prev + "\n" + new else: return new
def send_message(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: S...
def _lab_transform(t): """ Returns the cube root tranformation function from xyz color space to lab color space. """ if t > 216. / 24389.: return t ** (1. / 3.) return 841. / 108. * t + 4. / 29.
def sortby(somelist, n): """ Suppose, for example, you have a list of tuples that you want to sort by the n-th field of each tuple. """ nlist = [(x[n], x) for x in somelist] nlist.sort() return [val for (key, val) in nlist]
def reverse_cols_lr(matrix): """ Flip order of the columns in the matrix[row][col] Using numpy only fits matrix lists with numbers: np_matrix = np.array(matrix) return np_matrix.fliplr().tolist() To suit any list element type use general fliplr. """ result = [] for row...
def likelihood_with_regularization_from_inversion_terms( chi_squared, regularization_term, noise_normalization ): """Compute the likelihood of an inversion's fit to the datas, including a regularization term which \ comes from an inversion: Likelihood = -0.5*[Chi_Squared_Term + Regularization_Term + No...
def replace_chars(value, deletechars='\/:*?"<>|'): """ Removes non-legal chars :param value: :param deletechars: :return: """ for c in deletechars: value = value.replace(c, '') value.replace(" ", "_") return value;
def expand_unknown_vocab(line, vocab): """ Treat the words that are in the "line" but not in the "vocab" as unknows, and expand the characters in those words as individual words. For example, the word "Spoon" is in "line" but not in "vocab", it will be expanded as "<S> <p> <o> <o> <n>". """ ...
def check_user_type(is_contract: bool) -> str: """ Checks the type of a actor in the network :param is_contract: boolean :return: string C or U for contract or user. """ if is_contract == True: return 'C' else: return 'U'
def get_node_index(glTF, name): """ Return the node index in the glTF array. """ if glTF.get('nodes') is None: return -1 index = 0 for node in glTF['nodes']: if node['name'] == name: return index index += 1 return -1
def dx(a, b, n): """ Width of subintervals in partitioning of [a, b] in to n equal parts """ return (b - a) / n
def _id_to_str_util(doc): """Used to resolve the following error: TypeError: Object of type ObjectId is not JSON serializable :param doc: :return: """ doc['_id'] = str(doc['_id']) return doc
def max_returns(prices): """ Calculate maximum possible return Args: prices(array): array of prices Returns: int: The maximum profit possible """ min_price_index = 0 max_price_index = 0 current_min_price_index = 0 for idx, price in enumerate(prices): if price...
def has_consequential_property(exchange): """Return list of consequential properties from an exchange""" return [prop for prop in exchange.get('properties', []) if prop['name'] == 'consequential' and prop['amount'] == 1]
def _replace_md(match): """ If the "MD" professional title was matched, make sure it's got no punctuation in it. :param match: a regular expression matched to a string """ if not match or len(match.groups()) < 1: return match return match.groups()[0] + "MD"
def FmtD(x): """Return a nicely formatted string for number x.""" if abs(x - round(x)) < 1e-40: return str(int(x)) if abs(x) < 1e-3: return "{:.2e}".format(x) return "{:.3f}".format(x)
def matrix_multiplier(mat1, mat2): """Multiplies Two matrix of any size""" # empty list for storing multiplied rows multiplied_matrix = [] for row1 in mat1: # list for adding multiplied value rows = [] for col2 in zip(*mat2): sum1 = 0 for (a, ...
def json_traversal(data, key_to_find, ret_dict=False): """ PENDING MODIFICATION TO MORE GENERALIZED NOTATION Recursive function to traverse a JSON resposne object and retrieve the array of relevant data (value or full key/value pair). Only a single key needs to be found within the dictionary in ord...
def getPair(v): """ Parses a variant (9338V) and splits it into its numeric and alphabetic bits... """ i=0 vlen = len(v) num = 0 while i < vlen: if v[i] >= '0' and v[i] <= '9': num = (num*10) + int(v[i]) i += 1 else: break # some variants have a trailing * to indicate th...
def _create_trained_wights_dict(matconv_params_list): """ Creates dictionary with layer param name as a key and trained parameters as a value. Note that in matconvnet param.value in refers to trained weights. :param matconv_params_list: :return: """ trained_weights_dic = {} for mcn_lr_pa...
def create_return_response(status_code, body): """ Create return status using a fixed set of header options and the status_code and body passed as parameters. Parameters ---------- status_code: int HTTP status code of return response body: str Body of return response """...
def IsInclude(line): """Returns True if the line is an #include/#import/import line.""" return any([line.startswith('#include '), line.startswith('#import '), line.startswith('import ')])
def get_submatrix(m, rows, cols): """ Gets the selected positions from the matrix and inserts them into the submatrix. Args: m: the larger matrix rows: list of the indexes of the rows to select from cols: list of the indexes of the columns to select from Returns: ...
def Main(a, b): """ :param a: :param b: :return: """ if a == b: return True return False
def after_last_x(text, x): """ after_last_x(str, str) -> str >>> after_last_x("enum class Actions", " ") 'Actions' >>> after_last_x("enum Actions", " ") 'Actions' """ i = text.rfind(x) if i > -1: return text[i+1:] return None
def correlation_criterion(x, a, b): """ This function returns the correlation coefficient for respective input parameters x = [u, v, dudx, dudy, dvdy, dvdx] """ cc = 0 return cc
def _get_annotations(cls): """ Get annotations for *cls*. """ anns = getattr(cls, "__annotations__", None) if anns is None: return {} # Verify that the annotations aren't merely inherited. for base_cls in cls.__mro__[1:]: if anns is getattr(base_cls, "__annotations__", None)...
def HTMLColorToRGB(colorString): """ Convert #RRGGBB to a [R, G, B] list. :param: colorString a string in the form: #RRGGBB where RR, GG, BB are hexadecimal. The elements of the array rgb are unsigned chars (0..255). :return: The red, green and blue components as a list. """ colorString = co...
def print_palindromes_from_list(palindrome_list): """ Given a list with palindrome positions, lengths and sequences, print the positions and lengths separated by a whitespace, one pair per line. """ for palindrome in palindrome_list: print("%s %s" % ( palindrome[0], palindrome[1]...
def rgb_to_hex(r, g=0, b=0, a=0, alpha=False): """ Returns the hexadecimal string of a color :param r: red channel :param g: green channel :param b: blue channel :param a: alpha channel :param alpha: if True, alpha will be used :return: color in a string format such as #abcdef ...
def correctHER2(text): """ This is to correct for an error introduced when converting the pdf to xml. The error is the inclusion of the watermark "FOR PERSONAL USE ONLY" in some of the data items. Upon close inspection of the data, we see that in most of the HER2 values an additional unwanted "NAL" ...
def takeBlock(aList, row_l,row_r,col_l,col_r): """ Take sublist given from row row_l to row_r and column col_l to col_r from a double list. The convention for the index of the rows and columns are the same as in slicing. """ result = [] for aRow in aList[row_l:row_r]: result.append(aRow[col_l:col_r]) return res...
def stripPinnedVerDep(dep): """ Function to keep only the package name and remove everything else """ if "=" in dep: name = dep[:dep.index("=")] else: return dep return name
def to_degC(value): """Convert binary sysctl value to degree Centigrade.""" return round(int.from_bytes(value, byteorder="little") / 10 - 273.15, 1)
def lensing_efficiency_cmb(x, xs): """Parametric lensing efficiency cmb. This function computes the cmb lensing efficiency function given in [1]_. Parameters ---------- x : (nx,) array_like Array of comoving distances at which evaluate the lensing efficiency function. xs : ...
def vartype_map(ref_alt_bases): """ This function assigns the following vartypes to the allele specified by allele_base_col: snp, mnp, ins, del, indel or SV """ ref, alt = str(ref_alt_bases[0]), str(ref_alt_bases[-1]) len_diff = len(ref) - len(alt) if ref == alt: return 'ref' # Ord...
def split_infiles(infiles): """ breaks the infile string with space-delimited file names and creates a list """ infileList = infiles.strip("\'").strip('\"').split(" ") if len(infileList) == 1: infileList = infileList[0].split(";") return(infileList)
def reverseStringv1(a_string): """assumes a_string is a string returns a string, the reverse of a_string""" return a_string[::-1]
def open_port_filter(result): """ Returns true if the specified result tuple is for an open port. :param result: The result tuple (host, port, is_open) :return: True or False depending on the is_open flag """ _, _, is_open = result return is_open
def get_hdfs_upload_path(biz_id, file_name): """ /data/{biz_id}/{file_name}/{id}.data """ return "/data/{}/{}/".format(biz_id, file_name)
def num_numeric_chars(free_text): """ returns number of numeric "words" (i.e., digits that are surrounded by spaces) """ num_numeric_words = len( [free_text for free_text in free_text.split() if free_text.isdigit()] ) return num_numeric_words
def comparison_pre_validation_checks( workflow_config_dict, wf_key, command_name): """ Checks if provided workflow is correct for commands which need to compare samples """ file = '' file = workflow_config_dict[wf_key][command_name][0] if len(file) > 0: if fi...
def encode_whitespace(text): """ Encode whitespace so that web browsers properly render it. :param text: The plain text (a string). :returns: The text converted to HTML (a string). The purpose of this function is to encode whitespace in such a way that web browsers render the same whitespace r...
def model_get_kwargs(feature): """ Get AvailableProperty get() kwargs--useful for get_or_create()--for the given feature. """ return { 'asset_id': feature['attributes']['ASSET_ID'], }
def field_values_valid(field_values): """ Loop over a list of values and make sure they aren't empty. If all values are legit, return True, otherwise False. :param field_values: A list of field values to validate. :returns: False if any field values are None or "", True otherwise. """ for ...
def has_v10_header(password_bytes: bytes) -> bool: """ Checks whether or not chrome password has v10 header """ return password_bytes[:3].decode() == "v10"
def get_scanner_pos(counter, depth): """Get the index of scanner, given the counter time and layer depth.""" remainder = counter / 2 * (depth - 1) if remainder > depth: return 2 * depth - remainder return remainder
def int_to_roman(input): """ Convert an integer to Roman numerals. Examples: >>> int_to_roman(0) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(-1) Traceback (most recent call last): ValueError: Argument must be between 1 and 3...
def _isbn_has_valid_checksum(identifier): """Determine whether the given ISBN has a valid checksum.""" if len(identifier) == 10: identifier = '978' + identifier numerals = [int(char) for char in identifier] checksum = 0 for i, numeral in enumerate(numerals): weight = 1 if i % 2 == 0...
def is_useless_dim(line): """ See if we can skip this Dim statement and still successfully emulate. We only use Byte type information when emulating. """ # Is this dimming a Byte variable? line = line.strip() if (not line.startswith("Dim ")): return False return (("Byte" not in ...
def reverse_items(items): """Reverse the sequence of items.""" return ''.join(reversed(items))
def camelcase(sentence): """ Convert sentence to camelCase, for example, "Display all books" is converted to "displayAllBooks" """ title_case = sentence.title() # Uppercase first letter of each word upper_camel_cased = title_case.replace(' ', '') # remove spaces # Lowercase first letter, join with rest of...
def valid_agreement(s): """Is this a valid "agreement" value?""" return s in ['institution', 'individual', 'none']
def uncapitalize(string: str): """De-capitalize first character of string E.g. 'How is Michael doing?' -> 'how is Michael doing?' """ if len(string): return string[0].lower() + string[1:] return ""
def model_path_to_test_name(model_path): """Generates string for test name from model path. Args: model_path: model path. """ # Remove .tflite extension. tmp = model_path.split(".tflite")[0] return tmp.replace(".", "_").replace("/", "_").replace("-", "_")
def is_prime(n): """ What comes in: An integer n >= 2. What goes out: -- Returns True if the given integer is prime, else returns False. Side effects: None. Examples: -- is_prime(11) returns True -- is_prime(12) returns False -- is_prime(2) returns True No...
def decode_erd_int(value: str) -> int: """Decode an integer value sent as a hex encoded string.""" return int(value, 16)
def discrete_3d(x, y, z): """Compute c * x * y where c = 0.1 if z == "small" else 0.15. `x` and `y` are discrete numerical values, z is categorical. Args: x: int, discrete variable (1, 2, 3, 4) y: int, discrete variable (-3, 2, 5) ...
def consecutive_words_score(n_gram_reference_repeated_list, n_gram_output_repeated_list): """ Returns a score for the bi-grams that are consecutive words """ score = [0 for _ in range(len(n_gram_output_repeated_list))] found = 0 for index, (list1, list2) in enumerate(zip(n_gram_output_repeated_li...
def phone_str_to_dd_format(phone_str): """ :param str phone_str: :returns: `str` -- """ if len(phone_str) != 10: return phone_str return '({}) {}-{}'.format(phone_str[:3], phone_str[3:6], phone_str[6:])
def _is_pdb_regex(pdb_regex): """Check if provided file is a pdb regex.""" return '*' in pdb_regex
def is_scalar_shape(shape): """Determines if a shape is scalar. """ if shape == (): return True return False
def prot_comp_composite(row): """Creates a composite column from the protein and compound IDs""" composi = row["DeepAffinity Compound ID"] + "," + row["DeepAffinity Protein ID"] return composi
def shorten_unique(names, keep_first=4, keep_last=4): """ Shorten strings, inserting '(...)', while keeping them unique. Parameters ---------- names: List[str] list of strings to be shortened keep_first: int always keep the first N letters keep_last: int always keep ...
def remove_first2(alist,k): """Removes the first occurrence of k from alist.""" retval = [] for x in range(0,len(alist)): # Here we use range instead of iterating the list itself # We need the current index to get the rest of the list # once one occurrence of k is removed. if alist[x] == k: retval.exten...
def num_sevens(n): """Returns the number of times 7 appears as a digit of n. >>> num_sevens(3) 0 >>> num_sevens(7) 1 >>> num_sevens(7777777) 7 >>> num_sevens(2637) 1 >>> num_sevens(76370) 2 >>> num_sevens(12345) 0 >>> from construct_check import check >>> # b...