content
stringlengths
42
6.51k
def is_integer_literal(name): """Checks whether name is an integer literal string. Args: name: The identifier to check Returns: True if name is an integer literal, otherwise False """ result = True try: int(name) except ValueError: result = False return result
def init_naive_array(n): """ return a list that is n long """ result = list() for i in range(1, n+1): result.append(i) return result
def split_into_chunks(string, chunk_length=2): """Split string to chunks fixed length.""" chunks = [] while len(string) > 0: chunks.append(string[:chunk_length]) string = string[chunk_length:] return chunks
def str_to_ascii_upper_case(s): """Converts the ASCII characters in the given string to upper case.""" return ''.join([c.upper() if 'a' <= c <= 'z' else c for c in s])
def __tqdmlog__(x_input, log): """ Private function for dealing with logging :param x_input: any iterable object :param log: bool, if True and module tqdm exists use logging :return: """ # deal with importing tqdm try: from tqdm import tqdm except ModuleNotFoundError: ...
def atom_frac_cols(fracs): """Return columns corresponding to the average atom fraction :fracs: list str :returns: list str """ return ["<atom_frac({})>".format(f) for f in fracs]
def normalize_mapping(mapping): """ Normalizes the mapping definitions so that the outputs are consistent with the parameters - "name" (parameter) == "id" (SDK) """ if mapping is None: return None _mapping = mapping.to_dict() _mapping['name'] = mapping['id'] return _mapping
def _is_begin_bulk(line_upper: str) -> bool: """ is this a: 'BEGIN BULK' but not: 'BEGIN BULK SUPER=2' 'BEGIN BULK AUXMODEL=2' 'BEGIN BULK AFPM=2' """ is_begin_bulk = 'BULK' in line_upper and ( 'AUXMODEL' not in line_upper and 'AFPM' not in line_upper and ...
def file_duration_parser(line): """ Parses lines of the following form: extracts only the seconds part File duration: 5248.68s (100.00%) :param line: string :return: float containing the duration for the file in seconds """ line = line[len('File duration:'):] ie = line.find('s') ...
def val_checker(val): """Type check of variable to pass to style functions. Parameters ---------- val : str String containing the value to evaluate Returns ------- val : Recasted value """ from distutils.util import strtobool if "'" not in val and '"' not in val: try: val=float(val) if '.' in va...
def find_parent_classes_recursively(cls): """Finds all parent classes recursively with any inheritance structure and omits duplicates""" all_parent_classes=[] base_classes=cls.__bases__ for base_class in base_classes: if base_class not in all_parent_classes: all_parent_classes.append...
def is_even(number: int) -> bool: """ Info: Check if a number is even, if so return True if not return False Paramaters: number: int - The number to check if is even. Usage: is_even(number) Returns: bool """ return number % 2 == 0
def substrings(txt, min_length, max_length, pad=''): """ >>> substrings("abc", 1, 100) ['a', 'ab', 'abc', 'b', 'bc', 'c'] >>> substrings("abc", 2, 100) ['ab', 'abc', 'bc'] >>> substrings("abc", 1, 2) ['a', 'ab', 'b', 'bc', 'c'] >>> substrings("abc", 1, 3, '$') ['$a', 'a', '$ab', 'ab'...
def is_unit(char): """ Verifies whether the character given is a "unit" (meaning it is a regex command (by opposition to an operator)). """ assert len(char) == 1 return char.isalpha() or char.isnumeric() or char in ['.', ' ', '-']
def get_publish_token(package_name: str): """ parses the package_name into the name of the token to publish the package. Example: @google-cloud/storage => google-cloud-storage-npm-token dialogflow => dialogflow-npm-token Args: package: Name of the npm package. Returns: ...
def quote_identifier(identifier, sql_mode=""): """Quote the given identifier with backticks, converting backticks (`) in the identifier name with the correct escape sequence (``) unless the identifier is quoted (") as in sql_mode set to ANSI_QUOTES. Args: identifier (str): Identifier to quote. ...
def tex(text, env=None): """Create html code for any object with a string representation Parameters ---------- text : any Object to be converted to HTML. If the object has a ``.get_html()`` method the result of this method is returned, otherwise ``str(text)``. env : dict Env...
def ScalarFunc(val): """ Manipulate the scalar (z-axis) values Accepts and returns a double """ if val >= 0.0: return 60.0 else: return val
def _dispense_tokens(size, total): """ >>> _dispense_tokens(3, 0) [] >>> _dispense_tokens(3, 1) [1] >>> _dispense_tokens(3, 3) [3] >>> _dispense_tokens(3, 4) [3, 1] """ return [min(i, size) for i in range(total, 0, -size)]
def pattern(vals: list) -> str: """ Return a regex string from a list of values """ return f"^({'|'.join(map(str, vals))})$"
def iobes_to_iob2(tags): """ IOBES -> IOB2 """ new_tags = [] for i, tag in enumerate(tags): if tag.split('-')[0] == 'B': new_tags.append(tag) elif tag.split('-')[0] == 'I': new_tags.append(tag) elif tag.split('-')[0] == 'S': new_tags.append...
def argmaxIndex(l, f = lambda x: x): """ @param l: C{List} of items @param f: C{Procedure} that maps an item into a numeric score @returns: the index of C{l} that has the highest score """ best = 0; bestScore = f(l[best]) for i in range(len(l)): xScore = f(l[i]) if xScore > b...
def removeExtension( stringName ): """ removes the .123 extension from a string and returns this string """ return stringName[0:-4]
def selectSort(nums): """ Original version :type nums:list[int] numRange:int :rtype list[int] """ res = list(nums) for i in range(len(res)): minIndex = i for j in range(i + 1, len(res)): if res[j] < res[minIndex]: minIndex = j res[i], res[m...
def _multi_bleu(hypothesis, reference_set, aligner): """ Compute a list of scores with the aligner. :param hypothesis: a single hypothesis. :param reference_set: a reference set. :param aligner: a callable to compute the semantic similarity of a hypothesis and a list of references. :return:...
def true_if_hello(x): """Will return true if and only if passed the str 'hello' >>> true_if_hello('hello') True >>> true_if_hello('olleh') False >>> true_if_hello(7) False """ x = str(x) if x == 'hello': return True ...
def noneorstr(s): """Turn empty or 'none' string to None.""" if s.lower() in ("", "none"): return None else: return s
def double_eights(n): """Determine if the input integer, n, contains two eight numbers consecutively Args: n (int): input integer >= 0 Returns: (bool): True if two consecutive B is detected in n, returns False, otherwise Raises: ValueError: if n is negative TypeError: ...
def scale(value, start_min, start_max, end_min, end_max): """Returns the result of scaling value from the range [start_min, start_max] to [end_min, end_max]. """ return (end_min + (end_max - end_min) * (value - start_min) / (start_max - start_min))
def rot_pattern(pattern, deg): """Rotate a pattern 90, 180, or 270 degrees""" newpattern = pattern[:] if deg in [90, 180, 270]: for i in range(deg//90): newpattern_tup = zip(*list(reversed(newpattern))) newpattern = ["".join(j) for j in newpattern_tup] return newpattern
def measure_difference(element_i, element_j, pars={}): """ Parameters ---------- element_i: float or np.ndarray the spatial information of the element `i`. element_j: float or np.ndarray the spatial information of the element `j`. pars: dict the parameters of the measure...
def get_tendancy_curve(x_values, y_values): """Returns the tendancy curve of a set of points of coords x_values[n], y_values[n]""" n = len(x_values) try: a = (sum(x * y for x, y in zip(x_values, y_values)) - (sum(x_values) * sum(y_values) / n)) / ( sum(x ** 2 for x in x_values) - (s...
def convert_string_to_list(string_val): """Helper function to convert string to list. Used to convert shape attribute string to list format. """ result_list = [] list_string = string_val.split(',') for val in list_string: val = str(val.strip()) val = val.replace("(", "") ...
def generate_netacl(source, default=[]): """ Generates IP ACL Doesn't work with IPv6 Args: source: string with IP/network or iterable default: returns if source is empty """ if source: from netaddr import IPNetwork return [ IPNetwork(h) f...
def bitfield_max(msb, lsb=None): """Return the largest value that fits in the bitfield [msb:lsb] (or [msb] if lsb is None)""" if lsb is None: lsb = msb return (1 << (msb - lsb + 1)) - 1
def multilinify(sequence, sep=","): """Make a multi-line string out of a sequence of strings.""" sep += "\n" return "\n" + sep.join(sequence)
def ivar_filter(pass_test): """ Description: process ivar filter into vcf filter format. input: pass_test - ivar fisher exact test [ True, False ] return: Whether it passes the filter or not. [False, "ft"] """ if pass_test == "TRUE": return False else: ...
def dna_to_binary_string(seq): """Encodes the given DNA sequence to binary encoding (2 bits per nt). The last letter of the sequence is encoded in the 2 least significant bits. """ DNA_CODES = { ord(b'A'): 0b00, ord(b'C'): 0b01, ord(b'G'): 0b10, ord(b'T'): 0b11 } ...
def get_schema_entities(schema): """Gets the schema entities (column and table names) for a schema.""" names = set() for table_name, cols in schema.items(): names.add(table_name.lower().replace('_', ' ')) for col in cols: names.add(col['field name'].lower().replace('_', ' ')) return names
def decolonize(val): """Remove the colon at the end of the word This will be used by the unique word of template class to sanitize attr accesses """ return val.strip(":")
def strip_code_markup(content: str) -> str: """ Strips code markup from a string. """ # ```py # code # ``` if content.startswith("```") and content.endswith("```"): # grab the lines in the middle return "\n".join(content.split("\n")[1:-1]) # `code` return content.strip("` \n")
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration...
def rst_link_filter(text, url): """Jinja2 filter creating RST link >>> rst_link_filter("bla", "https://somewhere") "`bla <https://somewhere>`_" """ if url: return "`{} <{}>`_".format(text, url) return text
def get_graph_last_edge(g): """ Get the last edge of the graph or an empty edge if there is non :param g: a graph as a dictionary :return: an edge as a dictionary """ return g["edgeSet"][-1] if 'edgeSet' in g and g["edgeSet"] else {}
def SelectDefaultBrowser(possible_browsers): """Returns the newest possible browser.""" if not possible_browsers: return None return max(possible_browsers, key=lambda b: b.last_modification_time())
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = "red" if val < 0 else "black" return "color: %s" % color
def check_int_list_param(value): """ This method parse a string into a list. Args: value (uniode): The list to parse. Returns: (list): The parsed list. """ tab = value.split(u",") if not tab: return False return [int(item) for item in tab]
def split_path(path): """ Normalise S3 path string into bucket and key. Parameters ---------- path : string Input path, like `s3://mybucket/path/to/file` Examples -------- >>> split_path("s3://mybucket/path/to/file") ['mybucket', 'path/to/file'] """ if path.startswi...
def rotate_right(byte): """ Rotate bits right. """ byte &= 0xFF bit = byte & 0x01 byte >>= 1 if(bit): byte |= 0x80 return byte
def unique(string): """ Algorithm to determine if a string's characters are all unique :param string: input string (ASCII character set) :return: Boolean """ # Special Case, cannot be greater than 128 characters if len(string) > 128: return False # Set up "Empty" list for observ...
def is_strobogrammatic(num): """ :type num: str :rtype: bool """ comb = "00 11 88 69 96" i = 0 j = len(num) - 1 while i <= j: if comb.find(num[i]+num[j]) == -1: return False i += 1 j -= 1 return True
def eval_operand(expr, pos=0): """ >>> eval_operand(EX1) (1, 1) >>> eval_operand(EX1[19:]) (6, 2) >>> eval_operand(EX6) ('(2 + 4 * 9) * (6 + 9 * 8 + 6) + 6', 35) >>> eval_operand(EX6, 1) ('2 + 4 * 9', 12) >>> eval_operand(" 36 ") (36, 4) >>> """ while expr[pos]...
def spacer(text, times, char="\u2000"): """Prepends a specified number of the char value to the text. Handy for neatly appending special space characters two or three times.""" return char * times + text
def _create_trip_from_stack(temp_trip_stack, origin_activity, destination_activity, trip_id_counter): """ Aggregate information of trip elements in a structured dictionary Parameters ---------- temp_trip_stack : list list of dictionary like elements (either pandas series or pyth...
def _filter_partial_matches(diffs, partial_diffs_to_exclude): """Filter out diffs that match a subset of attributes :type partial_diffs_to_exclude: dict([(attr, value)...]) """ def _partial_match(diff): for partial in partial_diffs_to_exclude: if all(getattr(diff, attr) == val for at...
def filter_keys(obj, keys): """Filter a dictionary by keys. Args: obj (dict): The dictionary to filter. Returns: obj (dict): The filtered dict. """ if obj is None or not isinstance(keys, list): return obj newdict = {} for k, v in list(obj.items()): if k in k...
def get_broker_signup_button(burl, broker): """ xxx """ return_data = '' l_button = 'Signup with '+ str(broker) button_signup = '<a href="'+\ burl+'join/?broker='+\ str(broker) +'" class="btn btn-success" style="font-size:small;">'+\ l_button +'</a>' return_data = button_signup ret...
def change(_port, prop, _value): """Change a property of a package,""" if prop == "explicit": return False else: assert not "unknown package property '%s'" % prop
def pitch2hz(p, beta=12, ref_frq=440.0): """Convert pitch to frequency. Parameters ---------- p : np.ndarray, float midi pitch beta : int equal divisions of the octave ref_frq : float, optional Description Returns ------- frq : np.ndarray, float freq...
def merge_adjacent_intervals(intervals): """ >>> merge_adjacent_intervals([(1, 3), (4, 5)]) [(1, 3), (4, 5)] >>> merge_adjacent_intervals([(1, 4), (4, 5)]) [(1, 5)] >>> merge_adjacent_intervals([(1, 2), (2, 5), (5, 7)]) [(1, 7)] >>> merge_adjacent_intervals([(1, 2), (2, 5), (5, 7), (8, 9...
def convert_datastores_to_hubs(pbm_client_factory, datastores): """Convert Datastore morefs to PbmPlacementHub morefs. :param pbm_client_factory: pbm client factory :param datastores: list of datastore morefs :returns: list of PbmPlacementHub morefs """ hubs = [] for ds in datastores: ...
def interface_has_mirror_config(mirror_table, interface_name): """ Check if port is already configured with mirror config """ for _, v in mirror_table.items(): if 'src_port' in v and v['src_port'] == interface_name: return True if 'dst_port' in v and v['dst_port'] == interface_name: ...
def compare_headers(headers): """This function compares two HTTP headers to ensure they are the same. .. versionadded:: 2.7.4 """ control_dict = { 'content-type': 'application/json', 'accept': 'application/json', 'some-list': ['something', 'something-else'], 'some-intege...
def normalize_comment(comment: str) -> str: """ Normalize a comment. It does the following: * uncheck checked boxes """ fixed = comment.replace("[x]", "[ ]") return fixed
def extract_http_req_body(contents): """ Splits the HTTP request by new lines and gets the last line which is the HTTP payload body """ return contents.split(b"\n")[-1]
def tokenize (text): """ Tokenizes a text sample. Args: text (str): The text sample Returns: list of str: A list of tokens """ replacements = ["\r", "\n", "\t"] output = text for replacement in replacements: output = output.replace(replacement, " ") # Convert whitespace to spaces only. return list(filter(...
def inc_avg(li): """ Calculate the average incrementally. Input: a list. Output: average of the list. See http://ubuntuincident.wordpress.com/2012/04/25/calculating-the-average-incrementally/ . >>> inc_avg([2, 3, 4]) 3.0 """ left = 0 right = len(li) - 1 avg = li[left] l...
def _format_where(where, subj_variable, obj_variable=None): """ Format WHERE clauses, including replacing ?subj and ?obj with unique variable names. """ new_where = where.strip() new_where = new_where.replace("?subj", "?{}".format(subj_variable)) if obj_variable: new_where = new_wher...
def halve_grades(grades): """ Returns a copy of grades, cutting all of the exam grades in half. Parameter grades: The dictionary of student grades Precondition: grades has netids as keys, ints as values. """ # DICTIONARY COMPREHENSION #return { k:grades[k]//2 for k in grades } # ACCUMU...
def _diff_replication_group(current, desired): """ If you need to enhance what modify_replication_group() considers when deciding what is to be (or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used in modify_replication_group() to that in describe_replication_groups()...
def strip_PKCS7_padding(val): """ Function to strip off PKCS7 padding. """ if len(val) % 16 or not val: raise ValueError("String of len %d can't be PCKS7-padded" % len(val)) numpads = val[-1] if numpads > 16: raise ValueError("String ending with %r can't be PCKS7-padded" % val[-1]) ...
def kappa_histogram(ratings, min_rating=None, max_rating=None): """ Returns the counts of each type of rating that a rater made """ if min_rating is None: min_rating = min(ratings) if max_rating is None: max_rating = max(ratings) num_ratings = int(max_rating - min_rating + 1) hist_ratings = [0 for x...
def in_notin(list1, list2): """Find entries in the first list that are not in the second list.""" set2 = set() for val in list2: set2.add(val) out_list = [] for val in list1: if val not in set2: out_list.append(val) return out_list
def is_anagram(word1, word2): """Receives two words and returns True/False (boolean) if word2 is an anagram of word1, ignore case and spacing. About anagrams: https://en.wikipedia.org/wiki/Anagram""" list1 = [letter for letter in word1.lower() if letter.isalnum()] list2 = [letter for lett...
def prepareCurveSignal(button, label, type_, xData, yData, x, y, xPixel, yPixel): """See Plot documentation for content of events""" return {'event': 'curveClicked', 'button': button, 'label': label, 'type': type_, 'xdata': xData, ...
def strip_lines(multi_line_string: str, strip_first_and_list_lines: bool = True) -> str: """ Strip leading and trailing whitespace from every line in the input string. :param multi_line_string: A string where some lines may or may not have leading or trailing whitespace :param strip_first_and_list_l...
def append_mod_to_sys(locs): """ Appends module directory/directories to sys.path Arguments: -- locs: string or list of strings. The absolute filepath/s to the module to be imported. """ import sys import os if type(locs) != list: locs = [locs] for i...
def get_clusters(preds): """ Convert {antecedent_id: mention_id} pairs into {mention_id: assigned_cluster_id} pairs. """ cluster_assignments = {} for id_cluster, cluster_starter in enumerate(preds.get(None, [])): stack = [cluster_starter] curr_cluster = [] while len(stack) > 0: ...
def mandatory_keys_check(list_mandatory, list_dict_keys): """ Check if the payload json file have the mandatory keys :param list_mandatory: list :param list_dict_keys: list :return True or False """ check = all(item in list_dict_keys for item in list_mandatory) return check
def compare(obj1, obj2): """ Compare 2 objects. Return True if they are equal and False otherwise. This code is really ugly, more elegant way to do that?? """ try: attributes_1 = sorted([x for x in obj1.class_trait_names()]) attributes_2 = sorted([x for x in obj2.cla...
def within_range(r, pos): """ Check if a given position is in window Args: r (tuple): window, ((int, int), (int, int)) in the form of ((x_low, x_up), (y_low, y_up)) pos (tuple): (int, int) in the form of (x, y) Returns: bool: True if `pos` is in `r`, False otherwise ...
def between(start: int, stop: int, step: int=1): """ Like ``range()``, but this INCLUDES the stop value. ``range`` produces results in the range [start, stop) ``between`` produces results in the range [start, stop] :param start: start value. :param stop: end value (inclusive). :param step:...
def is_child_node(node): """ Return `True` if the given node is a "child" node, `False` otherwise. """ if not node: return False return node.is_child is True and node.is_root is False
def get_input(text: str) -> str: """Get input (str) from user returns str""" try: value = int(text) if value < 0: return "" else: return str(value) except ValueError: return ""
def extract_rank_stats(stats): """ Extract the rank and number of plays of past days. **Parameters** - `stats`: list of rankStats for each track within charts, each element being a dictionary containing the ranks (and plays if available) of previous days ...
def _FormatTypeCheck(type_): """Pretty format of type check.""" if isinstance(type_, tuple): items = [_FormatTypeCheck(t) for t in type_] return "(%s)" % ", ".join(items) elif hasattr(type_, "__name__"): return type_.__name__ else: return repr(type_)
def validate_slots(slots : dict) -> dict: """ Validate slots Arguments: slots {dict} -- slots dictionary to be validate Returns: dict -- validated version """ #slots["ESMLFileTypes"] = to_validate_text(slots.get("ESMLFileTypes"), ["text", "image"]) return slots
def _args_or_none(arg): """Return None if the arg is 'None' or the arg.""" if arg == 'None': return None return arg
def load_geo_cache(cache_file): """ Returns a set of what's already in the cache as a state,city,location tuple. """ return { (c[0], c[1], c[2]) for c in cache_file }
def fib(n): """Assumes n int >= 0 Returns Fibonacci of n""" if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2)
def flatten(l): """Flatten an arbitrary list-of-lists into one flat list.""" return [item for sublist in l for item in sublist]
def get_attr_info_dict(name, dotted_path, admin_order_field, short_description): """ Returns a dict with keys named, dotted_path, admin_order_field, and short_description. """ return { 'name': name, 'dotted_path': dotted_path, 'admin_order_field': admin_order_field, 'shor...
def extract_window(x, past, now, future): """ Helper to split a time window """ return x[past:now], x[now:future]
def TypeOrNothing(dart_type, comment=None, nullable=False): """Returns string for declaring something with |dart_type| in a context where a type may be omitted. The string is empty or has a trailing space. """ nullability_operator = '?' if nullable else '' if dart_type == 'dynamic': if comment...
def brake_distance(speed, max_deaccel, delay, sim_step): """ Return the distance needed to come to a full stop if braking as hard as possible. Parameters ---------- speed : float ego speed max_deaccel : float maximum deaccel of the vehicle delay : float the ...
def _geom_sum(r, n): """Computes sum of geometric series. Use n=float('inf') for infinite series. """ return (1 - r**(n + 1)) / (1 - r)
def JDdiff(JD0, JD1): """Returns the number of seconds between two Julian dates.""" return (JD1 - JD0) * 86400
def auto_biographical(number) -> bool: """Check whether the entered number is auto_biographical number or not.""" number = str(number) if len(number) > 9: return False for i in range(len(number)): if(number.count(str(i)) != int(number[i])): return False return True
def separate_into_groups(dependency_relationships): """ Split into sorted logical groups. """ projects = list() projects_bad = list() packages = list() packages_bad = list() for dep in dependency_relationships: if dep.is_package: if dep.is_known: packages.appe...
def extract_passport_list(lines): """ Gets a list of passports from the input :param lines: input :return: list of passports """ passports = [] current_passport = {} for line in lines: if line == '\n': passports.append(current_passport) current_passport = {} ...