content
stringlengths
42
6.51k
def timsort_merge(left, right): """Takes two sorted lists and returns a single sorted list by comparing the elements one at a time. [1, 2, 3, 4, 5, 6] """ if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + timsort_merge(left[...
def checkFrameStatements(value): """ Check that frames statements list value proper. Must not be None, must not contain None, and of course only statements sequences, or statements, may be empty. """ assert value is not None assert None not in value for statement in value: assert ...
def normalized (string) : """Normalize a base32 encoded string.""" return string.upper ().replace ("-", "")
def gf2_rank(rows): """Find rank of a matrix over GF2 given as list of binary ints. From https://stackoverflow.com/questions/56856378 """ rank = 0 while rows: pivot_row = rows.pop() if pivot_row: rank += 1 lsb = pivot_row & -pivot_row for index, r...
def armstrong(num: int)->str: """ Function checks by getting the digits of the number and powering them to length of number, and adding together to compare if we are getting same number or not. Input: Integer Output: String (Sentence telling armstrong or not) """ n = 0 result = 0 cop...
def thermal_speed(temp, abar=1.0, spec='e'): """ Calculate the thermal speed for electrons or ions Parameters ---------- - temp [eV] - abar: mean atomic number - spec: species Returns ------- speed in cm/s Source: https://en.wikipedia.org/wiki/Plasma_parameters ""...
def linear_curve(t, a, b): """ fit data to linear model """ return a*t + b
def generate_entry(intents, actions, expected_actions, dialogues, kbs, boundaries1, boundaries2, i): """generate entry based on the available of data.""" # required fields entry = {'intent': intents[i], 'action': actions[i], 'kb': kbs[i]} # optional fields depending on the input type if dia...
def text_color(color): """Given a color, estimate if it's better to show block or white text on top of it. :param color: A string of six hex digits (RRGGBB) representing the background color :returns: A string of six hex digits (RRGGBB) representing the estimated text c...
def decapsulate(params): """ decapsulate VAD parameters """ flag = params['flag'] Eor = params['energy-original'] E = params['energy'] Cor = params['centroid-original'] C = params['centroid'] Te = params['threshold-energy'] Tc = params['threshold-centroid'] return flag, Eor, E, Cor, C, Te, Tc
def isHappy(n): """ Is happy takes in a number and returns True if it is a happy number, False otherwise. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number e...
def unescaper(msg): """ unescape message this function undoes any escape sequences in a received message """ out = [] escape = False for x in msg: if x == 0x5c: escape = True continue if escape: x = 0x5c ^ x ^ 0xa3 escape = False ...
def recall_k(actuals: list, candidates: list, k: int) -> float: """ Return the recall at k given a list of actuals and an ordered list of candidates """ if len(candidates) > k: candidates = candidates[:k] return len(set(actuals).intersection(candidates)) / len(actuals)
def well_row_name(x): """Return a well row name for the given zero-based index""" if x < 26: return chr(ord("A") + x) return chr(ord("A") + int(x / 26) - 1) + chr(ord("A") + x % 26)
def choose_layer_style(n_clicks): """ This function takes as input the number of clicks on the button defined above and returns: - the appropriate message for the button (changed at each click); - the background layer style to use (URL and attribution). """ # Because we start with the topograp...
def _parse_address(address): """Parse a colon-separted address string into constituent parts. Given a string like ``foo:1234`` this will split it into a tuple containing ``foo`` and ``1234``, where ``1234`` is an integer. If the port is not given in the address string then it will default to 27015....
def multibyte_truncate(string, byte_length, encoding='utf-8'): """Truncate a multi-byte encoded string to a given maximal byte size. Parameters ---------- string : str The string to truncate. byte_length : int The length in bytes to truncate to. encoding : str, optional ...
def _flatten_to_dict(list_of_facets): """ Simple helper that flattens the solr facet into a dict. """ facet = {'sort': []} for i in range(0, len(list_of_facets), 2): facet['sort'].append(list_of_facets[i]) facet[list_of_facets[i]] = list_of_facets[i+1] return facet
def job_url(project_id: str, job_id: str) -> str: """Returns a URL that will load the default page for the newly launched AI Platform job. """ prefix = "https://console.cloud.google.com/ai-platform/jobs" return "{}/{}?projectId={}".format(prefix, job_id, project_id)
def disabling_button_1a(n_clicks): """ Disabling the button after its being clicked once """ if n_clicks >= 1: return {'display':"none"}
def to_mst(f: float): """ Convert float input to minutes/seconds/thirds/fourths """ _r = f * 60 * 60 * 60 * 60 minutes, _r = divmod(_r, 60*60*60*60) seconds, _r = divmod(_r, 60*60*60) thirds, _r = divmod(_r, 60*60) fourths, _r = divmod(_r, 60) return int(minutes), int(seconds), int(...
def bouncingBall(h, bounce, window): """ A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known. He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). His mother looks out of a windo...
def csv_escape(string_value): """Escape a string value for CSV encoding. Arguments --------- string_value : `str` String value to escape for its encoding into CSV. Returns ------- `str` Escaped translation of :param:`string_value`. """ return string_value.translate(...
def _fix_url(url): """ fix given url to use HTTP requests """ if not url.startswith('http'): url = 'http://' + url return url
def get_variant_dict(variant_line, header_line): """Parse a variant line Split a variant line and map the fields on the header columns Args: variant_line (str): A vcf variant line header_line (list): A list with the header columns Returns: ...
def squared_numbers(start, stop): """ :param start: :param stop: :return: List of all the numbers between start and stop squared """ List = [] i = start while i <= stop: List.append(i ** 2) i += 1 return List
def _add_missing_roles_to_request( missing_roles, role_to_req, req_count_fields): """Helper for :py:func:`_igs_satisfy_request`. Add requests for *missing_roles* to *role_to_ig* so that we have a better chance of matching the cluster's actual instance groups.""" # see #1630 for discussion #...
def unwind(g, num): """Return <num> first elements from iterator <g> as array.""" return [next(g) for _ in range(num)]
def _parse_variable_name(line): """ :param line: Line in the file :returns: The variable name being assigned. >>> line = 'X = [1];' >>> _parse_variable_name(line) X """ rhs = line.split('=')[0].strip() if rhs.find('(') >= 0: rhs = rhs[:rhs.find('(')] return rhs
def separate_tagged_sents(tagged_sents): """Given a list of list of (token, TAG) pairs from Brown corpus, returns a parallel list of tokens and a list of tags.""" # Combine the sentences together tagged_tokens = [pair for sent in tagged_sents for pair in sent] return tuple(map(list, zip(*tag...
def abs_squared(x): """Computes Re(x)^2 + Im(x)^2. Args: x: An complex ndarray. """ return x.real**2 + x.imag**2
def match_sublist(the_list, to_match): """ Find sublist in the whole list Args: the_list (list(str)): the whole list - [1, 2, 3, 4, 5, 6, 1, 2, 4, 5] to_match (list(str)): the sublist - [1, 2] Returns: list(tuple): matched (start, end) position list ...
def fold(f, l, a): """ f: the function to apply l: the list to fold a: the accumulator, who is also the 'zero' on the first call """ return a if(len(l) == 0) else fold(f, l[1:], f(a, l[0]))
def split_strip(string, delimiter=","): """ Splits ``string`` on ``delimiter``, stripping each resulting string and returning a list of non-empty strings. """ if not string: return [] words = [w.strip() for w in string.split(delimiter)] return [w for w in words if w]
def csat(total_responses, positive_responses): """Return the Customer Satisfaction or CSAT score for a period. Args: total_responses (int): Total number of responses received within the period. positive_responses (int): Total number of positive responses received within the period. Returns...
def shard(lines): """Shard a file in several smaller ones.""" # The creation of the shard is handle in a generic way. Do we need this ? return lines
def check_negative_cycle(A, n): """ check if it has a negative cycle """ for i in range(1, n + 1): if A.get((i, i)) < 0: return True return False
def flatten_list(list_of_lists): """Returned a flattened version of a list of lists""" flat_list = [ val for sublist in list_of_lists for val in sublist ] return flat_list
def get_ref_spec(spec='LIOx'): """ Store of reference species for families Parameters ---------- spec (str): species/tracer/variable name Returns ------- ref_spec (str) reference species for a given family Notes ----- This is for use in conbination with functions that cal...
def final_dot(msg: str): """Add dot at end if need. title -> title. title: -> title: """ return msg and msg[-1].isalnum() and f"{msg}." or msg
def get_q_value(data, p): """ Helper function to be used for quantile(). Given data and a p value, returns the value from data below which you would find (p*100)% of the values. """ q = len(data) * p for index, _ in enumerate(data): if (index + 1) >= q: return(data[index...
def _verify_req_cols(req_cols, allowed_output_cols): """Verify user requested columns against allowed output columns. """ if req_cols is not None: if not req_cols.issubset(allowed_output_cols): raise ValueError( "Given req_cols must be subset of %s" % (allowed_output_cols...
def read_ip_address_from_file(filename): """ Read my saved IP address from file """ try: with open(filename, "r") as saved: for line in saved: return True, line except IOError: pass return False, None
def last(xs): """``last :: [a] -> a`` Extract the last element of a list, which must be finite and non-empty. """ return xs[-1]
def formatter(inf: dict): """ Returns: str: Formatted string """ s = f"__**Case {inf['case']}**__: **VICTIM** - {inf['victim']}, **ACTION** - {inf['action']}, **Moderator** - {inf['author']}, **Duration** - {inf['duration']}" s += f" **REASON** - {inf['reason']}" return s
def split_unescape(s, delim, escape='\\', unescape=True): """ >>> split_unescape('foo,bar', ',') ['foo', 'bar'] >>> split_unescape('foo$,bar', ',', '$') ['foo,bar'] >>> split_unescape('foo$$,bar', ',', '$', unescape=True) ['foo$', 'bar'] >>> split_unescape('fo...
def assign_str(source, key, default=""): """ Get the key value from source or return the default or return nothing :param source: :param key: :param default: :return: """ if key in source: if not source[key] == "": # if settings.DEBUG: # print(...
def removeLocations(lmA, prefix): """Removes locations with a given prefix Keyword arguments: lmA -- Location map to delete location from prefix -- Key or part of key in location map dictionary Creates a copy of provided location map lmA Copy contains all key-value pairs from l...
def oppositedirection(moved, last_op, op): """ Check if keeper will repeat move in the opposite direction (and had not pushed anything)""" opposites = [('W', 'S'), ('A', 'D')] if moved: return False for t in opposites: if (last_op == t[0] and op == t[1]) or (last_op == t[1] and op == t[0...
def user_app_cache_key(user_pk: str) -> str: """Cache key where application list for user is saved""" return f"user_app_cache_{user_pk}"
def find_alpha(lst): """ Return alpha part from the harmonic series. :param lst: list with alpha. :return: string alpha. """ if '(' in lst or ')' in lst: return ''.join(lst[1:-1]) else: return ''.join(lst)
def bstr(bits): """Convert a bit sequence to a string. >>> assert bstr([0, 0]) == "00" >>> assert bstr([0, 1]) == "01" >>> assert bstr([1, 0]) == "10" >>> assert bstr([1, 1]) == "11" """ return "".join(str(x) for x in bits)
def _get_keywords_with_score(extracted_lemmas, lemma_to_word): """ :param extracted_lemmas:list of tuples :param lemma_to_word: dict of {lemma:list of words} :return: dict of {keyword:score} """ keywords = {} for score, lemma in extracted_lemmas: keyword_list = lemma_to_word[lemma] ...
def is_monotonic(full_list): """ Determine whether elements in a list are monotonic. ie. unique elements are clustered together. ie. [5,5,3,4] is, [5,3,5] is not. """ prev_elements = set({full_list[0]}) prev_item = full_list[0] for item in full_list: if item != prev_item: ...
def _update_expected(expected, output): """If pytest >= 4.1.0 is used, remove single quotes from expected output. This function allows to successfully assert output using version of pytest with or without pytest-dev/pytest@e9b2475e2 (Display actual test ids in `--collect-only`) introduced in version 4....
def pagenav(object_list, base_url, order_by, reverse, cur_month, is_paginated, paginator): """Display page navigation for given list of objects""" return {'object_list': object_list, 'base_url': base_url, 'order_by': order_by, 'reverse': reverse, 'cur_month': cur_...
def conjugate_matrix(matrix): """Conjugates all entries of matrix. Returns the conjugated matrix. Args: matrix (2-D list): Matrix. Returns: Conjugated matrix. """ conj_matrix = [[0] * len(matrix[i]) for i in range(len(matrix))] for i, row in enumerate(matrix): for ...
def fix(d): """Turn mono data into stereo""" line=d n=2 return ''.join([line[i:i+n]*2 for i in range(0, len(line), n)]) shorts = struct.unpack('<' + 'h' * (len(d)/2), d) dbl = reduce(lambda x,y: x+y, zip(shorts, shorts)) return struct.pack('<' + 'h' * len(d), *dbl)
def filterdictvals(D, V): """ dict D with entries for valeus V removed. filterdictvals(dict(a=1, b=2, c=1), 1) => {'b': 2} """ return {K: V2 for (K, V2) in D.items() if V2 != V}
def camelcase(s): """Turn strings_like_this into StringsLikeThis""" return ''.join([word.capitalize() for word in s.split('_')])
def _unique_item_counts(iterable): """ a dictionary giving the count of each unique item in a sequence """ items = tuple(iterable) return {item: items.count(item) for item in sorted(set(items))}
def fix_pctg_in_name(val): """ Function that escapes a value for SQL processing (replacing % by double %%) :param val: Value to escape :return: Escaped value """ return val.replace('%', '%%')
def int_convert(s): """ Parse string int from parameters * :param s(str): String to convert :return s(int): Int type """ try: return int(s) except ValueError: return s except TypeError: return s
def parse_window(time): """Convert a string in the format 'Wd Xh Ym Zs' into an int in seconds. Args: time (str): A string in the format 'Wd Xh Ym Zs'. Returns: int: Number of seconds. """ time_seconds = 0 if isinstance(time, int): # time already converted return time ...
def removeDuplicates(nums): """ :type nums: List[int] :rtype: int """ i = 0 while i < len(nums) - 1: if nums[i] == nums[i + 1]: nums.remove(nums[i]) else: i = i + 1 return nums
def spin_factor(J, M, c): """ Calculate spin factor(a) of kerr body Parameters ---------- J : float Angular momentum in SI units(kg m2 s-2) M : float Mass of body in SI units(kg) c : float Speed of light Returns ------- float Spin factor (J/(Mc))...
def credit_given(file_paths): """Check if Misc/ACKS has been changed.""" return True if 'Misc/ACKS' in file_paths else False
def compareRule(origFileName): """ Function that applies a rule to a file name to be comparable to other file names. Basically it extracts the file name part to compare with others. Example: tif files that only differ in one character at the end, like 038_FJB_1904-001a.tif and 038_FJB_1904-001b...
def parse_benchmark_name(name: str): """ Parses a template benchmark name with a size >>> parse_benchmark_name('BM_Insert_Random<int64_t, int64_t, std::unordered_map>/1000') ('BM_Insert_Random', ['int64_t', 'int64_t', 'std::unordered_map'], 1000) """ base_name = name[0 : name.find('<')] t_pa...
def normalize_timedelta(timedelta): """ Given a string like "1w" or "-5d", convert it to an integer in milliseconds. Integers without a suffix are interpreted as seconds. Note: not related to the datetime timedelta class. """ try: return int(timedelta) * 1000 except ValueError as e: ...
def potential(x, a): """ """ if abs(x) <= a: # position inside potential V0 = -83.0 else: # position outside potential V0 = 0.0 return V0
def fibonacci_recursion(n): """ :param n: F(n) :return: val """ if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci_recursion(n-1) + fibonacci_recursion(n-2)
def makeByte(highNibble, lowNibble): """ 0 <= highNibble <= 15 0 <= lowNibble <= 15 0 <= result <= 255 """ result = highNibble << 4 | lowNibble & 0xF return result
def join_and(value): """Given a list of strings, format them with commas and spaces, but with 'and' at the end. >>> join_and(['apples', 'oranges', 'pears']) "apples, oranges, and pears" """ # convert numbers to strings value = [str(item) for item in value] if len(value) == 0: r...
def diff_metadata_columns(li1, li2): """ Compares two lists and returns differnce """ diff = list(set(li1) - set(li2)) return diff
def to_filename(name): """ Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'. """ return name.replace('-', '_')
def is_ip(s): """Returns whether or not a given string is an IPV4 address.""" import socket try: return bool(socket.inet_aton(s)) except socket.error: return False
def get_base_fee_multiplier(base_fee_gwei: int) -> float: """Returns multiplier value.""" if base_fee_gwei <= 40: # pylint: disable=no-else-return return 2.0 elif base_fee_gwei <= 100: # pylint: disable=no-else-return return 1.6 elif base_fee_gwei <= 200: # pylint: disable=no-else-re...
def _DoRemapping(element, map): """If |element| then remap it through |map|. If |element| is iterable then each item will be remapped. Any elements not found will be removed.""" if map is not None and element is not None: if isinstance(element, list) or isinstance(element, tuple): element = filter(None,...
def get_bezier4_point(point_a,control_a,control_b,point_b,t): """gives the point t(between 0 and 1) on the defined Bezier curve""" return (1-t)**3*point_a + 3*(1.-t)**2*t*control_a + 3*(1-t)*t**2*control_b + t**3*point_b
def subdict(dct, seq, **kwargs): """Sub dict.""" # tuple(seq) as seq might be iterator # return {k: v for k, v in dct.iteritems() if k in tulpe(seq)} # This might be faster if dct is large as doesn't have to iterate through it. # also works natively with seq being an iterator, no tuple initialisati...
def background_negative_green(val): """ Changes the background color of a cell in DataFrame according to its value. Parameters ---------- val : float single cell value in a pandas DataFrame. Returns ------- str return background color for the cell of pandas DataFrame. ...
def get_routes(routes): """ Given a list of routes, return a formatted string of all the routes. """ return "`" + "`, `".join(p for r in routes for p in r["paths"]) + "`"
def height(root): """ DFS v = Vertices e = Edges d = Depth Time complexity: O(v + e) Space complexity: O(d) """ if root: return 1 + max(height(root.left), height(root.right)) else: return -1
def SegmentContains(main_l, main_r, l, r): """Returns true if [l, r) is contained inside [main_l, main_r). Args: main_l: int. Left border of the first segment. main_r: int. Right border (exclusive) of the second segment. l: int. Left border of the second segment. r: int. Right border (exclusive) of...
def html_rep(obj): """Format an object in an html-friendly way. That is; convert any < and > characters found in the str() representation to the corresponding html-escape sequence.""" s = str(obj) if s == '': s = repr(obj) return s.strip().replace('<','&lt;').replace('>', '&...
def _ensure_wrappability(fn): """Make sure `fn` can be wrapped cleanly by functools.wraps.""" # Handle "builtin_function_or_method", "wrapped_descriptor", and # "method-wrapper" types. unwrappable_types = (type(sum), type(object.__init__), type(object.__call__)) if isinstance(fn, unwrappable_types): # pyl...
def show_hidden(str, show_all=False): """Return true for strings starting with single _ if show_all is true.""" return show_all or str.startswith("__") or not str.startswith("_")
def comp(obj1, obj2): """code a l arrache, il faudrait passer du temps pour voir ca mieux""" if hasattr(obj1, "__dict__") and hasattr(obj2, "__dict__"): return obj1.__dict__ == obj2.__dict__ else: return obj1 == obj2
def isEven(num): """Boolean function returning true if num is even, false if not""" return num%2 == 0
def meets_criteria_strict(value): """Determine if a number meets the criteria >>> meets_criteria_strict(112233) True >>> meets_criteria_strict(123444) False >>> meets_criteria_strict(111111) False >>> meets_criteria_strict(111122) True >>> meets_criteria_strict(223450) False...
def _augment(graph, capacity, flow, val, u, target, visit): """Find an augmenting path from u to target with value at most val""" visit[u] = True if u == target: return val for v in graph[u]: cuv = capacity[u][v] if not visit[v] and cuv > flow[u][v]: # arc franchissable ...
def auto_parameterize(nn_dist, snn_dist, smear=None): """ Automatically calculate fermi parameters from crystal properties so that the midpoint and width of the smearing depend on the distance between first and second nearest neighbours. Args: nn_dist (float): Nearest neighbour distance. ...
def format_descriptor(descriptors): """ formats a descriptor dictionary Args: descriptors(dict): the descriptor dictionary Returns: String: formatted string to show dict """ string_descriptors = '' for entry in descriptors: string_descriptors = (string_descriptors + ...
def prox_l2(x, threshold): """Proximal operator for ridge regularization.""" return 2 * threshold * x
def get_val_from_dict(indict, col): """ Gets the value from a branch of a dictionary. The dictionary can have nested dictionaries and lists. When walking through lists, #i in the branch data identifies the ith element of the list. This method can be used to travel branches of a dictionary previous...
def snp_contig_location(flag, pos, adjusted_bp_location, alignment_length): """ determine new bp position of the snp on the larger contig""" try: """ make sure a number was passed in, if not return empty bp """ adjusted_bp_location / 1 except: return '-' if flag == 0 or flag == 256: """ forward aligment, a...
def TakeClosest(myList,myNumber): """Given a list of integers, I want to find which number is the closest to a number x.""" return min(myList, key=lambda x:abs(x-myNumber))
def is_leap_year(year: str) -> bool: """ Helper function used to determine if a string is a leap year or not. :param year: The year to check. :return: True if a leap year, false otherwise. """ if int(year) % 4 == 0: if int(year) % 100 == 0: if int(year) % 400 == 0: ...
def min_operations(target): """ Return number of steps taken to reach a target number input: target number (as an integer) output: number of steps (as an integer) """ steps = 0 while target != 0: steps += 1 if target % 2 == 1: target -= 1 else: ...