content
stringlengths
42
6.51k
def RemoveCommentInString(string,comchr): """ remove string after 'comchr' in 'string'. :param str string: string data, :param str comchr: a character, :return: str(str) - string data """ if len(comchr) <= 0: comchr='#' str=string.strip() cm=str.find(comchr) if cm > 0: str=str[:cm]; str=str.strip() return str
def sqrt(i): """ Return the square root of x. """ return i ** (1 / 2)
def _build_influxdb_point(unix_ts_secs, tags, measurement, fields): """ Build the json for an InfluxDB data point. """ timestamp_ns = unix_ts_secs * 1000000000 # convert to nanoseconds point_json = { "measurement": measurement, "tags": tags, "time": timestamp_ns, "fields": {}, } for field_name, field_value in fields: point_json["fields"][field_name] = field_value return point_json
def compare_float( expected, actual, relTol = None, absTol = None ): """Fail if the floating point values are not close enough, with the givem message. You can specify a relative tolerance, absolute tolerance, or both. """ if relTol is None and absTol is None: exMsg = "You haven't specified a 'relTol' relative tolerance " exMsg += "or a 'absTol' absolute tolerance function argument. " exMsg += "You must specify one." raise ValueError(exMsg) msg = "" if absTol is not None: absDiff = abs( expected - actual ) if absTol < absDiff: expectedStr = str( expected ) actualStr = str( actual ) absDiffStr = str( absDiff ) absTolStr = str( absTol ) msg += "\n" msg += " Expected: " + expectedStr + "\n" msg += " Actual: " + actualStr + "\n" msg += " Abs Diff: " + absDiffStr + "\n" msg += " Abs Tol: " + absTolStr + "\n" if relTol is not None: # The relative difference of the two values. If the expected value is # zero, then return the absolute value of the difference. relDiff = abs( expected - actual ) if expected: relDiff = relDiff / abs( expected ) if relTol < relDiff: # The relative difference is a ratio, so it's always unitless. relDiffStr = str( relDiff ) relTolStr = str( relTol ) expectedStr = str( expected ) actualStr = str( actual ) msg += "\n" msg += " Expected: " + expectedStr + "\n" msg += " Actual: " + actualStr + "\n" msg += " Rel Diff: " + relDiffStr + "\n" msg += " Rel Tol: " + relTolStr + "\n" if msg: return msg else: return None
def list_cab (archive, compression, cmd, verbosity, interactive): """List a CAB archive.""" cmdlist = [cmd, '-l'] if verbosity > 0: cmdlist.append('-v') cmdlist.append(archive) return cmdlist
def log2(n): """computes the base 2 logarithm of argument n""" l = 0 while n > 1: n = n >> 1 l = l + 1 return l
def gen_subsets(L): """ Exponential Complexity 1. it's prevalent to think about size of smaller 2. Remember that for a set of size K there are pow(2, k) cases 3. To solve this we need something like pow(2, n-1) + pow(2, n-2) + ... + pow(2, 0) >>> gen_subsets([1,2]) [[], [1], [2], [1, 2]] >>> gen_subsets([1,3]) [[], [1], [3], [1, 3]] >>> gen_subsets([1,2,3]) [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] """ res = [] # empty list if len(L) == 0: return [[]] # list of an empty list smaller = gen_subsets(L[:-1]) # recursive return all subsets without last element extra = L[-1:] # create a list of just the last element new = [] # again, empty list for small in smaller: new.append(small + extra) # for all smaller solutions, add one with last element return smaller + new
def mie(r, eps, sig, m=12, n=6): """Mie pair potential. """ prefactor = (m / (m - n)) * (m / n)**(n / (m - n)) return prefactor * eps * ((sig / r) ** m - (sig / r) ** n)
def formatRecommendation(recommendation_text: str) -> str: """Format the recommendation string by removing the recommendation grade. Arguments: recommendation_text {str} -- Recommendation string to be formatted. Returns: str -- Formatted recommendation string. """ # Splitting on periods recommendation_text_split = recommendation_text.split('.') # Removing recommendation text recommendation_text_split.pop() # Recombining and returning sentence without recommendation return '.'.join(recommendation_text_split) + '.'
def get_go_module_path(package): """assumption: package name starts with <host>/org/repo""" return "/".join(package.split("/")[3:])
def strtobool(text): """ Truthy conversion as per PEP 632 """ tls = str(text).lower().strip() if tls in ['y', 'yes', 't', 'true', 'on', '1']: return True if tls in ['n', 'no', 'f', 'false', 'off', '0']: return False raise ValueError("{} is not convertable to boolean".format(tls))
def tri_dual(Tri): """[summary] Arguments: Tri (type): [description] Returns: [type]: [description] """ a1, a2, a3 = Tri return a2 * a3, a1 * a3, a1 * a2
def read_int32(val): """ Recibe bytes y los convierte a entero """ return int.from_bytes(val,"little")
def wait_until_ready(connections_to_test, timeout=5): """Wait until each connection can be established or the timeout is reached. :param connections_to_test: A list of `(host, port)` tuples :param timeout: Timeout in seconds :return: False if the timeout is reached, True else """ import socket import time print("Starting connectivity test...") print("Given TCP endpoints:", " ".join("{}:{}".format(*host_port) for host_port in connections_to_test)) for conn_tuple in connections_to_test: print("Trying to connect to {}:{}...".format(*conn_tuple), end='') old_time = time.time() while time.time() - old_time < timeout: try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(conn_tuple) except ConnectionRefusedError: pass else: print(" SUCCESS") break else: print(" FAIL") break else: return True return False
def otpChars(data, password, encodeFlag=True): """ do one time pad encoding on a sequence of chars """ pwLen = len(password) if pwLen < 1: return data out = [] for index, char in enumerate(data): pwPart = ord(password[index % pwLen]) newChar = ord(char) + pwPart if encodeFlag else ord(char) - pwPart newChar = newChar + 128 if newChar < 0 else newChar newChar = newChar - 128 if newChar >= 128 else newChar out.append(chr(newChar)) return "".join(out)
def transformation_remove_non_ascii(text, *args): """ :param text: the text to run the transformation on :type text: str :return: the transformed text :type return: str """ return ''.join(i for i in text if ord(i) < 128)
def flags(value): """Return a list of the set binary flags. For example: [2, 16, 64] """ flags = [] while value: _current_bit = value & (~value+1) flags.append(_current_bit) value ^= _current_bit return flags
def find_extra_inferred_properties(spec_dict: dict) -> list: """Finds if there are any inferred properties which are used. Args: spec_dict: Dict obj containing configurations for the import. Returns: List of properties that appear in inferredSpec but are not part of 'pvs' section. """ ret_list = [] if 'inferredSpec' in spec_dict: for property_name in spec_dict['inferredSpec']: if property_name not in spec_dict['pvs']: ret_list.append(property_name) return ret_list
def is_statement_in_list(statement, statement_list): """Return True of given statement is equivalent to on in a list Determines whether the statement is equivalent to any statement in the given list of statements, with equivalency determined by Statement's equals method. Parameters ---------- statement : indra.statements.Statement The statement to compare with statement_list : list[indra.statements.Statement] The statement list whose entries we compare with statement Returns ------- in_list : bool True if statement is equivalent to any statements in the list """ for s in statement_list: if s.equals(statement): return True return False
def rgb_to_hex(rgb): """Receives (r, g, b) tuple, checks if each rgb int is within RGB boundaries (0, 255) and returns its converted hex, for example: Silver: input tuple = (192,192,192) -> output hex str = #C0C0C0""" for num in rgb: if not 0<= num <= 255: raise ValueError r = str(hex(rgb[0]))[2:].upper().zfill(2) g = str(hex(rgb[1]))[2:].upper().zfill(2) b = str(hex(rgb[2]))[2:].upper().zfill(2) return f'#{r}{g}{b}' pass
def is_excluded(path, dirs): """ if path is excluded in list of dirs/files :param path: path to check for exclude :param dirs: list of excludes :return: Boolean """ for directory in dirs: if path.startswith(directory): return True return False
def mean(values, empty=0): """ calculates mean of generator or iterator. Returns `empty` in case of an empty sequence """ n, mean = 0, 0 for value in values: n += 1 mean += (value - mean) / n return mean if n > 0 else empty
def fields_to_md(field_names): """ Create a Markdown representation of the given list of names to use in Swagger documentation. :param field_names: the list of field names to convert to Markdown :return: the names as a Markdown string """ *all_but_last, last = field_names all_but_last = ', '.join([f'`{name}`' for name in all_but_last]) return f'{all_but_last} and `{last}`'
def short_str(s: str, length=35) -> str: """return a copy of s. If the length of s > length, return part of it.""" if len(s) > length: return s[:length - 3] + '...' else: return s
def bold(text: str): """Return bolded text""" return f"**{text}**"
def create_ngrams(kw_iterable, max_n=False): """takes a list of keywords and computes all possible ngrams e.g. in> ['nice', 'red', 'wine'] out> [ ('nice',), ('red',), ('wine',), ('nice', 'red'), ('red', 'wine'), ('nice', 'red', 'wine') ] """ kwCount = len(kw_iterable) output = [] for n in reversed(range(kwCount+1)[1:]): if n <= max_n: for tokenIndex in range(kwCount-n+1): output.append(tuple(kw_iterable[tokenIndex:tokenIndex+n])) return output
def _infection_indicator( health_states, infected_state_index): """Returns a binary vector that indicates whether individuals are infected.""" return [int(state == infected_state_index) for state in health_states]
def gen_cluster_1d(data_list, number_class): """ Cluster one dimension data with Jenks Natural Breaks. https://stackoverflow.com/questions/28416408/scikit-learn-how-to-run-kmeans-on-a-one-dimensional-array """ data_list.sort() mat1 = [] for i in range(len(data_list) + 1): temp = [] for j in range(number_class + 1): temp.append(0) mat1.append(temp) mat2 = [] for i in range(len(data_list) + 1): temp = [] for j in range(number_class + 1): temp.append(0) mat2.append(temp) for i in range(1, number_class + 1): mat1[1][i] = 1 mat2[1][i] = 0 for j in range(2, len(data_list) + 1): mat2[j][i] = float('inf') v = 0.0 for l in range(2, len(data_list) + 1): s1 = 0.0 s2 = 0.0 w = 0.0 for m in range(1, l + 1): i3 = l - m + 1 val = float(data_list[i3 - 1]) s2 += val * val s1 += val w += 1 v = s2 - (s1 * s1) / w i4 = i3 - 1 if i4 != 0: for j in range(2, number_class + 1): if mat2[l][j] >= (v + mat2[i4][j - 1]): mat1[l][j] = i3 mat2[l][j] = v + mat2[i4][j - 1] mat1[l][1] = 1 mat2[l][1] = v k = len(data_list) kclass = [] for i in range(number_class + 1): kclass.append(min(data_list)) kclass[number_class] = float(data_list[len(data_list) - 1]) count_num = number_class while count_num >= 2: # print "rank = " + str(mat1[k][count_num]) idx = int((mat1[k][count_num]) - 2) # print "val = " + str(data_list[idx]) kclass[count_num - 1] = data_list[idx] k = int((mat1[k][count_num] - 1)) count_num -= 1 return kclass
def fetch_param_value(response, key, key_field): """Fetch the specified key from list of dictionary. Key is identified via the key field.""" for param in response: if param[key_field] == key: return param["Value"]
def to_key(val: dict) -> str: """Convert option name to arg key. e.g. --hello-world -> hello_world""" return val['names'][0][:2].replace('-', '') + val['names'][0][2:].replace('-', '_')
def holes(refWindow, intervals): """ Given a window and a set of disjoint subintervals, return the "holes", which are the intervals of the refWindow not covered by the given subintervals. """ winId, winStart, winEnd = refWindow output = [] intervals = sorted(intervals) lastE = winStart for (s, e) in intervals: if s > lastE: output.append((lastE, s)) lastE = e if lastE < winEnd: output.append((lastE, winEnd)) return output
def sequence_nth(first_term,term_number,common_difference): """Usage: Find the nth term of a sequence""" return first_term+(common_difference*(term_number-1))
def ParseManagedZoneForwardingConfig(server_list, messages): """Parses list of forwarding nameservers into ManagedZoneForwardingConfig. Args: server_list: (list) List of IP addreses to use as forwarding targets for the DNS Managed Zone. messages: (module) Module (generally auto-generated by the API build rules) containing the API client's message classes. Returns: A messages.ManagedZoneForwardingConfig instance populated from the given command line arguments. """ if not server_list: return None if server_list == ['']: # Handle explicit unset case for update return messages.ManagedZoneForwardingConfig(targetNameServers=[]) target_servers = [ messages.ManagedZoneForwardingConfigNameServerTarget(ipv4Address=name) for name in server_list ] return messages.ManagedZoneForwardingConfig(targetNameServers=target_servers)
def smooth(bgn_fin_pairs, n_smooth): """Smooth the [bgn, fin] pairs. """ new_bgn_fin_pairs = [] if len(bgn_fin_pairs) == 0: return [] [mem_bgn, fin] = bgn_fin_pairs[0] for n in range(1, len(bgn_fin_pairs)): [pre_bgn, pre_fin] = bgn_fin_pairs[n - 1] [bgn, fin] = bgn_fin_pairs[n] if bgn - pre_fin <= n_smooth: pass else: new_bgn_fin_pairs.append([mem_bgn, pre_fin]) mem_bgn = bgn new_bgn_fin_pairs.append([mem_bgn, fin]) return new_bgn_fin_pairs
def pretty_extract_device(ident): """ change fusions_uv to Fusions UV, etc """ n = "" if ident: args = ident.split("_") if args[-1] in ("uv, co2"): n = " ".join([a.capitalize() for a in args[:-1]]) n = "{} {}".format(n, args[-1].upper()) else: n = " ".join([a.capitalize() for a in args]) return n
def extract_pipeline_name(pipeline): """Extracts the name of a configured pipeline :param pipeline: Pipeline configuration entity :type pipeline: dict :returns: The name of the given pipeline :rtype: str """ return list(pipeline.keys())[0]
def name2Label(name): """Convert label vector into name of piece""" return ' KQRBNPkqrbnp'.find(name)
def depth(tag): """Returns the depth of an ITag or str. A str has depth 0, ITag([]) has depth 0, ITag(['str']) has depth 1. Args: tag (ITag or str): The ITag or string to get the depth of. """ if type(tag) is str: return 0 if len(tag.children) == 0: return 0 return max([depth(t) for t in tag.children])
def build_filename(fname: dict) -> str: """ returns filename given a dictionary with name components """ filename = fname["name"] assert "out_src" in fname, "Named_dict (fname) does not contain 'out' keys." filename = filename + "." + fname["out_src"] + "-" + fname["out_tgt"] + "." + fname["out_ext"] return filename
def pax_file(x): """Return URL to file hosted in the pax repository master branch""" return 'https://raw.githubusercontent.com/XENON1T/pax/master/pax/data/' + x
def get_url(state_code, ac_code): """ :param state_code: 3 digit alphanumeric code :param ac_code: numeric :return: """ url = f"http://results.eci.gov.in/pc/en/constituencywise/Constituencywise{state_code}{ac_code}.htm?ac={ac_code}" return url
def getGridMarker(location, grid): """Return marker in grid at given location""" return grid[location[0]][location[1]]
def conv_bright_lib_to_ha(brightness) -> int: """Convert library brightness scale 0-16 to HA scale 0-255.""" brightness = int(brightness) * 16 if brightness > 255: # force big numbers into 8-bit int range brightness = 255 return brightness
def average(values): """Returns the average of the student's grades""" return sum(values) / len(values)
def solution(A): """ Returns the missing number from array A [1...N+1] with len(A) = N Should work in O(N) :param A: Input array (int) :returns: Missing value (int) :rtype: Integer """ # write your code in Python 3.6 if len(A) == 0: return 1 A.sort() ind = 1 while (A[ind - 1] == ind): if (ind == len(A)): return ind + 1 ind += 1 return ind
def satellites_used(feed): """Counts number of satellites used in calculation from total visible satellites Arguments: feed feed=data_stream.satellites Returns: total_satellites(int): used_satellites (int): """ total_satellites = 0 used_satellites = 0 if not isinstance(feed, list): return 0, 0 for satellites in feed: total_satellites += 1 if satellites['used'] is True: used_satellites += 1 return total_satellites, used_satellites
def as_dict(val, key): """Construct a dict with a {`key`: `val`} structure if given `val` is not a `dict`, or copy `val` otherwise.""" return val.copy() if isinstance(val, dict) else {key: val}
def get_channels_first_permutation(spatial): """Returns a permutation to make a (N, ..., C) array into (N, C, ...).""" return [0, spatial + 1] + list(range(1, spatial + 1))
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: ? Space Complexity: ? """ if num == 0: raise ValueError arr = [0,1,1] for i in range(3,num + 1): r = arr[arr[i-1]]+arr[i-arr[i-1]] arr.append(r) string_array = [] for num in arr[1:]: string_array.append(str(num)) string_array = ' '.join(string_array) return string_array
def is_v6(ip_string: str) -> bool: """Returns True if a given IP string is v6, False otherwise.""" return ":" in ip_string
def pem2b64(pem): """ Strip the header and footer of a .pem. BEWARE: Won't work with explanatory strings above the header. @params pem A string representing the pem """ # XXX try to use cryptography parser to support things like # https://tools.ietf.org/html/rfc7468#section-5.2 pem = pem.decode('ascii') return '\n'.join(pem.strip().split('\n')[1:-1])
def parse_line(line): """ Parses a string line to a tuple :param line: :return: """ from ast import literal_eval try: entry = literal_eval(line) if not isinstance(entry, tuple): raise Exception("Input parsed, but is not a tuple") except: raise Exception("Could not evaluate (parse) input into an object") return entry
def init_table(code_size,char_size): """code_size - bits per code, maximum length of string_table char_size - how many bits for a character (ie, 256 for ascii)""" string_table = [] for i in range(char_size): string_table.append([i]) string_table.append("CLEAR") string_table.append("END") return string_table
def clean_nested_colname(s): """ Removes map name for MapType columns. e.g. metadata.SeriesInstanceUID -> SeriesInstanceUID """ return s[s.find('.')+1:]
def convert_evaluations(evaluations): """ Converts the evaluation to a dictionary of strings and floats. :param evaluations: the evaluations :type evaluations: Dict[TheoryMetric, float] :return: the evaluations :rtype: Dict[str, float] """ converted = map(lambda x: (str(x[0]), x[1]), evaluations.items()) return dict(converted)
def get_video_play_url(video): """ Find playback_url for video target named 'high', in case there isn't one, returns the first target on the list. Change this to the specific target name you wish to play. """ if len(video['targets']) > 0: target = next((target for target in video['targets'] if target['name'] == 'high'), video['targets'][0]) return target['playback_url'] else: return ''
def shell_esc(txt): """Return a double-quoted string, with all special characters properly escaped.""" new = str(txt) # Escape dollar signs (variable references) new = new.replace("$", "\\$") # Escape double quotes. new = new.replace('"', '\\"') # Escape back-ticks new = new.replace('`', '\\`') return '"' + new + '"'
def bubble_sort(nums_array: list) -> list: """ Bubble Sort Algorithm :param nums_array: list :return nums_array: list """ is_sorted = True for i in range(0, len(nums_array) - 1): for j in range(0, len(nums_array) - i - 1): if nums_array[j] > nums_array[j + 1]: is_sorted = False temp = nums_array[j] nums_array[j] = nums_array[j + 1] nums_array[j + 1] = temp if is_sorted: break return nums_array
def naive_width2z(width): # assert width <= 0.01 """ a naive way to map width to z axis position :param width: width of a corresponding control point :return: the z axis position """ assert width >= 0 return 0.01 - width
def _get_keywords(line, num=2): """Gets the first num keywords of line""" return line.lower().split(None, num)
def segregate_features(feature_list): """ This function segregates features corresponding to the same query given a list of extracted features from a document. The list returned is a list of lists containing features corresponding to the same query """ processed=[] # This list holds the query indices which have been segregated from the feature_list argument segregated_feat=[] # List to be returned count=0 # Count of features segregated for feature in feature_list: if feature.queryindex not in processed: cur_idx=feature.queryindex cur_query_list=[] for feature in feature_list: if feature.queryindex==cur_idx: cur_query_list.append(feature) segregated_feat.append(cur_query_list) processed.append(cur_idx) return segregated_feat
def percentformat(x, pos): """ Generic percent formatter, just adds a percent sign """ if (x==0): return "0%" if (x<0.1): return ('%4.3f' % (x)) + "%" if (x<1): return ('%3.2f' % (x)) + "%" if (x<5): return ('%2.1f' % (x)) + "%" return ('%1.0f' % x) + "%"
def sum_digits(num: int): """ Suma los digitos de un numero de 2 cifras """ ult_dig = num % 10 pri_dig = num // 10 return pri_dig + ult_dig
def tags_list_to_string(tags): """ Given a list of ``tags``, turn it into the canonical string representation (space-delimited, enclosing tags containing spaces in double brackets). """ tag_string_list = [] for tag in tags: if ' ' in tag: tag = '[[%s]]' % tag tag_string_list.append(tag) return u' '.join(tag_string_list)
def _GetPerfDashboardRevisionsWithProperties( got_webrtc_revision, got_v8_revision, git_revision, main_revision, point_id=None): """Fills in the same revisions fields that process_log_utils does.""" versions = {} versions['rev'] = main_revision versions['webrtc_git'] = got_webrtc_revision versions['v8_rev'] = got_v8_revision versions['git_revision'] = git_revision versions['point_id'] = point_id # There are a lot of "bad" revisions to check for, so clean them all up here. for key in versions.keys(): if not versions[key] or versions[key] == 'undefined': del versions[key] return versions
def _millerRabinIterations(w): """Calculates the number of Miller-Rabin iterations to do for w.""" #return max( 5, int(22 * math.log(w.bit_length())) - 112 ) return 10
def fix_mounts(report_city): """ Changes Mt. -> Mount """ city_components = report_city.split(" ") if city_components[0].strip().lower() == "mt.": city_components[0] = "Mount" return " ".join(city_components)
def lineCount(poemString): """ This function returns number of lines from the poem string. """ lines = poemString.splitlines() if "" in lines: lines.remove("") return len(lines)
def clean_name_list(name_list: list) -> list: """Clean redundant name from the name list. Args: name_list: The name list. Returns: return_name_list: The cleaned name list. """ return_name_list = [] for name in name_list: return_name = [name[0], name[1]] if return_name not in return_name_list: return_name_list.append(return_name) return return_name_list
def find_lowest_common_in_paths(path_a, path_b): """Find the element with the smallest height that appears in both given lists. The height of an element here is defined as the maximum over the indices where it occurs in the two lists. For example if path_a = [2, 3, 5] and path_b = [5, 6, 2] then the height of element 2 is max(0 + 2) = 2 since the element 2 occurs in position 0 in the first list and position 2 in the second. Args: path_a: A list. path_b: A list. Returns: lowest_common: The element with the smallest 'height' that is common between path_a and path_b. height: The height of lowest_common, computed as described above. """ # Maps elements that appear in both lists to their heights. common_elements, heights = [], [] for element in path_a: if element in path_b: height = max(path_a.index(element), path_b.index(element)) common_elements.append(element) heights.append(height) if not heights: raise ValueError('No common nodes in given paths {} and {}.'.format( [n.words for n in path_a], [n.words for n in path_b])) # Find the lowest common element. # There may be multiple common ancestors that share the same minimal height. # In that case the first one appearing in common_elements will be returned. min_height = min(heights) argmin_height = heights.index(min_height) lowest_common = common_elements[argmin_height] assert min_height > 0, ('The lowest common ancestor between two distinct ' 'leaves cannot be a leaf.') return lowest_common, min_height
def divisor_game(N: int) -> bool: """ This is a mathematical problem. odd numbers are only divisible by odd numbers. If player starts with even number he can always choose 1 as it's next number remaining player 2 with odd number. In extreme scenario each player can reduce 1 at its turn resulting that if the start player has odd number he losses and wins for even number """ return N % 2 == 0
def extract_key_values_from_dict_list(key_name, dict_list, exclude_if_present=None, convert_to_string=True): """This function extracts values for a specific key from a list of dictionaries. :param key_name: The name of the dictionary key from which to extract the value(s) :type key_name: str :param dict_list: The list of dictionaries (or single dictionary) from which to extract the value(s) :type dict_list: list, dict :param exclude_if_present: Will skip extracting the key value if this given key is also present (Optional) :type exclude_if_present: str, None :param convert_to_string: Determines if the values should be converted to string format (``True`` by default) :type convert_to_string: bool :returns: A list of values extracted from the dictionary list for the given key :raises: :py:exc:`TypeError` """ value_list, dict_list = [], [dict_list] if isinstance(dict_list, dict) else dict_list for single_dict in dict_list: if key_name in single_dict: skip_dict = True if exclude_if_present and exclude_if_present in single_dict else False if not skip_dict: key_value = str(single_dict.get(key_name)) if convert_to_string else single_dict.get(key_name) value_list.append(key_value) return value_list
def is_value_2(for_): """check if for_["value"] == 2""" v = for_.get("value", None) return v == 2
def values_list_repr(values): """Concatenate a list of values to a readable string. """ return "'{}' or '{}'".format("', '".join([str(i) for i in values[:-1]]), values[-1])
def ptp(m): """ptp(m) returns the maximum - minimum along the first dimension of m. """ return max(m)-min(m)
def strSQLite(string): """ Sanitizes input for SQLite TEXT fields by converting to string and replacing each single quote (') with two single quotes ('') """ return str(string).replace(r"'", "''")
def get_query(string, pos=1): """Get query parameter of a URL.""" try: return string.split("?")[pos] except IndexError: if pos == 1: return "" else: return string
def bottom_up(rv, F, atoms=False, nonbasic=False): """Apply ``F`` to all expressions in an expression tree from the bottom up. If ``atoms`` is True, apply ``F`` even if there are no args; if ``nonbasic`` is True, try to apply ``F`` to non-Basic objects. """ args = getattr(rv, 'args', None) if args is not None: if args: args = tuple([bottom_up(a, F, atoms, nonbasic) for a in args]) if args != rv.args: rv = rv.func(*args) rv = F(rv) elif atoms: rv = F(rv) else: if nonbasic: try: rv = F(rv) except TypeError: pass return rv
def bytes_startswith(x: bytes, prefix: bytes) -> bool: """Does given bytes object start with the subsequence prefix? Compiling bytes.startswith, with no range arguments, compiles this function. This function is only intended to be executed in this compiled form. Args: x: The bytes object to examine. prefix: The subsequence to look for. Returns: Result of check. """ if len(x) < len(prefix): return False index = 0 for i in prefix: if x[index] != i: return False index += 1 return True
def minus(a, b): """ Returns the assymetrical difference of set 'a' to set 'b' (a minus b). In plain english: Remove all the items in 'a' from 'b'. Return 'a'. (Order matters.) Minus is set_a.difference(set_b). The nomenclature 'difference is not linguistically descriptive (at least to a layman) so the method 'minus' was used, as the meaning of 'minus' conveys the result of the function more properly (once again... at least to the layman). """ return a.difference(b)
def duration_parser(delta: str) -> str: """Parse time duration string into a float-like string. Args: delta (str): The time duration formatted as '00:01:45.292135' Returns: str: The time duration as seconds formatted as float-like string """ t, f = delta.split(".") h, m, s = t.split(":") return f"{int(h) * 60 * 60 + int(m) * 60 + int(s)}.{f}"
def set_table3_field(str_fields, ifield, value): """ ifield is 1 based """ return str_fields[:ifield-1] + value + str_fields[ifield:]
def add_into_dict(input_key, incon_tuple, incon_dict): """ Two step: 0. under the same backends pair * 1. the same input, choose largest. 2. different inputs with small distance. Do not update """ if input_key not in incon_dict.keys() or incon_dict[input_key][1] < incon_tuple[1]: incon_dict[input_key] = incon_tuple return incon_dict
def un_pad_and_decode(padded: bytes) -> str: """ Un-pads the given data sequence by stripping trailing null characters and recodes it at utf-8. """ return padded.rstrip(b"\0").decode("utf-8")
def subreadNamesToZmwCoverage(qnames): """From list of PacBio subread names, report number of ZMWs represented QNAME of a PacBio subread has the following convention: {movieName}/{holeNumber}/{qStart}_{qEnd} We want to count the number of holes (ZMWs), because a given hole may result in multiple subreads. Parameters ---------- qnames : list read names of PacBio subreads Returns ------- int Number of ZMWs represented by the above subreads """ zmwnames = ["/".join(n.split("/")[0:2]) for n in qnames] zmwnames = set(zmwnames) return(len(zmwnames))
def get_sorted_request_variable(variable): """ Get a data structure for showing a sorted list of variables from the request data. """ try: if isinstance(variable, dict): return {"list": [(k, variable.get(k)) for k in sorted(variable)]} else: return {"list": [(k, variable.getlist(k)) for k in sorted(variable)]} except TypeError: return {"raw": variable}
def safe_decode(b, encs=(None, 'utf-8', 'latin-1')): """Tries to decode a bytes array in a few different ways.""" enc, encs = encs[0], encs[1:] try: s = b.decode() if enc is None else b.decode(enc) except UnicodeDecodeError: if len(encs) == 0: raise s = safe_decode(b, encs) return s
def one_hot_2_label(int_to_vector_dict): """ Converts integer to one_hot dictionary to a one_hot to integer dictionary. dictionary Arguments --------- one_hot_ndarray : A numpy.ndarray Contains one-hot format of class labels. Returns ------- tuple_to_int_dict : dictionary keys are tuples with one-hot format and values are integer class labels. """ tuple_to_int_dict = dict([(tuple(val),key) for key, val in int_to_vector_dict.items()]) return tuple_to_int_dict
def make_metric(name): """ return a template metric """ return { "type": "Metric", "name": name, "value": "", "units": "", "rating": "", "notes": "", "comment": "", }
def get_prev_element(array, index): """ get the prev element in the array """ if index == 0: return len(array) - 1 return index - 1
def is_ipynb_file(file_name: str) -> bool: """ Return whether a file is a jupyter notebook file. """ return file_name.endswith(".ipynb")
def propagate_difference(tree: dict, root_node: str, start_node: str, diff: int): """Subtracts diff from parent(p) of start_node, parent(pp) of p, parent of pp.. upto the root node. Additionally deletes the subtree rooted at start_node from tree.Additionally, removes start_node from 'replies' of its parent. """ if tree[start_node]["parent_id"] == "": for k in list(tree.keys()): tree.pop(k) return tree tree[tree[start_node]["parent_id"]]["replies"].remove(start_node) init_start_node = start_node while True: start_node = tree[start_node]["parent_id"] tree[start_node]["subtree_size"] -= diff if start_node == root_node: break def delete_subtree(tree: dict, start_node: str): for reply_id in tree[start_node]["replies"]: delete_subtree(tree, reply_id) tree.pop(start_node) delete_subtree(tree, init_start_node) return tree
def compute_yield(x): """ Compute yield as measured with UMIs for a droplet x. """ return x["az_total"]*x["nb_hp"]*10.0/x["hp_total"]
def build_message(missing_scene_paths, update_stac): """ """ message_list = [] for path in missing_scene_paths: landsat_product_id = str(path.strip("/").split("/")[-1]) if not landsat_product_id: raise Exception(f'It was not possible to build product ID from path {path}') message_list.append( { "Message": { "landsat_product_id": landsat_product_id, "s3_location": str(path), "update_stac": update_stac } } ) return message_list
def nonlinear_limb_darkening(mu, c0=0., c1=0., c2=0., c3=0.): """ Define non-linear limb darkening model with four params. """ return (1. - (c0 * (1. - mu**0.5) + c1 * (1. - mu) + c2 * (1. - mu**1.5) + c3 * (1. - mu**2)))
def partition(predicate, sequence): """ Takes a predicate & a sequence of items, and applies the predicate to each of them. Returns a tuple with the first item being the list of matched items, and the second being the list of not matched items. """ match, nomatch = [], [] for item in sequence: if predicate(item): match.append(item) else: nomatch.append(item) return match, nomatch
def _select_plottables(tasks): """ Helper function to select plottable tasks. Used inside the doNd functions. A task is here understood to be anything that the qc.Loop 'each' can eat. """ # allow passing a single task if not hasattr(tasks, '__iter__'): tasks = (tasks,) # is the following check necessary AND sufficient? plottables = [task for task in tasks if hasattr(task, '_instrument')] return tuple(plottables)
def get_distribution(skill, rounds, dist): """ Computes the full distribution of possible scores given a number of rounds left and a skill value for the team """ if rounds == 0: return dist dist[19-rounds] = dist[18-rounds] * skill for score in sorted(dist, reverse=True)[1:-1]: prob = (dist[score] * (1.0 - skill)) + (dist[score-1] * skill) dist[score] = prob dist[0] *= (1.0 - skill) return get_distribution(skill, rounds - 1, dist)
def smartindent(s, width=1, indentfirst=False, indentchar=u'\t'): """Return a copy of the passed string, each line indented by 1 tab. The first line is not indented. If you want to change the number of tabs or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja {{ mytext|indent(2, true, 'x') }} indent by two 'x' and indent the first line too. """ indention = indentchar * width rv = (u'\n' + indention).join(s.splitlines()) if indentfirst: rv = indention + rv return rv
def transform_contact_details(data): """ Takes a dictionary of contact details and flattens every entry to {key: {label: label, value: value} . """ transformed_data = {} for key, value in data.items(): if 'label' in value: transformed_data[key] = value else: for key2, value2 in value.items(): transformed_data['%s_%s' % (key, key2)] = {'label': key2, 'value': value2} return transformed_data