content
stringlengths
42
6.51k
def get_num_atoms_in_formula_unit(configuration): """Return the number ot atoms per formula unit. For unaries, it's the number in the primitive cell: 1 for SC, BCC, FCC; 2 for diamond. """ mapping = { 'XO': 2, 'XO2': 3, 'X2O': 3, 'X2O3': 5, 'XO3': 4, 'X2O5': 7, 'X/Diamond': 2, 'X/SC': 1, 'X/FCC': 1, 'X/BCC': 1 } try: return mapping[configuration] except KeyError: raise ValueError(f"Unknown number of atoms in formula unit for configuration '{configuration}'")
def parse_tsv(s): """Parse TSV-formatted string into a list of dictionaries. :param s: TSV-formatted string :type s: str :return: list of dictionaries, with each dictionary containing keys from the header (first line of string) :rtype: list """ lines = s.strip().splitlines() header = lines.pop(0).split('\t') rows = [] for line in lines: values = line.split('\t') rows.append({key: value for key, value in zip(header, values)}) return rows
def generate_anchor_tag(url: str, description: str) -> str: """ Fungsi yang menerima input berupa string url dan string description dan mengembalikan string yang berisi tag anchor dengan isi url dan description yang sama dengan input. Fungsi ini akan mengembalikan tag anchor dengan url yang berisi "/" dan description yang berisi "HOME" Contoh: >>> generate_anchor_tag("", "") '<a href="/">HOME</a>' >>> generate_anchor_tag("/about", "ABOUT") '<a href="/about">ABOUT</a>' >>> generate_anchor_tag("/contact-us", "CONTACT US") '<a href="/contact-us">CONTACT US</a>' >>> generate_anchor_tag("/sebuah-slug-yang-panjang-sekali", "SSYPS") '<a href="/sebuah-slug-yang-panjang-sekali">SSYPS</a>' """ if url == "": url = "/" description = "HOME" return f'<a href="{url}">{description}</a>'
def christmas_log(ingredients: str, mix: int) -> str: """Created the Christmas log Args: ingredients (str): list of ingredients mix (int): number of mixes to be made Returns: str: The christmas lgo """ return ingredients[-mix:] + ingredients[:-mix]
def getFloatFromStr(number: str) -> float: """ Return float representation of a given number string. HEX number strings must start with ``0x``. Args: numberStr: int/float/string representation of a given number. """ numberStr = number.strip() isNegative = False if "-" in numberStr: numberStr = numberStr.replace("-", "") isNegative = True if numberStr.lower().startswith("0x"): num = float(int(numberStr, 16)) else: num = float(numberStr) if isNegative: num = 0 - num return num
def normalize_whitespace(text, base_whitespace: str = " ") -> str: """ Convert all whitespace to *base_whitespace* """ return base_whitespace.join(text.split()).strip()
def _remove_dups(L): """ Remove duplicates AND preserve the original order of the elements. The set class is not guaranteed to do this. """ seen_before = set([]) L2 = [] for i in L: if i not in seen_before: seen_before.add(i) L2.append(i) return L2
def max_profit(stocks): """Computes the maximum benefit that can be done by buying and selling once a stock based on a list of stock values O(n) time complexity as we only go through the list of values once""" if stocks == []: return [] current_max_profit = 0 min_stock = stocks[0] solution = [stocks[0], stocks[0]] for stock in stocks: if stock < min_stock: min_stock = stock if stock - min_stock > current_max_profit: current_max_profit = stock - min_stock solution = [min_stock, stock] return solution
def flatten_lists_one_level(potential_list_of_lists): """ Wrapper to unravel or flatten list of lists only 1 level :param potential_list_of_lists: list containing lists :return: flattened list """ flat_list = [] for potential_list in potential_list_of_lists: if isinstance(potential_list, list): flat_list.extend(potential_list) else: flat_list.append(potential_list) return flat_list
def edit_distance(s1, s2): """ :param s1: list :param s2: list :return: edit distance of two lists """ if len(s1) < len(s2): return edit_distance(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[ j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer deletions = current_row[j] + 1 # than s2 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
def collatz_step(n: int) -> int: """Returns the next number in the Collatz sequence following n.""" return n // 2 if n % 2 == 0 else 3 * n + 1
def normalize_page_number(page_number, page_range): """Handle a negative *page_number*. Return a positive page number contained in *page_range*. If the negative index is out of range, return the page number 1. """ try: return page_range[page_number] except IndexError: return page_range[0]
def failures_message(failed): """Format a list of failed recipes for a slack message""" failures_msg = [ { "color": '#f2c744', "blocks": [ { "type": "divider" }, { "type": "section", "text": {"type": "mrkdwn", "text": ":warning: *The following recipes failed*"} } ] } ] for item in failed: info = item["message"] name = item["recipe"] failure_info = [ { "type": "section", "text": {"type": "mrkdwn", "text": f"{name}"} }, { "type": "section", "text": {"type": "mrkdwn", "text": f"```{info}```"} } ] failures_msg[0]['blocks'].extend(failure_info) return failures_msg
def dict_sorted(src: dict, is_reverse: bool=False) -> dict: """Convert the dictionary data to sorted data.""" assert isinstance(src, dict) assert isinstance(is_reverse, bool) return dict(sorted(src.items(), key=lambda x: x[0], reverse=is_reverse))
def capfirst(value, failure_string='N/A'): """ Capitalizes the first character of the value. If the submitted value isn't a string, returns the `failure_string` keyword argument. Cribbs from django's default filter set """ try: value = value.lower() return value[0].upper() + value[1:] except: return failure_string
def factorial(n): """ Calculates factoriel of give number that uses a recursion """ if n == 0: return 1 return n * factorial(n-1)
def one_feature(): """Returns feature object response in token, and list of feature permissions""" return {'feature': ['permission']}, ['feature.permission']
def corr_exon_num_or_no_fs(codon, exon_num): """Need to decide which exon num to assign.""" # count letters in the left and rigth exon cut_at = codon["split_"] left_side_ref = codon["ref_codon"][:cut_at] left_side_que = codon["que_codon"][:cut_at] # count gaps on each side ls_ref_gaps = left_side_ref.count("-") ls_que_gaps = left_side_que.count("-") # if number of gaps on the left exon % 3 != 0: # we say the left exon if mutated (exon_num - 1) # otherwise the rigth one (exon_num) fs_left = abs(ls_ref_gaps - ls_que_gaps) % 3 != 0 if fs_left: return exon_num - 1 else: return exon_num
def unknownEvaluationFunction(current: list, target: list): """ Some really tricky evaluation function, as shown in: Ma, S. P. et al(2004). Search Problems. In Artificial Intelligence(pp. 26-49). Beijing, Beijing: Tsinghua University Press """ count = 0 curr_1d = [] tgt_1d = [] for i in range(3): for j in range(3): curr_1d.append(current[i][j]) tgt_1d.append(target[i][j]) outer_layer_index = [0, 1, 2, 5, 8, 7, 6, 3] curr_outer_layer = tgt_outer_layer = [] for i in outer_layer_index: curr_outer_layer.append(curr_1d[i]) tgt_outer_layer.append(tgt_1d[i]) for i in range(7): if curr_outer_layer[i + 1] != tgt_outer_layer[tgt_outer_layer.index(curr_outer_layer[i + 1])]: count += 2 if curr_outer_layer[7] != tgt_outer_layer[tgt_outer_layer.index(curr_outer_layer[0])]: count += 2 if curr_1d[4] != 0: count += 1 return count
def get_microphysics_name(config): """Get name of microphysics scheme from configuration dictionary Args: config (dict): a configuration dictionary Returns: str: name of microphysics scheme Raises: NotImplementedError: no microphysics name defined for specified imp_physics and ncld combination """ imp_physics = config["namelist"]["gfs_physics_nml"].get("imp_physics") ncld = config["namelist"]["gfs_physics_nml"].get("ncld") if imp_physics == 11 and ncld == 5: microphysics_name = "GFDLMP" elif imp_physics == 99 and ncld == 1: microphysics_name = "ZhaoCarr" else: raise NotImplementedError( f"Microphysics choice imp_physics={imp_physics} and ncld={ncld} not one of the valid options" ) return microphysics_name
def same_padding_calc(inp_shape, kernel_shape, stride): """ !Attention - only square image padding calculation implemented! Calculates the size of 'same' padding for CONV layers. Args: kernel_shape (int or tuple): the shape of the kernel(filter). inp_shape (int or tuple): the shape of the input. stride (int). Returns: res (int or tuple): 'same' padding size. """ if type(inp_shape) == int and type(kernel_shape) == int: res = (inp_shape * stride - inp_shape - stride + kernel_shape) // 2 return res elif type(inp_shape) == tuple and type(kernel_shape) == int: res = None return res elif type(inp_shape) == int and type(kernel_shape) == tuple: res = None return res elif type(inp_shape) == tuple and type(kernel_shape) == tuple: res = None return res else: res = None return res
def EDSD(libitem, index): """ Exponentially decreasing space density prior Define characteristic length scale k in kpc """ k = 1.35 return k
def zstr(s): """ if s contains None, it replaced with 'noraffice' string """ return s or "notraffic"
def _get_line_with_str(lines, string, index): """Extracts the index-th line containing a string. Args: lines (list[str]): List of strings (typically lines from a file). string (str): Substring to filter lines by. index (int): Which filtered string to return. Returns: str: The index-th fitlered string. Returns None if no such string exists. """ relevant_lines = [line for line in lines if string in line] if len(relevant_lines) == 0 or (index != -1 and len(relevant_lines) <= index): return None return relevant_lines[index]
def _get_names(_dict): """Recursively find the names in a serialized column dictionary. Parameters ---------- _dict : `dict` Dictionary from astropy __serialized_columns__ Returns ------- all_names : `list` [`str`] All the column names mentioned in _dict and sub-dicts. """ all_names = [] for key in _dict: if isinstance(_dict[key], dict): all_names.extend(_get_names(_dict[key])) else: if key == 'name': all_names.append(_dict['name']) return all_names
def metric7(gold, predicted): """Evaluate labeling as being clause-classification on clause level""" counts = {"tp": 0, "tn": 0, "fp": 0, "fn": 0} for gclause, pclause in zip(gold, predicted): gold_binary = "B" in gclause or "I" in gclause predicted_binary = "B" in pclause or "I" in pclause if predicted_binary: if gold_binary: counts["tp"] += 1 else: counts["fp"] += 1 else: if gold_binary: counts["fn"] += 1 else: counts["tn"] += 1 return counts
def compute_spiral_diagonal_sum(first_elem, loop_wh): """ Compute the sum of the four diagonal elements for the given loop first_elem: First element (in the right-most, second-down element of this loop) loop_wh: Width / height of the spiral's loop to compute the diag-sum return: sum of the four diagonal elements """ lower_right = first_elem + loop_wh - 2 return 4 * lower_right + 6 * loop_wh - 6
def find_average(data): """ averages total amounts from database dumps :param data: accepts multi-dimensional iterable data type :return: returns the average in a FLOAT """ total = 0 amount = len(data) for entry in data: total += entry[0] average = total / amount return round(average, 2)
def set_spat_info(location=None, primary_spatial_reference="string", resolution="string", srid=0): """ function to create a dictionary with typicial values of spatial information for the dataset :param location: :param primary_spatial_reference: :param resolution: :param srid: :return: returns dictionary of spatial information :rtype: dict : """ if location is None: location = {} spat_info = { "location": location, "primarySpatialReference": primary_spatial_reference, "resolution": resolution, "srid": srid } return spat_info
def incsum(prevsum, prevmean, mean, x): """Caclulate incremental sum of square deviations""" newsum = prevsum + (x - prevmean) * (x - mean) return newsum
def _to_str(value): """Convert value to str for bmfont file.""" if isinstance(value, str) : return '"{}"'.format(value) if isinstance(value, (list, tuple)): return ','.join(str(_item) for _item in value) return str(int(value))
def to_mmol(value): """ Convert a given value in mg/dL to mmol/L rounded to 1 decimal place. """ return round((float(value) / 18.018), 1)
def get_display_name(record): """Get the display name for a record. Args: record A record returned by AWS. Returns: A display name for the cluster. """ return record["clusterName"]
def l2s(x): """ [1,2,3,4,5,6,7,8] -> '1,2,...,7,8' """ if len(x)>5: x = x[:2] + ['...'] + x[-2:] y = [str(z) for z in x] # convert to list of strings, eg if list of int y = ",".join(y) return y
def Beta(x, norm=1., beta=1., r=1.): """ Beta profile. Parameters ---------- x : number The input number for calculation. norm : number The normalization at the center of the cluster. beta : number The beta parameter. r : number The core radius. References ---------- Cavaliere, A. & Fusco-Femiano, R. 1976, A&A, 500, 95 """ result = norm * (1 + (x / r) ** 2) ** (0.5 - 3 * beta) return result
def quantile(percent, data): """ Compute the quantile such that 100p% of data lies above the output value. """ if not data: return data data.sort() index = int(percent*len(data) + 0.5) - 1 if index < 0: index = 0 return data[index]
def _get_argument_type(value): """Get the type of a command line argument.""" type_ = "string" try: value = int(value) type_ = "int" except ValueError: pass return value, type_
def textToInt(text, defaultInt): """Converts text to an integer by using an eval and returns the integer. If something goes wrong, returns default Int. """ try: returnInt = int(text) except Exception: returnInt = defaultInt return returnInt
def get_best_trial(trial_list, metric): """Retrieve the best trial.""" return max(trial_list, key=lambda trial: trial[metric])
def to_element_case(el): """Convert an uppercase elemnt to element case, e.g. FE to Fe, V to V.""" return el[0].upper() + el[1:].lower()
def _calculate_verification_code(hash: bytes) -> int: """ Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed. See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm """ return ((0xFC & hash[0]) << 5) | (hash[-1] & 0x7F)
def _GuessCharset(text): """Guesses the character set of a piece of text. Args: text: A string that is either a US-ASCII string or a Unicode string that was encoded in UTF-8. Returns: The character set that is needed by the string, either US-ASCII or UTF-8. """ try: text.decode('us-ascii') return 'us-ascii' except UnicodeDecodeError: return 'utf-8'
def get_av_num(link): """ get av num""" av_num = link.split('/')[-1] return av_num
def clean_data(data): """Return the list of data, replacing dashes with zeros. Parameters ---------- data : list or str The data to be cleaned Returns ------- cleaned_data : list of str The data with dashes replaced with zeros """ cleaned_data = [] for item in data: if item == '-': cleaned_data.append(int(item.replace('-', '0'))) else: cleaned_data.append(int(item)) return cleaned_data
def is_event_match_for_list(event, field, value_list): """Return if <field> in "event" match any one of the value in "value_list" or not. Args: event: event to test. This event need to have <field>. field: field to match. value_list: a list of value to match. Returns: True if <field> in "event" match one of the value in "value_list". False otherwise. """ try: value_in_event = event['data'][field] except KeyError: return False for value in value_list: if value_in_event == value: return True return False
def calc_specificity(true_neg, false_pos): """ function to calculate specificity/true negative rate Args: true_neg: Number of true negatives false_pos: Number of false positives Returns: None """ try: spec = true_neg / float(true_neg + false_pos) return round(spec, 3) except BaseException: return None
def func_nogoal(x): """Map goals scored to nogoal flag. INPUT: x: Goals scored OUTPUT: 1 (no goals scored) or 0 (at least 1 goal scored) """ if x == 0: return 1 else: return 0
def get_ratelimiter_config(global_configs, api_name): """Get rate limiter configuration. Args: global_configs (dict): Global configurations. api_name (String): The name of the api. Returns: float: Max calls float: quota period) """ max_calls = global_configs.get(api_name, {}).get('max_calls') quota_period = global_configs.get(api_name, {}).get('period') return max_calls, quota_period
def get_value(amps, path): """ This function extracts a value from a nested dictionary by following the path of the value. """ current_value = amps for key in path.split('/')[1:]: current_value = current_value[key] return current_value
def distance_abs(x_dict, y_dict): """ Distance function for use in pyABC package, which takes dictionary arguments """ x = x_dict['X_2'] y = y_dict['X_2'] dist = 0 for idx_time in range(9): sim_hist = x[idx_time] data_hist = y[idx_time] for idx_el in range(len(data_hist)): a = data_hist[idx_el] b = sim_hist[idx_el] dist += abs(a - b) return dist
def get_hashtags(content) -> str: """ Get hashtags from json """ mentions = list() for name in content['entities']['hashtags']: mentions.append(name['text']) return '|'.join(mentions)
def _check_substituted_domains(patchset, search_regex): """Returns True if the patchset contains substituted domains; False otherwise""" for patchedfile in patchset: for hunk in patchedfile: if not search_regex.search(str(hunk)) is None: return True return False
def invert(object): """Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array""" if type(object) is dict: o = object.items() else: o = enumerate(object) out = {} for key, value in o: try: out[value].append(key) except KeyError: out[value] = [key] return out
def get_file_name(path): """ Extracts the name of the file from the given path :param path: location of the file in which the name will be extracted from :return: """ split_path = path.split("/") file_name = split_path[len(split_path) - 1] return file_name
def _inject_key(key, infix): """ OSM keys often have several parts, separated by ':'s. When we merge properties from the left and right of a boundary, we want to preserve information like the left and right names, but prefer the form "name:left" rather than "left:name", so we have to insert an infix string to these ':'-delimited arrays. >>> _inject_key('a:b:c', 'x') 'a:x:b:c' >>> _inject_key('a', 'x') 'a:x' """ parts = key.split(':') parts.insert(1, infix) return ':'.join(parts)
def golden_section(f, a, b, tol=1e-5, **kwargs): """ Golden section search. Stolen from https://en.wikipedia.org/wiki/Golden-section_search Given a function f with a single local minimum in the interval [a,b], gss returns a subset interval [c,d] that contains the minimum with d-c <= tol. example: >>> f = lambda x: (x-2)**2 >>> a = 1 >>> b = 5 >>> tol = 1e-5 >>> (c,d) = golden_section(f, a, b, tol) >>> print (c,d) (1.9999959837979107, 2.0000050911830893) """ import numpy as np # 1/phi invphi = (np.sqrt(5) - 1) / 2 # 1/phi^2 invphi2 = (3 - np.sqrt(5)) / 2 (a, b) = (min(a, b), max(a, b)) h = b - a if h <= tol: return (a, b) # required steps to achieve tolerance n = int(np.ceil(np.log(tol / h) / np.log(invphi))) c = a + invphi2 * h d = a + invphi * h yc = f(c, **kwargs) yd = f(d, **kwargs) for k in range(n - 1): if yc < yd: b = d d = c yd = yc h = invphi * h c = a + invphi2 * h yc = f(c, **kwargs) else: a = c c = d yc = yd h = invphi * h d = a + invphi * h yd = f(d, **kwargs) if yc < yd: return (a, d) else: return (c, b)
def p1_for(input_list): """Compute some of numbers in list with for loop.""" out = 0 for i in input_list: out += i return out
def superpack_name(pyver, numver): """Return the filename of the superpack installer.""" return 'scipy-%s-win32-superpack-python%s.exe' % (numver, pyver)
def split_link_alias(link_alias): """Return (alias_root, link_id) from link alias.""" alias_root, alias_id = link_alias.split('#', 1) return alias_root, int(alias_id)
def field_to_list(row, key): """ Transforms key in row to a list. We split on semicolons if they exist in the string, otherwise we use commas. Args: row: row of data key: key for the field we want Reutrns: row: modified row """ if ";" in row[key]: row[key] = [c.strip() for c in row[key].split(";")] elif "," in row[key]: row[key] = [c.strip() for c in row[key].split(",")] else: row[key] = [row[key]] return row
def get_class(x): """ x: index """ # Example distribution = [99, 198, 297, 396, 495] x_class = 0 for i in range(len(distribution)): if x > distribution[i]: x_class += 1 return x_class
def call_filter(to_call, value, base): """ Encapsulates the logic for handling callables in the filter. Call the callable to_call with value and possibly base. """ # Callables can take either one or two values try: return to_call(value, base) except TypeError: return to_call(value)
def romberg_iterativo(f, i, lim): """ Funcion para ejecutar el metodo de Romberg iterativo. Esta funcion trata de ejecutar el metodo de Romberg iterativo con un acercamiento iterativo. Regresara el valor calculado, con la condicion de termino i == 0 donde no se llamara a si misma de nuevo. Para que esta funcion sea un poco mas "pythonica" no pediremos el valor previo del metodo y lo calcularemos de manera interna con el enfoque recursivo. Claramente este no es el metodo que se explica en la tarea, pero el otro se me revolvio y este funciona (aunque algo lento) Input: f := funcion para aproximar integral i := iteracion del metodo lim := tupla de limites de la evaluacion Regresa el valor de R(i,0), un flotante. """ try: a, b = lim except TypeError: raise Exception("Err: lim debe contener valores (a,b)") if i == 0: return ((b-a)/2)*(f(a) + f(b)) else: h = (b-a)/(2**i) r_im1 = romberg_iterativo(f, i-1, lim) suma = 0 for k in range(1, 2**(i-1)+1): suma += f(a + (2*k - 1)*h) return 0.5*r_im1 + h*suma
def power_intercept(popt, value=1): """At what x value does the function reach value.""" a, b = popt assert a > 0, f"a = {value}" assert value > 0, f"value = {value}" return (a / value) ** (1 / b)
def h(host_num: int) -> str: """ Returns the host name for a given host number """ return f'h{host_num}'
def convert_to_post(input_data): """ Api to get POST json data using PATCH/PUT json data Author: Ramprakash Reddy ([email protected]) :param: input_data (PATCH/PUT data) :return: POST data """ post_data = dict() temp = list(input_data.keys())[0] if isinstance(input_data[temp], dict): for key, value in input_data[temp].items(): post_data["{}:{}".format(temp.split(':')[0], key)] = value else: for key, value in input_data[temp][0].items(): if isinstance(value, dict): if "{}".format(temp.split('-')[0]) not in key: post_data["{}:{}".format(temp.split(':')[0], key)] = value else: post_data[key] = value return post_data
def colSel(idxes, iterable): """ colSel(idxes, iter: iterable) example: idxes = 1; iter = [1,2,3] => 2 idxes = [1,2]; iter = [1,2,3] => [2, 3] idxes = ("b", "a"); iter = {"a":"a", "b":"b"} => ["b", "a"] """ if type(idxes) not in (list, tuple): return iterable[idxes] return [iterable[idx] for idx in idxes]
def get_sample_ids_to_label(samples_file): """ Get sample id, label tuples to be highlighted """ sample_label_tuples = [] for line in open(samples_file, 'rU'): if line[0] == '#': continue line_pieces = [x.strip() for x in line.split('\t')] if len(line_pieces) == 2: sample_label_tuples.append(tuple(line_pieces[0:2])) return sample_label_tuples
def types_functions_to_json(json_types, functions): """Creates string for JSON output from types and functions.""" return {'functions': functions, 'types': json_types}
def find_peaks(list_of_intensities): """Find peaks Find local maxima for a given list of intensities or tuples Intensities are defined as local maxima if the intensities of the elements in the list before and after are smaller than the peak we want to determine. For example given a list: 1 5 [6] 4 1 2 [3] 2 We expect 6 and 3 to be returned. Args: list_of_intensities (list of floats, ints or tuple of ints): a list of numeric values Returns: list of floats or tuples: list of the identified local maxima Note: This is just a place holder for the TDD part :) """ peaks = [] if all([isinstance(x, tuple) for x in list_of_intensities]): for i in range(len(list_of_intensities)): list_of_intensities[i] = sum(list_of_intensities[i]) if i==0: if list_of_intensities[i] > list_of_intensities[i+1]: peaks.append(list_of_intensities[i]) elif i != 0 and i != len(list_of_intensities): if list_of_intensities[i-1] < list_of_intensities[i] > list_of_intensities[i+1]: peaks.append(list_of_intensities[i]) elif i==len(list_of_intensities): if list_of_intensities[i] > list_of_intensities[i+1]: peaks.append(list_of_intensities[i]) else: for i in range(len(list_of_intensities)): if isinstance(list_of_intensities[i], int) is False: continue if i==0: if list_of_intensities[i] > list_of_intensities[i+1]: peaks.append(list_of_intensities[i]) elif i != 0 and i != len(list_of_intensities): if list_of_intensities[i-1] < list_of_intensities[i] > list_of_intensities[i+1]: peaks.append(list_of_intensities[i]) elif i==len(list_of_intensities): if list_of_intensities[i] > list_of_intensities[i+1]: peaks.append(list_of_intensities[i]) return peaks
def dec(text): """ Create a declarative sentence """ formatted = '%s%s.' % (text[0].capitalize(), text[1:len(text)]) return formatted
def sum_pairs(ints, s): """ Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. sum_pairs([4, 3, 2, 3, 4], 6) ^-----^ 4 + 2 = 6, indices: 0, 2 * ^-----^ 3 + 3 = 6, indices: 1, 3 ^-----^ 2 + 4 = 6, indices: 2, 4 * entire pair is earlier, and therefore is the correct answer == [4, 2] """ cache = {} for i in ints: if s - i in cache: return [s - i, i] cache[i] = i
def _convert_now(arg_list): """ Handler for the "concatenate" meta-function. @param IN arg_list List of arguments @return DB function call string """ nb_args = len(arg_list) if nb_args != 0: raise Exception("The 'now' meta-function does not take arguments (%d provided)" % nb_args) return "SYSDATE"
def encodeFormData(arg, value): """Encode data as a multipart/form-data """ BOUNDARY = '----------BOUNDARY' l = [] l.append('--' + BOUNDARY) l.append('Content-Disposition: form-data; name="%s"' % arg) l.append('') l.append(value) l.append('--' + BOUNDARY + '--') l.append('') body = '\r\n'.join(l) contentType = 'multipart/form-data; boundary=%s' % BOUNDARY return body, contentType
def post_legacy(post): """Return legacy fields which may be useful to save. Some UI's may want to leverage these, but no point in indexing. """ _legacy = ['id', 'url', 'root_comment', 'root_author', 'root_permlink', 'root_title', 'parent_author', 'parent_permlink', 'max_accepted_payout', 'percent_steem_dollars', 'curator_payout_value', 'allow_replies', 'allow_votes', 'allow_curation_rewards', 'beneficiaries'] return {k: v for k, v in post.items() if k in _legacy}
def bubble_sort(array): """ Bubble sort implementation Arguments: - array : (int[]) array of int to sort Returns: - array : (int[]) sorted numbers """ for i in range(len(array)): for j in range(len(array)-1-i): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array
def get_pip_installation_line(package_name: str, package_version: str, package_url: str) -> str: """Return installation line for a pip installable package.""" extras_operators = ("[", "]") versions_operators = ("==", ">=", ">", "<=", "<") if any(operator in package_version for operator in extras_operators): assert all([operator not in package_version for operator in versions_operators]) install_arg = "" elif any(operator in package_version for operator in versions_operators): assert all([operator not in package_version for operator in extras_operators]) install_arg = "--upgrade " else: assert package_version == "" install_arg = "" if package_url == "": if install_arg == "": package_url = f"{package_name}{package_version}" else: assert install_arg == "--upgrade " package_url = f'{install_arg}"{package_name}{package_version}"' else: assert "https" in package_url if package_version != "": assert all([operator not in package_version for operator in versions_operators]) assert any(operator in package_version for operator in extras_operators) package_url = f'{install_arg}"{package_name}{package_version}@git+{package_url}"' return f"pip3 install {package_url}"
def node_para(args): """ :param args: args :return: node config or test node config list """ node_list = [] i = 0 if args.find("//") >= 0: for node in args.split("//"): node_list.append([]) ip, name, passwd = node.split(",") node_list[i].append(ip) node_list[i].append(name) node_list[i].append(passwd) i += 1 else: node_list.append([]) ip, name, passwd = args.split(",") node_list[i].append(ip) node_list[i].append(name) node_list[i].append(passwd) return node_list
def getTotalInAge(nodeState, ageTest): """Get the size of the population within an age group. :param nodeState: The disease states of the population stratified by age. :type nodeState: A dictionary with a tuple of (age, state) as keys and the number of individuals in that state as values. :param ageTest: The age range of the population. :type ageTest: str, e.g. '70+' :return: The population size within the age range. :rtype: int """ total = 0 for (age, _), value in nodeState.items(): if age == ageTest: total += value return total
def remove_last_range(some_list): """ Returns a given list with its last range removed. list -> list """ return some_list[:-1]
def escape_quotes(string): """Escape double quotes in string.""" return string.replace('"', '\\"')
def SET_DIFFERENCE(*expressions): """ Takes two sets and returns an array containing the elements that only exist in the first set. https://docs.mongodb.com/manual/reference/operator/aggregation/setDifference/ for more details :param expressions: The arrays (expressions) :return: Aggregation operator """ return {'$setDifference': list(expressions)}
def GetSubstitutedResponse(response_dict, protocol, response_values): """Substitutes the protocol-specific response with response_values. Args: response_dict: Canned response messages indexed by protocol. protocol: client's protocol version from the request Xml. response_values: Values to be substituted in the canned response. Returns: Xml string to be passed back to client. """ response_xml = response_dict[protocol] % response_values return response_xml
def _get_topic_name_from_ARN(arn): """ Returns undefined if arn is invalid Example arn: "arn:aws:sns:us-east-1:123456789012:notifications" """ return arn.split(":")[-1]
def get_adjacent_digits(n, tuple_length): """ Returns a list of numbers where each numbre is the tuple_length group of adjacent digits Ex: get_adjacent_digits(2345, 2) => [23, 34, 45] Ex: get_adjacent_digits(2345, 1) => [1, 2, 3, 4] """ result = [] limit = (10 ** (tuple_length - 1)) - 1 divisor = int(10 ** tuple_length) while n > limit: remainder = n % divisor result.insert(0, remainder) n //= 10 return result
def get_clean_urls(raw_urls): """ Known problems so far: https vs http https://www.test.de vs https://test.de https://www.test.de/something vs https://www.test.de/something#something https://www.test.de/something.html vs https://www.test.de/something.html?something """ cleaned_urls = [] for url in raw_urls: # Removing same html links with anchors (#) or question mark (?) url = url.split('#')[0].split('?')[0] # http vs https url = url.replace('http:', 'https:') # www if 'www' not in url[:12]: url = url.replace('https://', 'https://www.') cleaned_urls.append(url) return list(set(cleaned_urls))
def compute_boundary(max_item_id, max_user_id, num_workers): """ Compute the indexing boundary """ # Assume index is from 0 item_step = int((max_item_id+1) / num_workers) user_step = int((max_user_id+1) / num_workers) mov_interval = [] usr_interval = [] for idx in range(num_workers): if idx != num_workers-1: mov_interval.append((idx*item_step, (idx+1)*item_step-1)) usr_interval.append((idx*user_step, (idx+1)*user_step-1)) else: mov_interval.append((idx*item_step, max_item_id)) usr_interval.append((idx*user_step, max_user_id)) return mov_interval, usr_interval
def coluna_para_inteiro(c): """ Devolve um inteiro correspondente a coluna da posicao inserida. :param c: string, coluna da posicao. :return: int, valor correspondente da coluna. """ c_int = {'a': 0, 'b': 1, 'c': 2} return c_int[c]
def wrap_around(number: int, start: int, limit: int) -> int: """Returns the given number, wrapped around in range `[start, limit[`""" return start + ((number - start) % (limit - start))
def Commas(value): """Formats an integer with thousands-separating commas. Args: value: An integer. Returns: A string. """ if value < 0: sign = '-' value = -value else: sign = '' result = [] while value >= 1000: result.append('%03d' % (value % 1000)) value /= 1000 result.append('%d' % value) return sign + ','.join(reversed(result))
def process_json(json_parsed): """ Clear outputs from Notebook saved in JSON format """ if isinstance(json_parsed, dict): if 'cells' in json_parsed.keys(): for obj in json_parsed['cells']: if 'outputs' in obj.keys(): obj['outputs'] = [] else: return None else: return None return json_parsed
def correct_vgene(v, chain='B'): """Makes sure that the given v gene is in correct format, handles a few different formatsformats.""" if chain is 'B': v = v.replace('TCR','TR').replace('TRBV0','TRBV').replace('-0','-') elif chain is 'A': v = v.replace('TCR','TR').replace('TRAV0','TRAV').replace('-0','-') else: print("chain must be 'A' or 'B'. No corrections were made") return v.split(';')[0]
def split_lines_by_comment(lines): """Doc.""" lines_list = [] new_lines = [] in_multi_line_comment = False for line in lines: line = line.strip() if not line: continue if not in_multi_line_comment: if line.startswith('/*'): in_multi_line_comment = True lines_list.append(new_lines) new_lines = [] elif line.startswith('//'): line = '// ' + line[2:].strip() lines_list.append(new_lines) lines_list.append([line]) new_lines = [] else: new_lines.append(line) if in_multi_line_comment: new_lines.append(line) if line.endswith('*/'): in_multi_line_comment = False lines_list.append(new_lines) new_lines = [] lines_list.append(new_lines) return lines_list
def _group(template, resource, action, proid): """Render group template.""" return template.format( resource=resource, action=action, proid=proid )
def unchanged_required(argument): """ Return the argument text, unchanged. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: return argument
def valid(candidate): """Utility function that returns whether a pass permutation is valid""" permutation = str(candidate) # six digit number if not isinstance(candidate, int) or len(str(candidate)) != 6: # not a size digit number return False # increasing (next digit is > or ==) prev = permutation[0] for digit in permutation[1:]: # not increasing if digit < prev: return False prev = digit # at lease 2 adjacent digits are the same prev = permutation[0] for digit in permutation[1:]: # one adjacent match pair if digit == prev: return True prev = digit # Not matching adjacent digits - invalid return False
def merge_sort(collection): """ Counts the number of comparisons (between two elements) and swaps between elements while performing a merge sort :param collection: a collection of comparable elements :return: total number of comparisons and swaps, and the sorted list """ comparisons, swaps = 0, 0 mid = len(collection) // 2 left, right = collection[:mid], collection[mid:] if len(left) > 1: left_result = merge_sort(left) comparisons += left_result[0] swaps += left_result[1] left = left_result[2] if len(right) > 1: right_result = merge_sort(right) comparisons += right_result[0] swaps += right_result[1] right = right_result[2] sorted_collection = list() # while elements in both sub lists while left and right: if left[0] <= right[0]: sorted_collection.append(left.pop(0)) else: sorted_collection.append(right.pop(0)) comparisons, swaps = comparisons + 1, swaps + 1 # if elements are left in only one sublist, merge them (guaranteed sorted) # this does not count as swapping as it is just a copy operation # no need for swap += len(left or right) sorted_collection += (left or right) return comparisons, swaps, sorted_collection
def get_local_pod(module, array): """Return Pod or None""" try: return array.get_pod(module.params["name"]) except Exception: return None
def convert_to_list(array_): """ Convert all elements and array_ itself to a list. array_ is returned as is if it can't be converted to a list. """ if isinstance(array_, str): as_list = array_ else: try: as_list = list(convert_to_list(i) for i in array_) except TypeError: as_list = array_ return as_list
def __parse_search__(query): """ Parse the search by. First checks if a string is passed and converts = to : in order to later create a dictionary. If multiple parameters are provided a list is created otherwise the list will only contain one criteria. NOTE: This must be done because falcon parse the query parameters differently depending on the encoding. :param query: The query parameter parsed by falcon. :return: Dict with the search criteria """ query = query.replace('=', ':').split(',') if isinstance(query, str) else [item.replace('=', ':') for item in query] if isinstance(query, str): query = [query] return dict(item.split(":") for item in query)