content
stringlengths
42
6.51k
def get_video_muxings_from_configs(configs, codec, manifest_type): """ Returns all video muxings of a given codec to be used with a given manifest type (DASH/HLS). """ muxings = [] for config in configs: if config['profile']['codec'] == codec: muxings += [ muxing...
def line_contained_in_region(test_line: str, start_line: str, end_line: str) -> bool: """check if test_line is contained in [startLine, endLine]. Return True if so. False else. :param test_line: <fileID>:<line> :param start_line: <fileID>:<line> :param end_line: <fileID>:<line> :return: bool ...
def get_region(region): """Return the region naming used in this package. Parameters ---------- region : str Regional synonym. Returns ------- region : str Region either 'cena' or 'wna'. """ region = region.lower() if region in ['cena', 'ena', 'ceus', 'eus']: ...
def ros_service_response_cmd(service, result, _id=None, values=None): """ create a rosbridge service_response command object a response to a ROS service call :param service: name of the service that was called :param result: boolean return value of service callback. True means success, False failu...
def repair_value(value): """ share.repair_value(T.trade_info()[1][1])) :param value: :return: list of float number, first item is the value of the share, second of is the change with yesterday value and the last one is the percent of this change. """ value = value.replace(',', '') va...
def parse_spec(spec: str) -> dict: """ Return a map of {"positive": [<examples>], "negative": [<examples>]} Examples: >>> parse_spec(''' ... POSITIVE: ... ab ... abab ... ... NEGATIVE: ... ba ... baba ... ''') {'positive': ['ab...
def all_equal(elements): """return True if all the elements are equal, otherwise False. """ first_element = elements[0] for other_element in elements[1:]: if other_element != first_element: return False return True
def is_valid_pin(pin: str) -> bool: """Determine if pin is valid ATM pin.""" if len(pin) in (4, 6): try: return bool([int(i) for i in pin]) except ValueError: return False return False
def structEndian(endianness='big'): """:param endianness (str) return: str the code how "struct" is interpreting the bin data default is big endiann """ dictionary = { '@': '@', 'native': '@', '=': '=', 'standard': '=', '<': '<', ...
def commonprefix(l): """Return the common prefix of a list of strings.""" if not l: return '' prefix = l[0] for s in l[1:]: for i, c in enumerate(prefix): if c != s[i]: prefix = s[:i] break return prefix
def str_to_bytes(value): """ Converts string to array of bytes :param value: string :return: array of bytes """ if isinstance(value, (bytes, bytearray, memoryview)): return bytes(value) return bytes(value, "utf-8")
def binary_search(lst, to_find): """ Binary Search: O(log n) n: Number of elements in the list Works only on Sorted array. https://en.wikipedia.org/wiki/Binary_search_algorithm """ if to_find > lst[-1]: # Check if `to_find` is out of `lst` range ...
def get_most_rare_letter(items=[]): """ :param items: item list to find out the most rarely occurred :return: one object from the item list """ from operator import itemgetter if len(items) == 0: return 'Not existed' else: # get all first letters list first_letters_l...
def b_xor(a, b): """xor on bitstring encoded as string of '0's and '1's.""" y = '' for i in range(len(a)): if a[i] == b[i]: y += '0' else: y += '1' return y
def maybe_resolve(object, resolve): """ Call `resolve` on the `object`'s `$ref` value if it has one. :param object: An object. :param resolve: A resolving function. :return: An object, or some other object! :sparkles: """ if isinstance(object, dict) and object.get('$ref'): return re...
def reorder_after_dim_reduction(order): """Ensure current dimension order is preserved after dims are dropped. Parameters ---------- order : tuple The data to reorder. Returns ------- arr : tuple The original array with the unneeded dimension thrown away. """ ...
def parse_latitude(x): """ Parses latitude-coordinate out of a latitude/longitude-combination (separated by ','). """ y = x.strip().split(',') return float(y[0])
def abi_definitions(contract_abi, typ): """Returns only ABI definitions of matching type.""" return [a for a in contract_abi if a["type"] == typ]
def scale(x, a, b, c, d): """Scales a value from one range to another range, inclusive. This functions uses globally assigned values, min and max, of N given .nsidat files Args: x (numeric): value to be transformed a (numeric): minimum of input range b (numeric): maximum of inp...
def foo_two_params_redux(bar='hello', baz='world'): """Joins two strings with a space between them. **This function has a no deprecation decorator.** Parameters ---------- bar : str The first word to join. baz : str The second word to join. """ return bar + ' ' + baz
def function3(arg1, arg2): """This is my doc string of things Here is an extended decription. """ ans = arg1 + arg2 return ans
def get_vcf_sample_indices(sample_ids, ids_to_include=None): """Get the indices of the samples to be included in the analysis Parameters ---------- sample_ids : list, tuple All sample IDs in the input VCF file ids_to_include : set All sample IDs to be included in the analysis. I...
def process_pairings(pairings_file): """ Reads in pairings from the comma-delimited pairings file and creates a list of lists """ pairings = [] with open(pairings_file, 'r') as f: for group in f: group = group.strip().split(',') pairings.append(group) return pai...
def peval(plist,x,x2=None): """\ Eval the plist at value x. If two values are given, the difference between the second and the first is returned. This latter feature is included for the purpose of evaluating definite integrals. """ val = 0 if x2: for i in range(len(plist)): val +...
def matriztranspuesta(m1): """Funcion que convierte una matriz en su forma transpuesta (list 2D) -> list 2D""" ans = [] for j in range(len(m1[0])): ans.append([]) for i in range(len(m1)): num1 = m1[i][j] ans[j].append(num1) return(ans)
def foo3(value): """Missing return statement implies `return None`""" if value: return value
def is_name_in_email(name, email): """ Removing emails from Enron where name is in email """ if str(name).lower() in str(email).lower(): return 1 else: return 0
def _cleanup(lst): """ Return a list of non-empty dictionaries. """ clean = [] for ele in lst: if ele and isinstance(ele, dict): clean.append(ele) return clean
def get_shred_id(id): """ >>> get_shred_id("ca-bacs.5638.frag11.22000-23608") ("ca-bacs.5638", 11) """ try: parts = id.split(".") aid = ".".join(parts[:2]) fid = int(parts[2].replace("frag", "")) except: aid, fid = None, None return aid, fid
def find_by(list, key, val): """Find a dict with given key=val pair in a list.""" matches = [i for i in list if i[key] == val] return matches[0] if len(matches) == 1 else None
def side_pos(input_num, start, x_dist): """ Get the position indicator in the current side """ return (input_num - start) % ((x_dist - 1) * 2)
def altsumma(f, k, p): """Return the sum of f(i) from i=k, k+1, ... till p(i) holds true or 0. This is an implementation of the Summation formula from Kahan, see Theorem 8 in Goldberg, David 'What Every Computer Scientist Should Know About Floating-Point Arithmetic', ACM Computer Survey, Vol. 23, No...
def city_country(city, country): """Return the the name of a city and it's country.""" place = f"{city}, {country}" return place.title()
def hms(d, delim=':'): """Convert hours, minutes, seconds to decimal degrees, and back. EXAMPLES: hms('15:15:32.8') hms([7, 49]) hms(18.235097) Also works for negative values. SEE ALSO: dms """ # 2008-12-22 00:40 IJC: Created # 2009-02-16 14:07 IJC: Works with spaced or colo...
def derivatives(dim, order): """Return all the orders of a multidimensional derivative.""" if dim == 1: return [(order, )] out = [] for i in range(order + 1): out += [(i, ) + j for j in derivatives(dim - 1, order - i)] return out
def id_to_python_variable(symbol_id, constant=False): """ This function defines the format for the python variable names used in find_symbols and to_python. Variable names are based on a nodes' id to make them unique """ if constant: var_format = "const_{:05d}" else: var_format ...
def formula_double_format(afloat, ignore_ones=True, tol=1e-8): """ This function is used to make pretty formulas by formatting the amounts. Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4. Args: afloat (float): a float ignore_ones (bool): if true, floats of 1 are ignored. tol ...
def parse_value(s): """Parse a given string to a boolean, integer or float.""" if s.lower() == 'true': return True elif s.lower() == 'false': return False elif s.lower() == 'none': return None try: return int(s) except: # pylint: disable=bare-except pass try: return float(s) e...
def validate_rng_seed(seed, min_length): """ Validates random hexadecimal seed returns => <boolean> seed: <string> hex string to be validated min_length: <int> number of characters required. > 0 """ if len(seed) < min_length: print("Error: Computer entropy must be at least {0} char...
def naive_fib(n): """Compute the nth fibonaci number""" if n <= 2: f = 1 else: f = naive_fib(n - 1) + naive_fib(n - 2) return f
def test_url(url_to_test): """Basic testing to check if url is valid. Arguments: url_to_test {str} -- The url to check Returns: int -- Error number """ if not isinstance(url_to_test, str): return 103 url = str(url_to_test).strip() if not url: return 101 ...
def priority(s): """Return priority for a give object.""" if type(s) in (list, tuple, set, frozenset): return 6 if type(s) is dict: return 5 if hasattr(s, 'validate'): return 4 if issubclass(type(s), type): return 3 if callable(s): return 2 else: ...
def unify_duplicated_equal_signs(s: str) -> str: """ Removes repeated equal signs only if they are one after the other or if they are separated by spaces. Example: 'abc===def, mno= =pqr, stv==q== =' --> 'abc=def, mno=pqr, stv=q=' """ sequence_started = False new_string = [] for char in...
def get_linear_mat_properties(properties): """ Fy, Fu, E, G, poisson, density, alpha """ set_prop = [280_000_000, 0, 205_000_000_000, 77_200_000_000, 0.30, 7.850E12, 1.2E-5] set_units = ['pascal', 'pascal', 'pascal', 'pascal', None, 'kilogram/mstre^3', 'kelvin'] for x, item in en...
def to_set(words): """ cut list to set of (string, off) """ off = 0 s = set() for w in words: if w: s.add((off, w)) off += len(w) return s
def pretty_process(proc): """The HTML list item for a single build process.""" if proc["return_code"] is None: rc = '<span class="no-return">?</span>' elif proc["return_code"]: rc = '<span class="bad-return">%s</span>' % proc["return_code"] else: rc = '<span class="good-return">%...
def bs4_object_as_text(obj): """Parse bs4 object as text """ if obj is not None: return obj.get_text(strip=True) return None
def get_last_step_id(steps): """Returns the id of the last step in |steps|.""" return steps[-1]['id']
def integer(value, name): # type: (str, str) -> int """casts to an integer value""" if isinstance(value, int): return value value = value fvalue = float(value) if not fvalue.is_integer(): raise RuntimeError('%s=%r is not an integer' % (name, fvalue)) return int(fvalue)
def extract_number_oscillations(osc_dyn, index = 0, amplitude_threshold = 1.0): """! @brief Extracts number of oscillations of specified oscillator. @param[in] osc_dyn (list): Dynamic of oscillators. @param[in] index (uint): Index of oscillator in dynamic. @param[in] amplitude_threshold (...
def maybe_add(a, b): """ return a if b is None else a + b """ return a if b is None else a + b
def add_to_date(x, year=0, month=0, day=0): """This method... .. note: Should I return nan? """ try: return x.replace(year=x.year + year, month=x.month + month, day=x.day + day) except: return x
def problem_20(n=100): """ sum digits in n! both naive and space conservative work answer 648 """ # not space efficient n_fact = 1 for i in range(1, n + 1): n_fact *= i # insights: we can divide all the zeroes out as we go # while n_fact % 10 == 0: # n_fact /= 10...
def parse_namespace_uri(uri): """Get the prefix and namespace of a given URI (without identifier, only with a namspace at last position). :param str uri: URI :returns: prefix (ex: http://purl.org/dc/terms/...) :returns: namespace (ex: .../isPartOf) :rtype: tuple[str,str] """ # Split the uri...
def make_iterable(obj): """Check if obj is iterable, if not return an iterable with obj inside it. Otherwise just return obj. obj - any type Return an iterable """ try: iter(obj) except: return [obj] else: return obj
def bbox_vert_aligned(box1, box2): """ Returns true if the horizontal center point of either span is within the horizontal range of the other """ if not (box1 and box2): return False # NEW: any overlap counts # return box1.left <= box2.right and box2.left <= box1.right box1_left = box...
def solution(X, A): """ DINAKAR Clue -> Find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X [1, 3, 1, 4, 2, 3, 5, 4] X = 5 ie. {1, 2, 3, 4, 5} here 1 to X/5 is completed so we re...
def translate(word, translateDict): """This method takes a word and transliterate it using transcription rules which are provided in translateDict dictionary. Args: word (string): Word to be transliterated. translateDict (Dictionary): Dictionary in which keys and values represents 1:1 tran...
def TopologicalSort(vertices, adjacencies): """ Topological Sort of a directed acyclic graph (reverse ordered topsort) Example: vertices = [1,2,3,4,5] edges = [(1,2),(2,3),(2,4),(4,5),(3,5),(1,5)] adjacencies = lambda v : [ j for (i,j) in edges if i == v ] print(TopologicalSort(vertices,adjacenci...
def SortAndGrid(table,order): """table => {s:{p:{c:{a:{}}}}}""" grid=[] for (server,ports) in table.items(): for (port,configfiles) in ports.items(): for (configfile,appnames) in configfiles.items(): for appname in appnames.keys(): line=[] for col in order.values(): if col=="s": line....
def f1_score(real_labels, predicted_labels): """ Information on F1 score - https://en.wikipedia.org/wiki/F1_score :param real_labels: List[int] :param predicted_labels: List[int] :return: float """ assert len(real_labels) == len(predicted_labels) # tp = true-positive # fp = fals...
def get_divider(title='Error', linewidth=79, fill_character='#'): """ Useful for separating sections in logs """ lines = [ '', fill_character * linewidth, f' {title} '.center(linewidth, fill_character), ] return '\n'.join(lines)
def last_failure_for_job(job): """ Given a job, find the last time it failed. In the case that it has never failed, return None. """ return job.get('lastError', None)
def getFibonacciDynamic(n: int, fib: list) -> int: """ Calculate the fibonacci number at position n using dynamic programming to improve runtime """ if n == 0 or n == 1: return n if fib[n] != -1: return fib[n] fib[n] = getFibonacciDynamic(n - 1, fib) + getFibonacciDynamic(n - 2,...
def R0(beta, gamma, prob_symptoms, rho): """ R0 from model parameters. """ Qs = prob_symptoms return beta / gamma * (Qs + (1 - Qs) * rho)
def safe_filename(original_filename: str) -> str: """Returns a filename safe to use in HTTP headers, formed from the given original filename. >>> safe_filename("example(1).txt") 'example1.txt' >>> safe_filename("_ex@mple 2%.old.xlsx") '_exmple2.old.xlsx' """ valid_chars = 'abcdefghijkl...
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ stub = -1 max_len = 0 cache = {} for i, v in enumerate(s): if v in cache and cache[v] > stub: stub = cache[v] cache[v] = i else: cache[v] = i if i - stub > m...
def func_x_args_p_kwargs(x, *args, p="p", **kwargs): """func. Parameters ---------- x: float args: tuple p: str kwargs: dict Returns ------- x: float args: tuple p: str kwargs: dict """ return x, None, None, None, args, p, None, kwargs
def solution(A): """ Finds a value that occurs in more than half of the elements of an array """ n = len(A) L = [-1] + A count = 0 pos = (n + 1) // 2 candidate = L[pos] for i in range(1, n + 1): if L[i] == candidate: count = count + 1 print(count, n/2) if count > ...
def integrate_function(function, x_array): """ Calculate the numeric integral of a function along a given x array. :param function: a callable function that returns numbers. :x_array: a list of ascending number along which to integrate. """ i = integral = 0 while i < len(x_array) - 2: ...
def uses_all(word, letters): """Write a function named uses_all that takes a word and a string of required letters, and that returns True if the word uses all the required letters at least once.""" for letter in letters: if not(letter in word): return False return True
def sum_digits(s): """ assumes s a string Returns an int that is the sum of all of the digits in s. If there are no digits in s it raises a ValueError exception. """ sum_of_digits = 0 count = 0 for item in s: if item in list('0123456789'): sum_of_digits += int(item) ...
def quadratic_objective(x, a, b, c): """Quadratic objective function.""" return a*x**2 + b*x + c
def get_person_id(id): """Pad person ID to be 10 characters in length""" return "{:<14}".format(str(id))
def rule_110(a, b, c): """ Compute the value of a cell in the Rule 110 automata. https://en.wikipedia.org/wiki/Rule_110 Let `n` be the current row and `i` be the current column. This function computes the value of the cell (i, n). Inputs: a - The value of cell (i-1, n-1) b - The value ...
def array_to_bits(bit_array): """ Converts a bit array to an integer """ num = 0 for i, bit in enumerate(bit_array): num += int(bit) << (len(bit_array) - i - 1) return num
def _PickSymbol(best, alt, encoding): """Chooses the best symbol (if it's in this encoding) or an alternate.""" try: best.encode(encoding) return best except UnicodeEncodeError: return alt
def blocks_slice_to_chunk_slice(blocks_slice: slice) -> slice: """ Converts the supplied blocks slice into chunk slice :param blocks_slice: The slice of the blocks :return: The resulting chunk slice """ return slice(blocks_slice.start % 16, blocks_slice.stop % 16)
def _sum_func(dat): """Helper function to sum the output of the data_functions""" tot = 0 for params, obj in dat: tot += obj return tot
def convert_contrast(contrast, contrast_selected, entry1, entry2): """ 6. Contrast """ if contrast == 1: if contrast_selected == "+2": command = "+contrast +contrast" elif contrast_selected == "+1": command = "+contrast" elif contrast_selected == "-1": ...
def _parse_kwargs(kwargs): """ Extract kwargs for layout and placement functions. Leave the remaining ones for minorminer.find_embedding(). """ layout_kwargs = {} # For the layout object if "dim" in kwargs: layout_kwargs["dim"] = kwargs.pop("dim") if "center" in kwargs: layou...
def get_hex_chunks(hex_str): """From one hex str return it in 3 chars at a time""" return [hex_str[i:i+3] for i in range(0, len(hex_str), 3)]
def format_coords(coords): """Return a human-readable coordinate.""" lat, lng = map(lambda num: round(num, 2), coords) lat_component = u'{0}\u00b0 {1}'.format(abs(lat), 'N' if lat >= 0 else 'S') lng_component = u'{0}\u00b0 {1}'.format(abs(lng), 'E' if lng >= 0 else 'W') return u'{0}, {1}'.format(lat...
def _HexAddressRegexpFor(android_abi): """Return a regexp matching hexadecimal addresses for a given Android ABI.""" if android_abi in ['x86_64', 'arm64-v8a', 'mips64']: width = 16 else: width = 8 return '[0-9a-f]{%d}' % width
def rhesus_lambda(sequence): """ Rhesus lambda chains have insertions. This screws up the alignment to everything else - not really IMGT gapped. Remove and return """ return sequence[:20]+sequence[21:51]+ sequence[53:]
def simple_series_solution_sum(series_subtotals, *args, **kwargs): """ Simply adds up the totals from the series themselves. """ return sum(subtotal[-1] or 0 for subtotal in series_subtotals)
def polygon_area(corners): """ calculated the area of a polygon given points on its surface https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates https://en.wikipedia.org/wiki/Shoelace_formula """ n = len(corners) # of corners area = 0.0 for i in ...
def change_extension(filename, new_ext): """ Change file extension """ fn = '.'.join(filename.split('.')[:-1] + [new_ext]) return fn
def _query_for_log(query: bytes) -> str: """ Takes a query that ran returned by psycopg2 and converts it into nicely loggable format with no newlines, extra spaces, and converted to string :param query: Query ran by psycopg2 :return: Cleaned up string representing the query """ ...
def grid_pos_to_params(grid_data, params): """ converts a grid search combination to a dict for callbacks that expect kwargs """ func_kwargs = {} for j,k in enumerate(params): func_kwargs[k] = grid_data[j] return func_kwargs
def add(left: int, right: int): """ add up two numbers. """ print(left + right) return 0
def _parse_refraction(line, lines): """Parse Energy [eV] ref_ind_xx ref_ind_zz extinct_xx extinct_zz""" split_line = line.split() energy = float(split_line[0]) ref_ind_xx = float(split_line[1]) ref_ind_zz = float(split_line[2]) extinct_xx = float(split_line[3]) extinct_zz = float(...
def escape_parameter_name(p): """Necessary because: 1. parameters called 'size' or 'origin' might exist in cs 2. '-' not allowed in bokeh's CDS""" return 'p_' + p.replace('-', '_')
def eval_str(string): """Executes a string containing python code.""" output = eval(string) return output
def ac_voltage(q, u_dc): """ Computes the AC-side voltage of a lossless inverter. Parameters ---------- q : complex Switching state vector (in stator coordinates). u_dc : float DC-Bus voltage. Returns ------- u_ac : complex AC-side voltage. ...
def validate_none(value_inputs): """ Validation of inputs :param value_inputs: List of values from Input controls :return: """ for inputValue in value_inputs: if inputValue is None: return False return True
def set_parameters_and_default_1D(parlist, default, ngauss) : """ Set up the parameters given a default and a number of gaussians Input is parlist : the input parameters you wish to set default : the default when needed for one gaussian ngauss : the number of Gaussians """ ## If the le...
def present(element, act): """Return True if act[element] is valid and not None""" if not act: return False elif element not in act: return False return act[element]
def _is_earlier(t1, t2): """Compares two timestamps.""" if t1['secs'] > t2['secs']: return False elif t1['secs'] < t2['secs']: return True elif t1['nsecs'] < t2['nsecs']: return True return False
def canvas(with_attribution=True): """Placeholder function to show example docstring (NumPy format) Replace this function and doc string for your own project Parameters ---------- with_attribution : bool, Optional, default: True Set whether or not to display who the quote is from Retu...