content
stringlengths
42
6.51k
def clear_tables(data): """ Function clears table if rows are not valid (dasen't hold jumper data). :param data: raw data from the pdf tables :return: cleared raw data """ table_raw_content_list = [] # clean rows for pdfs with tables data_to_skip = ['Jury', 'RACE', 'Club', 'Rank', 'Nam...
def get_total_price_of_items(pizzas, kebabs, drinks): """Calculates and returns the total price of items provided. arguments: pizzas - list of pizzas kebabs - list of kebabs drinks - list of drinks """ total = 0.0 for p in pizzas: total += float(p.price_without_dollar_sign()) ...
def format_status(items, symbol_success='success', symbol_failed='failed'): """Format the status field of pipeline jobs.""" result = {} for name, content in items.items(): result[name] = content if content['status'] == 'success': result[name]['status'] = symbol_success if...
def e_s(msg): """Return a string, with reserved characters escaped""" msg = msg.replace(".", "\\.") msg = msg.replace("=", "\\=") msg = msg.replace("-", "\\-") msg = msg.replace("(", "\\(") msg = msg.replace(")", "\\)") msg = msg.replace("]", "\\]") msg = msg.replace("!", "\\!") retu...
def curies_runtime(base): """ base is .e.g https://api.blackfynn.io/datasets/{dataset_id}/ """ return { 'local': base, 'contributor': base + 'contributors/', 'subject': base + 'subjects/', 'sample': base + 'samples/', }
def mean(data): """Compute the mean of the provided data.""" n = len(data) try: return [float(sum(l))/len(l) for l in zip(*data)] except TypeError: return sum(data)/n
def get_link_type(link: str) -> str: """ Analyzes the given link and returns the type of download type required. (track for individual song, album for an album URL and playlist if given a the Spotify link of a playlist). """ # a spotify link is in the form of: open.spotify.com/<type>/<id> #...
def discrete_uniform_expval(lower, upper): """ Expected value of discrete_uniform distribution. """ return (upper - lower) / 2.
def is_set(object): """Check the given object is a set""" return isinstance(object, set)
def clean_exchanges(data): """Make sure all exchange inputs are tuples, not lists.""" def tupleize(value): for exc in value.get("exchanges", []): exc["input"] = tuple(exc["input"]) return value return {key: tupleize(value) for key, value in data.items()}
def text_to_title(value): """when a title is required, generate one from the value""" title = None if not value: return title words = value.split(" ") keep_words = [] for word in words: if word.endswith(".") or word.endswith(":"): keep_words.append(word) i...
def billions(x, pos): """The two args are the value and tick position.""" return '${:1.0f}B'.format(x*1e-9)
def get_identifier(recipe): """Return identifier from recipe dict. Tries the Identifier top-level key and falls back to the legacy key location.""" try: return recipe["Identifier"] except (KeyError, AttributeError): try: return recipe["Input"]["IDENTIFIER"] except (Ke...
def to_solution(parameters, columns): """Convert a solution given as a list pairs of column indices and values to a solution given as a list of pairs of columns and values.""" return [(parameters.columns[column_id], value) for column_id, value in columns]
def map_schema(line, schema): """ cleans the message msg, leaving only the fields given by schema, and casts the appropriate types returns None if unable to parse :type line : str message to parse :type schema: dict schema that contains the fields to filter :rtype : dict me...
def text_to_sentences(text, terminators = (".", "?", "!", '."', '?"', '!"'), exclude = ("Mr.", "Ms.", "Mrs.", "Dr.", "e.g.", "i.e.")): """ Break text into a list of sentences. This is a highly imperfect function that takes a passage of text and breaks it into a list of sentences. The main stumbling...
def div(numer, denom): """PFA division behavior: inf and -inf for a finite number divided by zero and nan for 0/0. Also ensures that return type of any two numbers (including integers) is floating point. :type numer: number :param numer: the numerator :type denom: number :param denom: the deno...
def min_max_indexes(seq): """ Uses enumerate, max, and min to return the indices of the values in a list with the maximum and minimum value: """ l = sorted(enumerate(seq), key=lambda s: s[1]) return l[0][0], l[-1][0]
def _build_pure_transition_impl(settings, attr): """ Transition that enables pure, static build of Go binaries. """ return { "@io_bazel_rules_go//go/config:pure": True, "@io_bazel_rules_go//go/config:static": True, }
def av_good_mock(url, request): """ Mock for availability, best case. """ return {'status_code': 301, 'text': 'Light side'}
def upsample_kernel_size_solver( in_size, out_size, stride=1, padding=0, output_padding=0, dilation=1, ): """ Returns kernel size needed to upsample a tensor of some input size to a desired output size. The implementation solves for kernel size in the equation described the the "Shape" section ...
def addr_to_text(mac_addr, big_endian=False, sep=""): """Convert a mac_addr in bytes to text.""" return sep.join(["{:02x}".format(b) for b in (mac_addr if big_endian else reversed(mac_addr))])
def get_core_identifier(cpu_identifier, sensor_identifier): """ a cpu has many sensors. some of them for cores. cores themselves don't have identifiers. thus, we use the identifier of the sensor to infer to which core it belongs. :param cpu_identifier: e.g. /intelcpu/0 :param sensor_identifier: e....
def parse_bool(value): """Attempt to parse a boolean value.""" if value in ("true", "True", "yes", "1", "on"): return True if value in ("false", "False", "None", "no", "0", "off"): return False return bool(int(value))
def convert_values_to_string(variables): """ Converts the values in the dictionary to the string type. :param variables: the variables dictionary :rtype: dict[str, object] :return: the variables dictionary with string values :rtype: dict[str, str] """ if not variables: return {...
def chunk(arr:list, size:int=1) -> list: """ This function takes a list and divides it into sublists of size equal to size. Args: arr ( list ) : list to split size ( int, optional ) : chunk size. Defaults to 1 Return: list : A new list containing the chunks of the original ...
def parseVectors(nodes): """ Parses a list of nodes (inputs, outputs, regs, wires, etc.) and encodes them based on whether they are a bus like [127:0]sk, or a single bit value like [1234] or 'a'. Args: nodes (list(string)): list of nodes to parse Returns: dict(string : int): dictio...
def score(word): """ Calculate score for a word """ result = 0 for char in word.upper(): if char in "AEIOULNRST": result += 1 elif char in "DG": result += 2 elif char in "BCMP": result += 3 elif char in "FHVWY": res...
def get_symmetric_key(): """Returns symmetric key bytes 16 bytes that were randomly generated. Form a 128 bit key. """ symmetric_key = ( b'\x92\xcf\x1e\xd9\x54\xea\x30\x70\xd8\xc2\x48\xae\xc1\xc8\x72\xa3') return symmetric_key
def is_remove(list, object): """remove objects from a list using is equivalence instead of comparison equivalence""" result = [] for e in list: if object is not e: result.append(e) return result
def overlap(range1, range2): """ Checks whether two ranges (f.e. character offsets overlap) This snippet by Steven D'Aprano is from the forum of www.thescripts.com. Keyword arguments: range1 -- a tuple where range1[0] <= range1[1] range1 -- a tuple where range2[0] <= range2[1] ...
def build_history_object(metrics): """ Builds history object """ history = {"batchwise": {}, "epochwise": {}} for matrix in metrics: history["batchwise"][f"training_{matrix}"] = [] history["batchwise"][f"validation_{matrix}"] = [] history["epochwise"][f"training_{matrix}"] =...
def has_straight(h): """ Straight: All cards are consecutive values. return: (hand value, remaining cards) or None """ values = {value for value, _ in h} if len(values) == 5 and max(values) - min(values) == 4: return max(values), [] else: return None
def float_fraction(trainpct): """ Float bounded between 0.0 and 1.0 """ try: f = float(trainpct) except ValueError: raise Exception("Fraction must be a float") if f < 0.0 or f > 1.0: raise Exception("Argument should be a fraction! Must be <= 1.0 and >= 0.0") return f
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' return 'color: %s' % color
def mapset(mapping, oldset): """ Applies a mapping to a set. Args: mapping: oldset (set): Returns: """ newset = set() for e in oldset: newset.add(mapping[e]) return newset
def _estimate_correlation_length(bins, averages): """Estimate the correlation length of a spatial velocity correlation function. The correlation length is typically defined as the radial distance at which the correlation first becomes zero. """ n_point = len(bins) for i in range(0, n_point-1): ...
def bound_ros_command(bounds, ros_pos, fail_out_of_range_goal, clip_ros_tolerance=1e-3): """Clip the command with clip_ros_tolerance, instead of invalidating it, if it is close enough to the valid ranges. """ if ros_pos < bounds[0]: if fail_out_of_range_goal: return bounds[0] if (bou...
def percents_to_pixels(image_width, image_height, row_percent, col_percent, width_percent, height_percent): """ Convert from percents of image to pixel values Args: image_width: image_height: row_percent: col_percent: width_percent: height_percent: Return...
def strip_position(pos): """ Stripes position from +- and blankspaces. """ pos = str(pos) return pos.strip(' +-').replace(' ', '')
def get_texture_declaration(texture): """Return the GLSL texture declaration.""" declaration = "uniform sampler%dD %s;\n" % (texture["ndim"], texture["name"]) return declaration
def add_trailing_slash(directory_path): """ Add trailing slash if one is not already present. Argument: directory_path -- path to which trailing slash should be confirmed. """ # Add trailing slash. if directory_path[-1] != '/': directory_path=str().join([directory_path, '/']) ...
def h3(text): """Heading 3. Args: text (str): text to make heading 3. Returns: str: heading 3 text. """ return '### ' + text + '\r\n'
def change_key_in_dict(d, old_key, new_key): """Change the key of the entry in `d` with key `old_key` to `new_key`. If there is an existing entry Returns: The modified dict `d`. Raises: KeyError : If `old_key` is not in `d`. """ d[new_key] = d.pop(old_key) return d
def get_min_rooms(lectures): """ Given an array of start and end times for lectures, find the minimum number of classrooms necessary. """ starts = sorted(start for start, _ in lectures) ends = sorted(end for _, end in lectures) num_rooms = 0 current_overlap = 0 start_idx, end_idx = ...
def find_active_firmware(sector): """Returns a tuple of the active firmware's configuration""" for i in range(8): app_entry = sector[i * 32 : i * 32 + 32] config_flags = int.from_bytes(app_entry[0:4], "big") active = config_flags & 0b1 == 0b1 if not active: continue ...
def f_exists(fname): """ checks if a file exists :param fname: :return: """ try: with open(fname) as f: return True except IOError: return False
def shorten_name(name, max_length = 10): """ Makes a string shorter, leaving only certain quantity of the last characters, preceded by '...'. @param name: The string to shorten. @param max_length: Maximum length of the resulting string. @return: A string with max_lenght characters plus '...' "...
def perlin_noise_1d(count, seed, octaves, bias): """ Return a noise 1d array """ perlin_noise = [0.0] * count for x in range(count): noise = 0.0 scale = 1.0 scale_accumulate = 0.0 for o in range(octaves): n_pitch = count >> o if n_pitch == 0: ...
def multi_gpu_load_single_gpu_model(checkpoint): """ Use the single gpu trained model in multi gpus. """ new_state_dict = {} for k, v in checkpoint.items(): # remove prefix 'module'. name = 'module.' + k new_state_dict[name] = v # Use 'load_state_dict' to load parameters. return new_state_dict
def add_sequences(seq1: list, seq2: list): """ A function to add two sequences and return the result seq1: A list of integers seq2: A list of integers returns: seq1 + seq2 as a list """ if len(seq1) == len(seq2): return [x + y for x, y in zip(seq1, seq2)] elif len(seq1) == 0 or l...
def wrappable_range_overlaps(start, end, test, wrap_after=59, wrap_to=0, overlap=False ): """Figure out whether a range of numbers (specified by 'start' and 'end') has any overlap with the set of numbers in the set 'test'. ...
def check_lammps_sim(out_file, verbose=True): """ Check if LAMMPS simulation is finished. """ FINISHED = False try: with open(out_file, 'r') as f: lines = f.readlines() if 'Total wall time' in lines[-1]: FINISHED = True except Exception as e: if ve...
def _tf(word_occured_in_doc: int, total_words_in_doc: int) -> float: """Term frequency of a word in certain document. See: https://bit.ly/3zEDkMn """ assert word_occured_in_doc <= total_words_in_doc return word_occured_in_doc / total_words_in_doc
def getid(obj): """Extracts object ID. Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
def call_req(obj_name, method, params): """Construct message used when sending API calls to CtrlServer. :param obj_name: Name of API-exported system that owns the given method. :type obj_name: string :param method: API-exported method to call on the given object. :type method: string :param par...
def subtract(v1, v2): """ Subtracts v2 from v1. """ return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]]
def divide(intf, ints): """ overpython.divide(intf, ints) Divide intf by ints. Raises ValueError if intf/ints is a string. """ try: return float(intf) / float(ints) except ValueError: raise ValueError("%s/%s is not a number" % (intf, ints))
def parse_keqv_list(l): """Parse list of key=value strings where keys are not duplicated.""" parsed = {} for elt in l: k, v = elt.split('=', 1) if v[0] == '"' and v[-1] == '"': v = v[1:-1] parsed[k] = v return parsed
def dico_add(*dicos): """ dictionnaries addition, with (shallow) copy """ if len(dicos) == 0: return {} res = dicos[0].__class__() for dico in dicos: res.update(dico) return res
def hr_range_formatter(start, end, step): """Format a range (sequence) in a simple and human-readable format by specifying the range's starting number, ending number (inclusive), and step size. Parameters ---------- start, end, step : numeric Notes ----- If `start` and `end` are in...
def get_insert_many_query(table_name: str) -> str: """Build a SQL query to insert several RDF triples into a PostgreSQL table. Argument: Name of the SQL table in which the triples will be inserted. Returns: A prepared SQL query that can be executed with a list of tuples (subject, predicate, object). "...
def to_bytes(something, encoding='utf8'): """ cast string to bytes() like object, but for python2 support it's bytearray copy """ if isinstance(something, bytes): return something if isinstance(something, str): return something.encode(encoding) elif isinstance(something, byte...
def frequencies(seq): """ Find number of occurrences of each value in seq >>> frequencies(['cat', 'cat', 'ox', 'pig', 'pig', 'cat']) #doctest: +SKIP {'cat': 3, 'ox': 1, 'pig': 2} See Also: countby groupby """ d = dict() for item in seq: try: d[item] += ...
def cage_correlations_summing(target_species_hit, transcript_id, target_cages, tf_cages, cage_correlations_dict, cage_corr_weights_dict): """ Extract correlation values between CAGEs associated with a predicted TFBS protein, and CAGEs associated with the current gene. """ corr_weights_ls = [] c...
def func_extract_all_project_ids(project_version_mapping): """ :param project_version_mapping: :return: project id list """ ids = [] for _ in project_version_mapping.keys(): ids.append(_.id) return ids
def uniq_arr(arr): """Remove repeated values from an array and return new array.""" ret = [] for i in arr: if i not in ret: ret.append(i) return ret
def line_intersect(pt1, pt2, ptA, ptB): """ Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html Returns the intersection of Line(pt1,pt2) and Line(ptA,ptB). """ import math DET_TOLERANCE = 0.00000001 # the first line is pt1 + r*(pt2-pt1) # in component form: x1, y1 = ...
def merge_dict_recursive(base, other): """Merges the *other* dict into the *base* dict. If any value in other is itself a dict and the base also has a dict for the same key, merge these sub-dicts (and so on, recursively). >>> base = {'a': 1, 'b': {'c': 3}} >>> other = {'x': 4, 'b': {'y': 5}} >>> want =...
def tickets(people): """ Determines whether Vasya can sell a ticket to all people in the queue. :param people: an array integers ranging from numbers 25, 50, and 100. :return: YES, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Other...
def is_object(x): """Returns True if x has a __dict__ attribute. This function is intended to determine if its argument is an object in the "classic" sense--that is, one belonging to a type created by the "class" construct, and excluding such built-in types as int, str, and list, which are, strictl...
def cleanArrayForKey(lst): """ This method will clean out so that only the kh will contain 0,1,2,3,4,5,6,7 """ array = [] temp = [] for i, x in enumerate(lst): if x[1] == 0: temp = [i, x[1]] array.append(temp) elif x[1] == 1: temp = [i, x[1]] ...
def _esc_var(name): """Returns a valid and unique Python identifier derived from name. Just returns name with the "_" appended. This is enough to ensure there's no collisions with any keyword or built-in or import. Args: name (string): The name to escape. Returns: string: A name w...
def normalise(val, minimum, maximum): """ Normalise a value between two values :param val: value to normalise :param minimum: minimum boundary :param maximum: maximum boundary :return: value between 0 and 1 """ return (val - minimum) / float(maximum - minimum)
def bubblesort(l): """ Runtime: O(n^2) """ last = len(l)-1 for i in range(last): for j in range(i+1, last): if l[i] > l[j]: l[i], l[j] = l[j], l[i] return l
def join_dots(*inputs): """['123', '456', '789'] -> '123.456.789'""" return '.'.join([item for item in inputs])
def wallis_product(n_terms): """Implement the Wallis product to compute an approximation of pi. See: https://en.wikipedia.org/wiki/Wallis_product XXX : write Parameters and Returns sections as above. """ # XXX : The n_terms is an int that corresponds to the number of # terms in the produc...
def format_datetime(datetime_): """Convert datetime object to something JSON-serializable.""" if datetime_ is None: return None return datetime_.strftime('%Y-%m-%dT%H:%M:%SZ')
def disbursal(from_acc, amount, from_pass, bank): """ Withdraws a desired amount of money from a user's account If a user's account is verified, using the account name and password, the desired amount of money is withdrawn from the user's account. :param from_acc: user's account number :param amou...
def str2bool(x): """ Convert a string to a boolean. """ return x.lower() in ("true", "1")
def fill_space(s, i, j): """ Replace [i to j) slice in a string with empty space " "*len """ return s[:i] + " " * (j - i) + s[j:]
def make_spec(repos, slack_user_id, author_name): """ Format and return spec specifying what to analyze Convenience method: spec used by several other methods here Args: repos: list of repo names, which should have their logs jumped to json already in logs2hours/logs/git start_date: datetime st...
def first_missing_positive_naive(a): """ O(n) time and O(n) space. """ n = len(a) flag = [False]*n for x in a: if x < 1 or x > n: continue flag[x-1] = True for i, f in enumerate(flag): if not f: return i+1
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'firstact': ['install'], 's...
def djfrontend_h5bp_html(lang): """ Returns HTML tag according to chosen language. Included in HTML5 Boilerplate. """ output=[ '<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="%s"> <![endif]-->' % lang, '<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="%s"> <![e...
def tslash(apath): """Add a trailing slash to a path if it needs one. Doesn't use os.sep because you end up jiggered on windoze - when you want separators for URLs. """ if (apath and apath != '.' and not apath.endswith('/') and not apath.endswith('\\')):...
def escape_markdown(text: str): """ return text escaped given entity types :param text: text to escape :param entity_type: entities to escape :return: """ # de-escape and escape again to avoid double escaping return text.replace('\\*', '*').replace('\\`', '`').replace('\\_', '_')\ ...
def guess_index_name(name: str) -> str: """Guess index name for a preferred name. Naive calculation of "Family Name, Given Name" """ return ', '.join(list(reversed(name.split(maxsplit=1))))
def decode_cigar(cigar): """Return a list of 2-tuples, integer count and operator char.""" count = "" answer = [] for letter in cigar: if letter.isdigit(): count += letter # string addition elif letter in "MIDNSHP=X": answer.append((int(count), letter)) ...
def removePrefix(str, prefix): """Removes prefix of str.""" return str[len(prefix):] if str.startswith(prefix) else str
def naive_2mm(p, t): """Return a naive string match allowing up to 2 mismatches.""" occurrences = [] for i in range(len(t) - len(p) + 1): # loop over alignments match = True mismatch = 0 for j in range(len(p)): # loop over characters if t[i+j] != p[j]: # compare charac...
def basis_function_ders_one(degree, knot_vector, span, knot, order): """ Finds the derivative of one basis functions for a single knot. Implementation of Algorithm A2.5 from The NURBS Book by Piegl & Tiller. :param degree: degree :type degree: int :param knot_vector: knot_vector :type knot_vec...
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback): """ Build the feedback when an user has completed the quiz and has failed the quiz. :param actor_name: Name of the user that has completed the quiz. :type actor_name: str :param quiz_name: Name of the quiz....
def italReplacements(tex): """ Replace the Latex command "\\textit{<argument>}" with just argument """ while (tex.find("\\textit{") != -1): beg = tex.find("\\textit{") sbrace = tex.find("{", beg) ebrace = tex.find("}", sbrace) tex = tex[:beg] + tex[sbrace+1:ebrace...
def toFloat (str, default=None): """toFloat(str[, default]) -> float | default Converts the given string to a floating-point value. If the string could not be converted, default (None) is returned. NOTE: This method is *significantly* more effecient than toNumber() as it only attempts to parse fl...
def nest_toc_tokens(toc_list): """Given an unsorted list with errors and skips, return a nested one. [{'level': 1}, {'level': 2}] => [{'level': 1, 'children': [{'level': 2, 'children': []}]}] A wrong list is also converted: [{'level': 2}, {'level': 1}] => [{'level': 2, 'children': []}, ...
def ordinal(n): """If n is a cardinal, ordinal function will return it's ordinality""" return "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])
def argsparselist(txt): """ Validate a list of txt argument. :param txt: argument with comma separated int strings. :return: list of strings. """ txt = txt.split(",") listarg = [i.strip() for i in txt] return listarg
def tn_rate(TN, neg): """ Gets true positive rate. :param: TP: Number of true negatives :type TN: `int` :param: pos: Number of negative labels :type neg: `int` :return: true negative rate :rtype: `float` """ if neg == 0: return 0 else: return TN / neg
def possible_bipartition(dislikes): """ Will return True or False if the given graph can be bipartitioned without neighboring nodes put into the same partition. Time Complexity: O(n^2) Space Complexity: O(n) """ visited = [False] * len(dislikes) color = [-1] * len(dislike...