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_spec for muxing_spec in config['muxing_list'] if muxing_spec['manifest_type'] == manifest_type ] return muxings
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 """ test_line_file_id = int(test_line.split(":")[0]) test_line_line = int(test_line.split(":")[1]) start_line_file_id = int(start_line.split(":")[0]) start_line_line = int(start_line.split(":")[1]) end_line_file_id = int(end_line.split(":")[0]) end_line_line = int(end_line.split(":")[1]) if test_line_file_id == start_line_file_id == end_line_file_id and \ start_line_line <= test_line_line <= end_line_line: return True return False
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']: return 'cena' elif region in ['wna', 'wus']: return 'wna' else: raise NotImplementedError('No recognized region for: %s', region)
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 failure. :param _id: if an ID was provided to the call_service request, then the service response will contain the ID :param values: dict of the return values. If the service had no return values, then this field can be omitted (and will be by the rosbridge server) """ command = { "op": "service_response", "service": service, "result": result } if _id: command["id"] = _id if values: command["values"] = values return command
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(',', '') value = value.replace('(', '') value = value.replace(')', '') value = value.replace('%', '') return list(map(float, value.split()))
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', 'abab'], 'negative': ['ba', 'baba']} """ _, sep1, spec = spec.strip().partition('POSITIVE:\n') positive, sep2, negative = spec.strip().partition('NEGATIVE:\n') if not sep1 or not sep2: raise ValueError('Spec does not contain a POSITIVE: and NEGATIVE: sections.') return { 'positive': positive.strip().splitlines(), 'negative': negative.strip().splitlines(), }
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': '=', '<': '<', 'little':'<', '>': '>', 'big': '>', '!': '!', 'network': '!' } return dictionary.get(endianness)
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 return False if to_find == lst[0] or to_find == lst[-1]: # Check if first or last element is == `to_find` return True middle = (len(lst)-1)//2 # Find mid-point of list mid_num = lst[middle] # Get middle element if mid_num == to_find: # Check if element == `to_find` return True if to_find > mid_num: return binary_search(lst[middle:], to_find) # If `to_find` is greater than mid-point, search right side `lst` else: return binary_search(lst[:middle], to_find)
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_list = list(map(lambda x: x[0], items)) # get the unique letters set first_letters_set = set(first_letters_list) # counts for each unique letter pairs = list(map(lambda x: (x, first_letters_list.count(x)), first_letters_set)) sorted_pairs = sorted(pairs, key=itemgetter(1), reverse=False) print('General statistics: ', sorted_pairs) pair_min = sorted_pairs[0] return pair_min
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 resolve(object['$ref']) return object
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. """ arr = sorted(range(len(order)), key=lambda x: order[x]) return tuple(arr)
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 input range c (numeric): minimum of output range d (numeric): maximum of output range Returns: numeric: The equivalent value of the input value within a new target range """ return (x - a) / (b - a) * (d - c) + c
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. If not provided, all samples will be included. Returns ------- tuple Indices for all sample IDs indicated for inclusion in downstream analysis """ return tuple( i for i in range(len(sample_ids)) if ((sample_ids[i] in ids_to_include) if ids_to_include else True) )
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 pairings
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 += plist[i]*(pow(x2,i)-pow(x,i)) else: for i in range(len(plist)): val += plist[i]*pow(x,i) return 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. 1, March 1991.""" if not p(k): return 0 else: S = f(k) C = 0 j = k + 1 while p(j): Y = f(j) - C T = S + Y C = (T - S) - Y S = T j += 1 return S
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 colon-ed delimiters from numpy import sign if d.__class__==str or hasattr(d, '__iter__'): # must be HMS if d.__class__==str: d = d.split(delim) if len(d)==1: d = d[0].split(' ') if (len(d)==1) and (d.find('h')>-1): d.replace('h',delim) d.replace('m',delim) d.replace('s','') d = d.split(delim) s = sign(float(d[0])) if s==0: s=1 degval = float(d[0])*15.0 if len(d)>=2: degval = degval + s*float(d[1])/4.0 if len(d)==3: degval = degval + s*float(d[2])/240.0 return degval else: # must be decimal degrees hour = int(d/15.0) d = abs(d) min = int((d-hour*15.0)*4.0) sec = (d-hour*15.0-min/4.0)*240.0 return [hour, min, sec]
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 = "var_{:05d}" # Need to replace "-" character to make them valid python variable names return var_format.format(symbol_id).replace("-", "m")
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 (float): Tolerance to round to nearest int. i.e. 2.0000000001 -> 2 Returns: A string representation of the float for formulas. """ if ignore_ones and afloat == 1: return "" elif abs(afloat - int(afloat)) < tol: return str(int(afloat)) else: return str(round(afloat, 8))
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) except: # pylint: disable=bare-except return s
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} characters long".format(min_length)) return False if len(seed) % 2 != 0: print("Error: Computer entropy must contain an even number of characters.") return False try: int(seed, 16) except ValueError: print("Error: Illegal character. Computer entropy must be composed of hexadecimal characters only (0-9, a-f).") return False return True
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 if ' ' in url: return 102 return 0
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: return 1
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 s: if not sequence_started: new_string.append(char) if char == '=': sequence_started = True else: if char != '=' and not char.isspace(): sequence_started = False new_string.append(char) return ''.join(new_string)
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 enumerate(set_prop): try: set_prop[x] = properties[x].convert(set_units[x]).value except AttributeError: set_prop[x] = properties[x] except IndexError: pass # check if Fu if not set_prop[1]: set_prop[1] = set_prop[0]/0.75 return set_prop
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">%s</span>' % proc["return_code"] command = "<code>%s</code>" % proc["command"] errors = "" proc["errors"] = [e for e in proc["errors"] if e["category"] != "ok path"] if proc["errors"]: errors = "<br />\n".join([ ("<span class=\"red-error\">%s</span>" "<span class=\"red-error-info\"> (%s)</span>" % (e["category"], e["info"])) for e in proc["errors"] ]) + "<br />\n" return "%s%s&nbsp;%s" % (errors, rc, command)
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 (double): Amplitude threshold when oscillation is taken into account, for example, when oscillator amplitude is greater than threshold then oscillation is incremented. @return (uint) Number of oscillations of specified oscillator. """ number_oscillations = 0; waiting_differential = False; threshold_passed = False; high_level_trigger = True if (osc_dyn[0][index] > amplitude_threshold) else False; for values in osc_dyn: if ( (values[index] >= amplitude_threshold) and (high_level_trigger is False) ): high_level_trigger = True; threshold_passed = True; elif ( (values[index] < amplitude_threshold) and (high_level_trigger is True) ): high_level_trigger = False; threshold_passed = True; if (threshold_passed is True): threshold_passed = False; if (waiting_differential is True and high_level_trigger is False): number_oscillations += 1; waiting_differential = False; else: waiting_differential = True; return number_oscillations;
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 return sum([int(x) for x in str(n_fact)])
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 str by '/'. split_uri = uri.split('/') # Get the uri prefix and namespace into different variables. prefix = '/'.join(split_uri[0:-1]) namespace = split_uri[-1] vocabulary = namespace.split('#')[-1] return prefix, namespace, vocabulary
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 = box1.left + 1.5 box2_left = box2.left + 1.5 box1_right = box1.right - 1.5 box2_right = box2.right - 1.5 return not (box1_left > box2_right or box2_left > box1_right) # center1 = (box1.right + box1.left) / 2.0 # center2 = (box2.right + box2.left) / 2.0 # return ((center1 >= box2.left and center1 <= box2.right) or # (center2 >= box1.left and center2 <= box1.right))
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 return the index which is time """ positions = set() for index, item in enumerate(A): print("Current Time " + str(index)) print("Position " + str(item)) positions.add(item) print("Positions covered..." + str(positions)) if len(positions) == X: return index return -1
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 transliteration. Returns: string: Transliteration of input word. """ translation = "" for char in word: translation += translateDict.get(char," ") return translation
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,adjacencies)) """ result = [] preordered = set() postordered = set() def unvisited_children(u): return [ w for w in adjacencies(u) if w not in preordered ] for root in vertices: if root in preordered: continue stack = [root] def visit(u): if u in preordered: if u not in postordered: result.append(u) postordered.add(u) else: preordered.add(u) stack.extend([u] + unvisited_children(u)) while stack: visit(stack.pop()) return result
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.append(server) if col=="p": line.append(port) if col=="c": line.append(configfile) if col=="a": line.append(appname) grid.append(line) grid.sort() return grid
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 = false positive # fn = false negative tp = float(sum(1 for x,y in zip(real_labels, predicted_labels) if (x == 1 and y ==1))) fp = float(sum(1 for x,y in zip(real_labels, predicted_labels) if (x == 0 and y ==1))) fn = float(sum(1 for x,y in zip(real_labels, predicted_labels) if (x == 1 and y ==0))) # define precision and recall if ((tp+fp)==0) or ((tp+fn)==0): precision = 0 recall = 0 else: precision = tp/(tp+fp) recall = tp/(tp+fn) # define and return f1-score if precision + recall == 0: f1 = 0 else: f1 = 2 * ((precision*recall)/(precision + recall)) return f1
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, fib) return fib[n]
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 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.' return ''.join(c for c in original_filename if c in valid_chars)
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 > max_len: max_len = i - stub return max_len
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 > n/2: return candidate return -1
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: average = (function(x_array[i]) + function(x_array[i + 1])) / 2 interval = x_array[i + 1] - x_array[i] integral += average * interval i += 1 return integral
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) count += 1 if not count: raise ValueError return sum_of_digits
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 of cell (i, n-1) c - The value of cell (i+1, n-1) Visually: n - 2 ................ n - 1 ........abc..... n .........X...... n + 1 ................ For efficiency, we use the boolean expression from the Karnaugh map of the ruleset: AB 00 01 11 10 --------------- C 0 | X X | 1 | X X X | --------------- """ return (not c and b) or (c and not (a and b))
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": command = "-contrast" elif contrast_selected == "-2": command = "-contrast -contrast" else: command = "" elif contrast == 2: command = "-contrast-stretch " + entry1 + "x" + entry2 + "%" else: command = "" return command
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: layout_kwargs["center"] = kwargs.pop("center") if "scale" in kwargs: layout_kwargs["scale"] = kwargs.pop("scale") placement_kwargs = {} # For the placement object if "scale_ratio" in kwargs: placement_kwargs["scale_ratio"] = kwargs.pop("scale_ratio") # For closest strategy if "subset_size" in kwargs: placement_kwargs["subset_size"] = kwargs.pop("subset_size") if "num_neighbors" in kwargs: placement_kwargs["num_neighbors"] = kwargs.pop("num_neighbors") return layout_kwargs, placement_kwargs
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_component, lng_component)
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 range(n): j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area
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 """ return ' '.join(query.decode().replace('\n', ' ').split())
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(split_line[4]) return {"energy": energy, "ref_ind_xx": ref_ind_xx, "ref_ind_zz": ref_ind_zz, "extinct_xx": extinct_xx, "extinct_zz": extinct_zz}
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. """ u_ac = q*u_dc return u_ac
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 len of the parlist is the good one, then just keep it if parlist is None : parlist = [] if len(parlist) != ngauss: ## If the length is 3, then it is just to be replicated ## ngauss times if len(parlist) == 1: parlist = parlist * ngauss ## Otherwise you need to use the default times the number of Gaussians elif len(default) == ngauss : parlist[:] = default elif len(default) == 1 : parlist[:] = default * ngauss else : print("ERROR: wrong passing of arguments in set_parameters_and_default_1D") print("ERROR: the default has not the right size ", len(default)) return parlist
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 Returns ------- quote : str Compiled string including quote and optional attribution """ quote = "The code is but a canvas to our imagination." if with_attribution: quote += "\n\t- Adapted from Henry David Thoreau" return quote