content
stringlengths
42
6.51k
def _findpath(dct, key, path=()): """ Find the first path to a given key in a nested dict Maybe update to this if the dict gets too big to recurse: http://garethrees.org/2016/09/28/pattern/ """ for k, v in dct.items(): if k == key: return True, path + (k,) if isinstance(v, dict): found, pth = _findpath(v, key, path + (k,)) if found: return True, pth return False, None
def clean_primary_types(val): """UDF function to fix duplicate primary types""" if val in ("NON - CRIMINAL", "NON-CRIMINAL", "NON-CRIMINAL (SUBJECT SPECIFIED)"): return "NON-CRIMINAL" if "NARCOTIC" in val: return "NARCOTICS" return val
def _sort_key(name): """Sorting helper for members of a directory.""" return name.lower().lstrip("_")
def kubekins(tag): """Return full path to kubekins-e2e:tag.""" return 'gcr.io/k8s-testimages/kubekins-e2e:%s' % tag
def counting_sort(arr: list, exp: int, base: int = 10) -> list: """ Modified counting sort, where k = base """ length = len(arr) output = [None] * length count_arr = [0] * base for el in arr: index = el // exp count_arr[index % base] += 1 for i in range(1, 10): count_arr[i] += count_arr[i - 1] for el in arr[::-1]: index = el // exp output[count_arr[index % base] - 1] = el count_arr[index % base] -= 1 return output
def _get_file_icon(item): """returns icon class based on file format""" extension = item.split('.')[-1].lower() if extension in ['xml', 'txt', 'json']: return "file-text" if extension in ['csv', 'xls']: return "bar-chart-o" if extension in ['shp', 'geojson', 'kml', 'kmz']: return "globe" return "file"
def response_from_message(message): """ Helper to wrap a message string into the minimum acceptable Alexa response JSON. """ return { 'version': '1.0', 'response': { 'outputSpeech': { 'type': 'PlainText', 'text': message, } } }
def accepts(source): """ Do we accept this source? """ if source["type"] == "github": return True return False
def _get_read_limits(start, end, interval, info): """ Given start time, end time and interval for reading data, determines limits to use. info is the dict returned by rdhdr end of -1 means end of record. If both end and interval are given, choose earlier limit of two. start and end are returned as samples. Example: >>> _get_read_limits(0, 2, -1, {'samp_count':100, 'samp_freq':10}) (0, 20) >>> _get_read_limits(0, 2, 3, {'samp_count':100, 'samp_freq':10}) (0, 20) >>> _get_read_limits(0, 4, 2, {'samp_count':100, 'samp_freq':10}) (0, 20) >>> _get_read_limits(0, 105, -1, {'samp_count':100, 'samp_freq':10}) (0, 100) >>> _get_read_limits(-1, -1, -1, {'samp_count':100, 'samp_freq':10}) (0, 100) """ start *= info['samp_freq'] end *= info['samp_freq'] if start < 0: # If start is negative, start at 0 start = 0 if end < 0: # if end is negative, use end of record end = info['samp_count'] if end < start: # if end is before start, swap them start, end = end, start interval_end = start + interval * info['samp_freq'] # end det by interval if interval_end < start: interval_end = info['samp_count'] end = min(end, interval_end, info['samp_count']) # use earlier end return int(start), int(end)
def JsonComplexEncoder(obj): """ Extends json.loads() to convert bytes to string """ if isinstance(obj, bytes): return str(obj) else: return obj
def mean_normalize(x, mean_x, max_x, min_x): """ Mean normalization of input x, given dataset mean, max, and min. >>> mean_normalize(10, 10, 15, 5) 0.0 >>> mean_normalize(15, 20, 30, 10) -0.25 Formula from: https://en.wikipedia.org/wiki/Feature_scaling """ # If min=max, all values the same, so return x. if (max_x - min_x) == 0: return x else: return ( (x-mean_x) / (max_x - min_x) )
def toy(n=0): """A nice toy. """ print(f"Toys are fun, I will give you {n+1} toys!") return n+1
def score(vals, weights): """ Score the values and weights. Args: vals (dict): A dict of words and their corresponding proximity bias. weights (dict): The weights of an edge according to GIPE metric. Returns: The final computed GIPE score """ score = 0 sum = 0 for v in vals: try: score += weights[v] * vals[v] sum += weights[v] except: aux_w = 1 #By default, the weight is 1 (1 is the lowest possible weight, means lowest "penalty") score += vals[v] * aux_w sum += aux_w score /= sum return score
def titleize(s: str) -> str: """ Titleizes a string, aka transforms it from underscored to English title format """ s = s.replace('_', ' ') words = s.split(' ') new_words = [ w[0].upper() + w[1:] for w in words ] return ' '.join(new_words)
def clean_music_name(music_name): """ DESCRIPTION: clean extra info from music name INPUT: music_name (str) OUTPUT: music_name (str) """ breaking_substring_list = [ ' (feat.', ' (with', ] for substring in breaking_substring_list: if substring in music_name: breaking_point = music_name.find(substring) music_name = music_name[:breaking_point] return music_name
def _escape_string(string): """Escape SQL string.""" string = string.replace("'", "''") return f"'{string}'"
def get_slurm_script_gpu(output_dir, command): """Returns contents of SLURM script for a gpu job.""" return """#!/bin/bash #SBATCH -N 1 #SBATCH --ntasks-per-node=1 #SBATCH --ntasks-per-socket=1 #SBATCH --gres=gpu:tesla_p100:1 #SBATCH --cpus-per-task=4 #SBATCH --mem=64000 #SBATCH --output={}/slurm_%j.out #SBATCH -t 05:59:00 #module load anaconda3 cudatoolkit/10.0 cudnn/cuda-10.0/7.3.1 #source activate yumi {} """.format( output_dir, command )
def prediction_stats(ans, predicts): """Calculates Accuracy of prediction against ground truth labels""" total_correct = 0 for i in range(len(predicts)): if ans[i] == predicts[i]: total_correct = total_correct + 1 return total_correct / float(len(predicts))
def r3(a, k): """ split at pos#k and swap halves a shorter ver. of r0 """ n = len(a) k = k % n return a[n-k:] + a[:n-k]
def rename_countries(country): """ Rename country. Removes abreviations in country names. - country: country to be renamed + return: renamed country """ if country == "CAN": return "Canada" elif country == "D.R.": return "Dominican Republic" elif country == "P.R.": return "Puerto Rico" elif country == "V.I.": return "British Virgin Islands" else: return country
def _combine(mappings): """Combine mappings. Doesn't account for nested behavior""" return {k: v for d in mappings for k, v in d.items()}
def wps_to_words(wps): """ input wp sequence and output word sequence For example: this is a g@@ oo@@ d day -> this is a good day """ s = '' for wp in wps: if wp.endswith('@@'): s += wp[0:-2] else: s += wp + ' ' return s.split()
def artifact_version_unsupported(artifact_version, supported_major_version): """artifact_version_unsupported message""" return "The decisioning artifact version ({}) is not supported. " \ "This library is compatible with this major version: " \ "{}".format(artifact_version, supported_major_version)
def get_vertex_names_from_indices(mesh, indices): """ Returns a list of vertex names from a given list of face indices :param mesh: str :param indices: list(int) :return: list(str) """ found_vertex_names = list() for index in indices: vertex_name = '{}.vtx[{}]'.format(mesh, index) found_vertex_names.append(vertex_name) return found_vertex_names
def IsNegativeResult(line): """Return True if line should be removed from the expected results.""" return line.startswith("@remove ")
def resolve_pipeline(plan): """ :type plan: List[Tuple[str, str]] :param plan: [(can_id, tag), ...] :rtype: List[Tuple[List[str], str]]] """ pipeline_change_set = list() job = ([], None) previous_env = None for tier_name, tier_env in plan: if tier_env != previous_env: pipeline_change_set.append(job) previous_env = tier_env job = ([tier_name, ], tier_env) else: job[0].append(tier_name) pipeline_change_set.append(job) pipeline_change_set = pipeline_change_set[1:] dct = dict() pipeline = list() for tier_list, tier_env in pipeline_change_set: if tier_env in dct: dct[tier_env].extend(tier_list) else: dct[tier_env] = tier_list pipeline.append((list(dct[tier_env]), tier_env)) return pipeline
def _get_enums_dict(enums): """ Parsing Enums into proper dict format Args: enums: list Returns: dict """ enums_dict = {} for enum in enums: long_name = enum.get('longName') enums_dict.update({long_name: enum.get('values')}) return enums_dict
def PDMS2Dec (decst, sep=":"): """ Convert a declination string to degrees Returns dec in deg decst Dec string as "dd:mm:ss.s" sep sympol to use to separate components instead of ":" """ ################################################################ pp = decst.split(sep) if len(pp)>0: deg = int(pp[0]) else: deg = 0 if len(pp)>1: min = int(pp[1]) else: min = 0 if len(pp)>2: ssec = float(pp[2]) else: ssec = 0.0 dec = abs(deg) + min/60.0 + ssec/3600.0 if pp[0].find("-") >=0: dec = -dec return dec # end PDec2DMS
def convert_to_local_image_name(image: str) -> str: """NOTE: get available image name For example, `abeja-inc/all-cpu:19.04` locates inside Platform. and cannot access it from outside of Platform. Therefore let use same images in DockerHub which name starts with `abeja/`. """ if image.startswith('abeja-inc/'): return image.replace('abeja-inc/', 'abeja/', 1) return image
def replace_nbsp(text: str) -> str: """Replace all non-breaking space symbols with a space symbol.""" return text.replace("\u00a0", "\u0020")
def PossibleChains(equivalences, fixed_names, chain_name): """Searches for all the identical chains to chain_name that are already included in the complex. Arguments: equivalences -- dictionary with chain IDs as keys and the equivalent IDs as values fixed_names -- list of chains IDs that are already included in the complex chain_name -- string representing the chain ID Returns: List containing the chain IDs """ possible_chains = [] for chain in equivalences: if chain_name in equivalences[chain]: for element in equivalences[chain]: if element in fixed_names: possible_chains.append(element) return possible_chains
def _LJ_rminepsilon_to_ab(coeffs): """ Convert rmin/epsilon representation to AB representation of the LJ potential """ A = coeffs['epsilon'] * coeffs['Rmin']**12.0 B = 2 * coeffs['epsilon'] * coeffs['Rmin']**6.0 return {"A": A, "B": B}
def _mem_matrix(n, k, r): """ Memory usage of parity check matrix in vector space elements INPUT: - ``n`` -- length of the code - ``k`` -- dimension of the code - ``r`` -- block size of M4RI procedure EXAMPLES:: >>> from .estimator import _mem_matrix >>> _mem_matrix(n=100,k=20,r=0) # doctest: +SKIP """ return n - k + 2 ** r
def get_cpu_frequency_cmd(cpu): """ """ cmd = 'cat /sys/devices/system/cpu/{0}/cpufreq/scaling_cur_freq'.format(cpu) return cmd
def _is_valid_email(email): """ Determines if the email is valid. Args: email: Email to test. Returns: bool: If the email is valid. """ if "@" not in email: return False if "." not in email: return False return True
def check_since(since: str = "") -> bool: """Check if the time range value is correct. Parameters: since (str): The time range. Returns: A boolean value. True for valid parameter, False otherwise. """ return since.lower() in ["daily", "weekly", "monthly"]
def value_to_zero_ten(confidence_value): """ This method will transform an integer value into the 0-10 scale string representation. The scale for this confidence representation is the following: .. list-table:: STIX Confidence to 0-10 :header-rows: 1 * - Range of Values - 0-10 Scale * - 0-4 - 0 * - 5-14 - 1 * - 15-24 - 2 * - 25-34 - 3 * - 35-44 - 4 * - 45-54 - 5 * - 55-64 - 6 * - 65-74 - 7 * - 75-84 - 8 * - 95-94 - 9 * - 95-100 - 10 Args: confidence_value (int): An integer value between 0 and 100. Returns: str: A string corresponding to the 0-10 scale. Raises: ValueError: If `confidence_value` is out of bounds. """ if 4 >= confidence_value >= 0: return '0' elif 14 >= confidence_value >= 5: return '1' elif 24 >= confidence_value >= 15: return '2' elif 34 >= confidence_value >= 25: return '3' elif 44 >= confidence_value >= 35: return '4' elif 54 >= confidence_value >= 45: return '5' elif 64 >= confidence_value >= 55: return '6' elif 74 >= confidence_value >= 65: return '7' elif 84 >= confidence_value >= 75: return '8' elif 94 >= confidence_value >= 85: return '9' elif 100 >= confidence_value >= 95: return '10' else: raise ValueError("Range of values out of bounds: %s" % confidence_value)
def get_threshold(votes,seats): """ compute quota needed based on total number of votes and number of seats """ return int(votes/(seats+1))+1
def match_dicts(dicts): """ Returns the matching or compatible parts of multi-type dictionaries. Only matching keys and values will be retained, except: Matching keys with float values will be averaged. Retains the actual type of the items passed, assuming they are all the same type of dictionary-like object.""" if len(dicts) == 0: return dict() matched_info = dicts[0] mult = 1.0 / len(dicts) for dict_ in dicts[1:]: for key, value in dict_.iteritems(): if key not in matched_info: # not present matched_info.drop(key) elif value != matched_info[key]: try: temp_fl = float(value) if '.' in str(value): # if number was actually a float # do average if dict_ == dicts[1]: # is the second element matched_info[key] = matched_info[key] * mult matched_info[key] += value * mult else: # not float matched_info.drop(key) except: # not equal and not float matched_info.drop(key) return matched_info
def update_behavior_validator(value): """ Property: SchemaChangePolicy.UpdateBehavior """ valid_values = [ "LOG", "UPDATE_IN_DATABASE", ] if value not in valid_values: raise ValueError("% is not a valid value for UpdateBehavior" % value) return value
def looks_like_ansi_color(text): """Return whether the text looks like it has ANSI color codes.""" return '\x1b[' in text
def str2bool(str): """ bool('False') is True in Python, so we need to do some string parsing. Use the same words in ConfigParser :param Text str: :rtype: bool """ return not str.lower() in ["false", "0", "off", "no"]
def fmtcols(mylist, cols): # based upon a work by gimel """Arrange a list of strings into columns.""" lines = ("\t".join(mylist[i:i+cols]) for i in range(0,len(mylist),cols)) return '\n'.join(lines)
def pad_name(name, pad_num=10, quotes=False): """ Pad a string so that they all line up when stacked. Parameters ---------- name : str The string to pad. pad_num : int The number of total spaces the string should take up. quotes : bool If name should be quoted. Returns ------- str Padded string """ l_name = len(name) quotes_len = 2 if quotes else 0 if l_name + quotes_len < pad_num: pad = pad_num - (l_name + quotes_len) if quotes: pad_str = "'{name}'{sep:<{pad}}" else: pad_str = "{name}{sep:<{pad}}" pad_name = pad_str.format(name=name, sep='', pad=pad) return pad_name else: if quotes: return "'{0}'".format(name) else: return '{0}'.format(name)
def _get_file_names(eval_file_idx): """ get the file names for eval """ file_names = {} train_files_idx_list = [1, 2, 3, 4, 5] train_files_idx_list.remove(eval_file_idx) print('Setting idx \'{}\' as validation/eval data.'.format(eval_file_idx)) file_names['train'] = ['data_batch_%d' % i for i in train_files_idx_list] file_names['eval'] = ['data_batch_'+str(eval_file_idx)] file_names['test'] = ['test_batch'] return file_names
def walk_json_field_safe(obj, *fields): """ for example a=[{"a": {"b": 2}}] walk_json_field_safe(a, 0, "a", "b") will get 2 walk_json_field_safe(a, 0, "not_exist") will get None """ try: for f in fields: obj = obj[f] return obj except: return None
def windowed(level, width): """ Function to display an image slice Input is a numpy 2D array """ maxval = level + width/2 minval = level - width/2 return minval, maxval
def to_pygame(coords, height=250): """Convert coordinates into pygame coordinates (lower-left => top left).""" return (coords[0], height - coords[1])
def max_bucket_len(buckets): """ Finds the maximum length of a bucket in buckets (dict as returned by bucket_sort) Parameters ---------- buckets : dict contains a map of ranks to list of cards Returns ------- integer length of the longest bucket in buckets """ m = 1 for k,v in buckets.items(): m = max(m, len(v)) return m
def simple_cycles_to_string(simple_cycles): """ Convert simple cycles to a string. Args: simple_cycles (list of lists): a list of simple cycles. Returns: None """ to_string = '' to_string += 'Number of simple cycles: {}'.format(str(len(simple_cycles))) for c in simple_cycles: to_string += c to_string += '\n' return to_string
def destandardize(x, mean, std): """Undo preprocessing on a frame""" return x * std + mean
def graph_attr_string(attrs): """Generate an xdot graph attribute string.""" attrs_strs = ['"'+str(k)+'"="'+str(v)+'"' for k,v in attrs.items()] return ';\n'.join(attrs_strs)+';\n'
def model_var_calculate(x, p, q, n): """ :param x: time intervar :param a: model parameter :param b: model parameter :param m: model parameter :return: variance of model """ def alpha_(x): return n * (p * (pow(x, 3)) + q * (x * x) + (1 - p - q) * x) def beta_(x): return n - alpha_(x) return ( (alpha_(x)*beta_(x)) / ((alpha_(x)+beta_(x))**2 * (alpha_(x)+beta_(x)+1) ))
def sum_digits(number): """ Takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. :param number: an integer value. :return: sum of the absolute value of each of the number's decimal digits. """ return sum(int(x) for x in str(abs(number)))
def value(entry): """ check if the string entry can Parameters ---------- entry: str an entry of type str Returns ------- bool True if the input can become an integer, False otherwise Notes ----- returns 'type' for the entry 'type', although type is a code object """ # Todo: try to replace bare except try: val = eval(entry) if isinstance(val, type): return entry else: return val except: return entry
def xo(s): """ Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char. :param s: A string value input. :return: True if amount of 'x's and 'o's are the same, Else False. """ return s.lower().count("x") == s.lower().count("o")
def is_movable(obj): """Check if object satisfies bluesky 'movable' interface. Parameters ---------- obj : Object Object to test. Returns ------- boolean True if movable, False otherwise. """ EXPECTED_ATTRS = ( 'name', 'parent', 'read', 'describe', 'read_configuration', 'describe_configuration', 'set', ) return all(hasattr(obj, attr) for attr in EXPECTED_ATTRS)
def attenuation_to_final_plato(attenuation: float, original_plato: float): """ Calculate the final degrees plato based on attenuation and original plato. """ apparent_attenuation = attenuation / 0.81 return original_plato - original_plato * apparent_attenuation
def pairs(k, arr): """ output # of pairs having k diff Array = unsorted, non empty, distinct, pos ints ASSUME - every pair of int instances that meet k diff are counted, even if it's same values as another pair - cannot pair an element w/ itself - can use built in sorting func Intuition: - need to check every element at least once Approach: 1. Brute Force - quadratic a) try all the pairs b) count up the ones that are k apart 2. Sorting - n log n + n --> linearithmic time Ex: [1, 5, 3, 4, 2], k = 2 [1, 2, 3, 4, 5] ^ ^ ^ ^ a) sort the array b) search for the pairs w/ 2 pointers + count 3) HashSet --> linear time + space a) make a set of all elements b) go through each element, in the array: - calculate it's comp, given k - check if comp in set - increment count of pairs [1, 5, 3, 4, 2] ^. ^. ^. ^ ^ {1, 5, 3, 4, 2} count = 0, 1, 2, 3 - for now I'll go with the HashSet option, but if the problem expanded to include duplicates, or the k could be negative, then this would need to be revised Edge Cases: - all same elements - return (n - 1) + (n - 2) + (n - 3)... --> "Triangular Series" - n(n - 1) / 2 (prove if asked) - """ values = set(arr) pairs = 0 for num in arr: complement = num + k if complement in values: pairs += 1 return pairs
def batches_shuffled(batch_list1, batch_list2): """ Ars: two lists of batches Returns True if the corresponding batches in lists are different Returns False otherwise """ for b1, b2 in zip(batch_list1, batch_list2): if b1 == b2: return False return True
def serialize_date(date): """ Computes the string representation of a date object composed of "day", "month", and "year". The argument is a Python dictionary. Example: { "day": "24", "month": "September", "year" "1985" } This would lead to the following output: "24 September 1985". Empty fields (day, month or year) are ignored. The only allowed date fields are "day", "month" and "year". Returns the string representation of the date object. """ assert(set(date.keys()) <= set(["day", "month", "year"])) date = date.items() date = filter(lambda item: item[1] is not None, date) date = filter(lambda item: len(str(item[1])) > 0, date) date = [str(item[1]) for item in sorted(date)] return " ".join(date)
def hex2(byt): """format a byte in a 2 character hex string""" str = hex(byt)[2:] # strip the 0x if len(str) == 1: str = '0' + str return str.upper()
def alias(name: str) -> str: """Add support for aliasing to make some names shorter & allow minor mistakes""" aliases = { "cpp": "c++", "jb": "jetbrains", "javascript": "node", "js": "node", "py": "python" } return aliases.get(name, name)
def print_running_report(current_time, start_time, num_of_first_pages): """ prints details about the run: "run ended after: 0.34 minutes, ran on 2 names" :param current_time: current time. :param start_time: start time of the run. :param num_of_first_pages: number of first pages drawn. :return: the time in minutes took to run (String) """ time_in_minutes = "{:.2f}".format((current_time - start_time) / 60) print("run ended after:", time_in_minutes, "minutes") print("ran on", num_of_first_pages, "names") return time_in_minutes
def do(*args): """Helper function for chaining function calls in a Python lambda expression. Part of a poor-man's functional programming suite used to define several pfainspector commands as one-liners. :type args: anything :param args: functions that have already been evaluated :rtype: anything :return: the last argument """ return args[-1]
def rev_comp(seq): """ """ complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'} return "".join(complement[base] for base in seq)[::-1]
def IsType(param, param_type): """Check if parameter is of the right type. Args: param: obj Parameter to check. param_type: type Type of the parameter to check against. Returns: bool True if the parameter is of right type, False otherwise. """ if not isinstance(param, param_type): return False return True
def atttyp(att: str) -> str: """ Get attribute type as string. :param str att: attribute type e.g. 'UNT002' :return: type of attribute as string e.g. 'UNT' :rtype: str """ return att[0:3]
def tuplize(d): """ This function takes a dictionary and converts it to a list of tuples recursively. :param d: A dictionary. :return: List of tuples. """ list_of_tuples = [] key_list = sorted(list(d.keys())) for key in key_list: if type(d[key]) == list: # Convert a value which is itself a list of dict to a list of tuples. if d[key] and type(d[key][0]) == dict: sub_tuples = [] for sub_dict in d[key]: sub_tuples.append(tuplize(sub_dict)) # To handle comparing two None values, while creating a tuple for a {key: value}, make the first element # in the tuple a boolean `True` if value is None so that attributes with None value are put at last # in the sorted list. list_of_tuples.append((sub_tuples is None, key, sub_tuples)) else: list_of_tuples.append((d[key] is None, key, d[key])) elif type(d[key]) == dict: tupled_value = tuplize(d[key]) list_of_tuples.append((tupled_value is None, key, tupled_value)) else: list_of_tuples.append((d[key] is None, key, d[key])) return list_of_tuples
def LinearReconstruct( u_stencil ): """Linear reconstruction with linear weights. This reconstructs u_{i+1/2} given cell averages \\bar{u}_i at each neighboring location. See (2.14) in `High Order Weighted Essentially Nonoscillatory Schemes for Convection Dominated Problems'. """ uim2, uim1, ui, uip1, uip2 = u_stencil return uim2/30 - (13*uim1)/60 + 47*(ui/60) + 9*(uip1/20) - uip2/20
def censor_non_alphanum(s): """ Returns s with all non-alphanumeric characters replaced with * Parameters ---------- s : str The string to be censored. Returns ------- output : str The censored version of `s` """ def censor(ch): if (ch >= 'A' and ch <= 'z') or (ch >= '0' and ch <= '9'): return ch return '*' return ''.join(censor(ch) for ch in s)
def _find_triangle_containing_vertex(vertex, triangles): """ Finds a triangle in a list that contains a prescribed point. Given a vertex and the corresponding triangulation it belongs to, return the index of the first triangle that contains the vertex. Parameters ---------- vertex : int An index of the vertex of interest. Index is in relation to the corresponding coordinates stored in the animal object. triangles : list of triples of ints List of all the triangles to be searched. Each triple represents the indices of the points of a triangle. Returns ------- int or None If there exists a triangle containing the vertex, it returns the index of the first triangle that contains it. Otherwise, returns None. """ triangle_index = None for triangle_i, triangle in enumerate(triangles): if vertex in triangle: triangle_index = triangle_i return triangle_index
def dekebab(string): """kebab-case -> kebab case""" return " ".join(string.split("-"))
def baseconvert(number, fromdigits, todigits): """ converts a "number" between two bases of arbitrary digits The input number is assumed to be a string of digits from the fromdigits string (which is in order of smallest to largest digit). The return value is a string of elements from todigits (ordered in the same way). The input and output bases are determined from the lengths of the digit strings. Negative signs are passed through. decimal to binary >>> baseconvert(555, BASE10, BASE2) '1000101011' binary to decimal >>> baseconvert('1000101011', BASE2, BASE10) '555' integer interpreted as binary and converted to decimal (!) >>> baseconvert(1000101011, BASE2, BASE10) '555' base10 to base4 >>> baseconvert(99, BASE10, "0123") '1203' base4 to base5 (with alphabetic digits) >>> baseconvert(1203, "0123", "abcde") 'dee' base5, alpha digits back to base 10 >>> baseconvert('dee',"abcde", BASE10) '99' decimal to a base that uses A-Z0-9a-z for its digits >>> baseconvert(257938572394, BASE10,BASE62) 'E78Lxik' ..convert back >>> baseconvert('E78Lxik', BASE62,BASE10) '257938572394' binary to a base with words for digits (the function cannot convert this back) >>> baseconvert('1101', BASE2,('Zero','One')) 'OneOneZeroOne' """ num_str = str(number) if num_str.startswith("-"): number = num_str[1:] neg = 1 else: neg = 0 # make an integer out of the number num_int = 0 for digit in str(number): num_int = num_int * len(fromdigits) + fromdigits.index(digit) # create the result in base 'len(todigits)' if num_int == 0: res = todigits[0] else: res = "" while num_int > 0: digit = num_int % len(todigits) res = todigits[digit] + res num_int = int(num_int / len(todigits)) if neg: res = "-" + res return res
def build_adj_and_indegrees(order, edges): """ Creates an adjacency list and indegree counts from an order (vertex count) and edges. """ adj = [[] for _ in range(order)] indegs = [0] * order for src, dest in edges: adj[src].append(dest) indegs[dest] += 1 return adj, indegs
def json_get_fields(struct, path=[]): """Recusrsively finds fields in script JSON and returns them as a list. Field has format: { "field":{ "name":"???", "kind":"???", "default":???, "description":"???" }} Args: struct: (dict) A dictionary representation fo the JSON script. path: (list) Stack that keeps track of recursion depth. Not used externally. Returns: fields: (list) A list of dictionaries representing each field struct found in the JSON. """ fields = {} path = path[:] if isinstance(struct, dict): if 'field' in struct: fields[struct['field']['name']] = struct['field'] else: for key, value in struct.items(): fields.update(json_get_fields(value, path + [key])) elif isinstance(struct, list) or isinstance(struct, tuple): for index, value in enumerate(struct): fields.update(json_get_fields(value, path + [index])) if path == []: return sorted(fields.values(), key=lambda f: f.get('order', 0)) # sort only on last step of recursion else: return fields
def extract_msg(elem): """Extracts a message""" if ' % ' in elem: elem = elem.split(' % ')[:-1] elem = ''.join(elem) elem = elem.rstrip(')').strip('"').strip("'") return elem
def ft2m(feet: float) -> float: """ Convert feet to meters. :param float feet: feet :return: elevation in meters :rtype: float """ if not isinstance(feet, (float, int)): return 0 return feet / 3.28084
def retrieve(url): """Downloads the file contained at the url endpoint in chunks and streams it to disk -> s3, then deletes the file""" local_filename = url.split('/')[-1] #with requests.get(url, stream=True) as r: # with open(local_filename, 'wb') as f: # shutil.copyfileobj(r.raw, f, length=16*1024*1024) return local_filename
def schedule_pipelineexecutionstartcondition(startcondition): """ Property: Schedule.PipelineExecutionStartCondition """ valid_startcondition = [ "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE", "EXPRESSION_MATCH_ONLY", ] if startcondition not in valid_startcondition: raise ValueError( 'PipelineExecutionStartCondition must be one of: "%s"' % (", ".join(valid_startcondition)) ) return startcondition
def get_lst_avg(lst): """ :param lst: (list) the list to average :return: (float) average value of the list """ try: return sum(lst) / float(len(lst)) except TypeError: print("get_lst_avg: bad lst or list contains non-numeric values (None, str, etc.)") except ZeroDivisionError: pass return -1
def waitTime(gate, station=None, gate_settle=None, default=1e-3): """ Return settle times for gates on a station """ if gate is None: return 0.001 if gate_settle is not None: return gate_settle(gate) if station is not None: if hasattr(station, 'gate_settle'): return station.gate_settle(gate) return default
def get_description(ast): """ Creates and returns decorator string """ if not hasattr(ast, "description") or ast.description is None: return "" else: return f"(description='''{ast.description.value}''')"
def _parse_and_format_value(string_value): """Parses and formats a string into the stats format. Args: string_value: Value of the stat as string. Returns: Value of the stat as a float. """ if str(string_value).lower() == 'nan': return None if type(string_value) == float: return string_value if type(string_value) == int: return float(string_value) string_value = str(string_value) if '%' in string_value: string_value = string_value.replace('%', '') return float(string_value) / 100 return float(string_value)
def count(string): """"Function to return a dictionary of alphabet as keys and their count's as values from a list of alphabets""" unique = dict() for elem in string: if elem in unique: unique[elem] = unique[elem]+1 else: unique[elem] = 1 return unique
def unrolled(i, init_x, func, num_iter, return_last_two=False): """Repeatedly apply a function using a regular python loop. Args: i (int): the current iteration count. init_x: The initial values fed to `func`. func (callable): The function which is repeatedly called. num_iter (int): The number of times to apply the function `func`. return_last_two (bool, optional): When `True`, return the two last outputs of `func`. Returns: The last output of `func`, or, if `return_last_two` is `True`, a tuple with the last two outputs of `func`. """ x = init_x x_old = None for _ in range(num_iter): x_old = x x = func(x_old) i = i + 1 if return_last_two: return i, x, x_old else: return i, x
def main_converter(input_number, input_base, output_base): """ function that do convert numbers from one base to another :param input_number: the number entered by the user :param input_base: the base user wants to convert from :param output_base: the base user wants to convert to :return converted number """ # this list holds the numbers to display at the end remainder_list = [] # start value for base 10. As base 10 is our intermediate, in int_base_10, int means intermediate int_base_10 = 0 # checking inputs if output_base == 2: return bin(input_number)[2:] # using the base 10 before the actual calculation as an intermediate elif input_base != 10: # reverse the string to start calculating from the least significant number, # the number as unit's place. reversed_input_number = input_number[::-1] # check if user typed in alphas outside HEX dictionary. dictionary_hex = { 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15 } for i, number in enumerate(reversed_input_number): for key, value in dictionary_hex.items(): if str(number).lower() == key: number = value int_base_10 += (int(number) * (int(input_base) ** i)) # if the number is already in Base 10, so we can start conversion elif input_base == 10: int_base_10 = int(input_number) # iterate through, until we hit 0. When we get 0, we'll have our number. while int_base_10 > 0: # find number to pass further down the loop, the number before the decimal point divided = int_base_10 // int(output_base) # find remainder to keep, the number after the decimal point remainder_list.append(str(int_base_10 % int(output_base))) # the new value to send to the next iteration int_base_10 = divided # if Hexadecimal output base, we should convert numbers above 9 if int(output_base) == 16: hex_dictionary = { '10': 'a', '11': 'b', '12': 'c', '13': 'd', '14': 'e', '15': 'f' } # iterate through remainder_list and convert 9+ numbers to alphas. for i, each in enumerate(remainder_list): for key, value in hex_dictionary.items(): if each == key: remainder_list[i] = value return ''.join(remainder_list[::-1])
def exchange(flw, exchanges_list): """Add docstring.""" exchanges_list.append(flw) return exchanges_list
def call_reply(msg, call_return): """Construct message used by CtrlServer when replying to API calls. :param msg: Description of API call. :type msg: string :param call_return: Return value of API call. :type call_return: string :returns: Constructed call_reply dict, ready to be sent over the wire. """ return {"type": "call_reply", "msg": msg, "call_return": call_return}
def _recursive_01_knapsack_aux(capacity: int, w: list, v: list, value: int) -> int: """Either takes the last element or it doesn't. This algorithm takes exponential time.""" if capacity == 0: return 0 if len(w) > 0 and len(v) > 0: if w[-1] > capacity: # We cannot include the nth item. value = _recursive_01_knapsack_aux(capacity, w[:-1], v[:-1], value) else: value = max( v[-1] + _recursive_01_knapsack_aux(capacity - w[-1], w[:-1], v[:-1], value), _recursive_01_knapsack_aux(capacity, w[:-1], v[:-1], value)) return value
def format_web_url(url): """Format web url.""" url = url.replace("localhost", "http://127.0.0.1") if not url.startswith("http://"): return "http://" + url return url
def max_prof(array): """input an array to determine max & sum profit by buying low and selling high""" #edge cases if len(array) < 1: return 0 # pointers low = array[0] high = array[0] profits = [] # iterate through list and set pointers for i in array: # if item is less than the high pointer, # sell and reinitiate pointers if i < high: profits.append(high-low) low = i high = i # if item is higher, then new high elif i >= high: high = i # if we have any left over if high > low: profits.append(high-low) print(f"Max profit: {max(profits)} and Total profit {sum(profits)}")
def _range_to_number(bucket_string): """Converts "X-Y" -> "X".""" return int(bucket_string.split('-')[0])
def color_rgb_to_hex(r: int, g: int, b: int) -> str: """Return a RGB color from a hex color string.""" return "{0:02x}{1:02x}{2:02x}".format(round(r), round(g), round(b))
def _prefix_expand(prefix): """Expand the prefix into values for checksum computation.""" retval = bytearray(ord(x) & 0x1f for x in prefix) # Append null separator retval.append(0) return retval
def find_point_in_section_list(point, section_list): """Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5, 32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for them the function returns 5, and 30, 30.7 and 31 all match [30-31]. Parameters --------- point : float The point for which to match a section. section_list : sortedcontainers.SortedList A list of start points of consecutive sections. Returns ------- float The start of the section the given point belongs to. None if no match was found. Example ------- >>> from sortedcontainers import SortedList >>> seclist = SortedList([5, 8, 30, 31]) >>> find_point_in_section_list(4, seclist) >>> find_point_in_section_list(5, seclist) 5 >>> find_point_in_section_list(27, seclist) 8 >>> find_point_in_section_list(31, seclist) 30 """ if point < section_list[0] or point > section_list[-1]: return None if point in section_list: if point == section_list[-1]: return section_list[-2] ind = section_list.bisect(point)-1 if ind == 0: return section_list[0] return section_list[ind] try: ind = section_list.bisect(point) return section_list[ind-1] except IndexError: return None
def divide(dividend, divisor): """Divide dividend by divisor. :param str dividend: Dividend. :param str divisor: Divisor. :return: quotient or exception information. """ try: return int(dividend) // int(divisor) except (ZeroDivisionError, ValueError) as exception: return f"{exception.__class__.__name__}: {exception}"
def _get_image_name(base_name,row,col,Z=None,C=None,T=None,padding=3): """ This function generates an image name from image coordinates """ name = base_name name += "_y" + str(row).zfill(padding) name += "_x" + str(col).zfill(padding) if Z is not None: name += "_z" + str(Z).zfill(padding) if C is not None: name += "_c" + str(C).zfill(padding) if T is not None: name += "_t" + str(T).zfill(padding) name += ".ome.tif" return name
def is_circuit_allowed_by_exclusion(op_exclusions, circuit): """ Returns True if `circuit` does not contain any gates from `op_exclusions`. Otherwise, returns False. """ for gate in op_exclusions: if gate in circuit: return False return True
def bCallback(dataset, geneid, colors): """Callback to set initial value of blue slider from dict. Positional arguments: dataset -- Currently selected dataset. geneid -- Not needed, only to register input colors -- Dictionary containing the color values. """ colorsDict = colors try: colorVal = colorsDict[dataset][4:-1].split(',')[2] return int(colorVal) except KeyError: return 0