content
stringlengths
42
6.51k
def set_chef_url(asg_name): """Sets Chef server url based on autoscaling group name""" return { 'autoscaling-group': 'https://ip-xxx-xxx-xx-x.ec2.internal/organizations/acme' }[asg_name]
def rm_prefixes(sequences): """ Remove sequences which are prefixes of another sequence. This process can be done by linearly scanning the list and removing any element which is a prefix of or identical to the next element """ i = 0 while i < len(sequences) - 1: if sequences[i + 1].s...
def concat_multi_values(models, attribute): """ Format Mopidy model values for output to MPD client. :param models: the models :type models: array of :class:`mopidy.models.Artist`, :class:`mopidy.models.Album` or :class:`mopidy.models.Track` :param attribute: the attribute to use :type ...
def u2u3(u2): """ inch -> feet & inch u3 is a tuple of (feet, inch) """ f = u2//12 i = u2%12 inch_int = int(i//1) inch_frac = i%1 # 1/4" accuracy test = round(inch_frac/0.25) if test == 0: i = str(inch_int) elif test == 4: i = str(inch_int+1) elif test == 2: i = str(inch_int) + " 1/2" else: i = st...
def nonwhitespace(argument): """Return argument with all whitespace removed. This includes removing any single spaces within the string. """ return "".join(argument.split())
def date_parser(dates): """Date Parser - changes dates to date format 'yyyy-mm-dd' Parameters ---------- dates: list of dates and times strings in the format 'yyyy-mm-dd hh:mm:ss' Returns ------- list: A list of only the dates in 'yyyy-mm-dd' format. """ data_for...
def update_alert(id): """ Update an alert. """ return 'Not Implemented', 501
def preprocess_search_title(line): """ Title processing similar to PubmedXMLParser - special characters removal """ return line.strip('.[]')
def strip_quotes(want, got): """ Strip quotes of doctests output values: >>> strip_quotes("'foo'") "foo" >>> strip_quotes('"foo"') "foo" """ def is_quoted_string(s): s = s.strip() return (len(s) >= 2 and s[0] == s[-1] and s[0]...
def get_item(dictionary, key): """ :param dictionary: the dictionary where you want to access the data from :param key: the key of the dictionary where you want to access the data from :return: the content of the dictionary corresponding to the key entry or None if the key does not exists """ re...
def gene_panels(request, parsed_case): """Return a list with the gene panels of parsed case""" panels = parsed_case['gene_panels'] return panels
def list_to_string(inlist, endsep="and", addquote=False): """ This pretty-formats a list as string output, adding an optional alternative separator to the second to last entry. If addquote is True, the outgoing strings will be surrounded by quotes. Examples: no endsep: [1,2,3] -> '1, 2...
def get_sel_repfile_name(model, irep, pop, freqbin, normed = False, basedir = "/idi/sabeti-scratch/jvitti/scores/", suffix =""): """ locate simulated composite score file in scenario with selection """ repfilename = basedir + model + "/sel" + str(pop) + "/sel_" + str(freqbin) + "/composite/rep" + str(irep) + "_" + st...
def reverse_int(i): """ Given an integer, return an integer that is the reverse ordering of numbers. reverse_int(15) == 51 reverse_int(981) == 189 reverse_int(500) == 5 reverse_int(-15) == -51 reverse_int(-90) == -9 """ negative = i < 0 tmp = abs(i) tmp_str = str(tmp)[::-...
def isproximal(coords): """returns True if all components are within 1""" result = True if len(coords) != 1: for i in range(1, len(coords)): diff = abs(coords[i] - coords[i - 1]) if diff > 1: result = False break return result
def display_one_level_dict(dic): """ Single level dict to HTML Args: dic (dict): Returns: str for HTML-encoded single level dic """ html = "<ul>" for k in dic.keys(): # Open field val = str(dic[k]) html += f"<li>{k}: {val} </li>" html += "</ul>" r...
def _overall_stats(label, tuples): """ Computes overall accuracy; returns in 'Settings'-friendly format. Args: tuples([(int, int)]) Each entry is (# correct, # total) label (str) What to call this Returns: (str, str) key, val of settings column to add """ n_correct = sum(tp[0] for tp i...
def differentiate(coefficients): """ Calculates the derivative of a polynomial and returns the corresponding coefficients. """ new_cos = [] #ignore the first coefficient as it will always become 0 #when taking derivative of a polynomial for deg, prev_co in enumerate(coefficients[1:]): ...
def add_path(tdict, path): """ :param tdict: a dictionary representing a argument tree :param path: a path list :return: a dictionary """ t = tdict for step in path[:-2]: try: t = t[step] except KeyError: t[step] = {} t = t[step] t[pat...
def ip_to_hex(address): """return a ipv4 address to hexidecimal""" return ''.join(['%02X' % int(octet) for octet in address.split('.')])
def remove_empty_lines_from_string(string: str) -> str: """Remove empty lines from a string.""" return "".join(string.splitlines()).strip()
def escape_for_like(query: str) -> str: """Escape query string for use in (I)LIKE database queries.""" # Escape characters that have a special meaning in "like" queries return query.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
def _validate_int(s, accept_none = False): """ A validation method to convert input s to int or raise error if it is not convertable """ if s is None and accept_none : return None try: return int(s) except ValueError: raise ValueError('Could not convert "%s" to int' % s)
def txout_decompress(x): """ Decompresses the Satoshi amount of a UTXO stored in the LevelDB. Code is a port from the Bitcoin Core C++ source: https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L161#L185 :param x: Compressed amount to be decompressed. :type x: int :return: T...
def lerp(value_0: float, value_1: float, t: float): """ Returns a linearly interpolated value between value_0 and value_1, where value_0 is returned for t=0, value_1 for t=1, and a weighted average for any intermediate value. """ if t > 1: t == 1 if t < 0: t == 0 return val...
def letter_counts(sentence: str) -> dict: """ returns the unique counts of letters in the specified sentence :param sentence: the sentence :return: dictionary of counts per letter that exists in the sentence """ letters_in_sentence = [c for c in sentence if c.isalpha()] # use dictionary co...
def create_url_with_query_parameters(base_url: str, params: dict) -> str: """Creates a url for the given base address with given parameters as a query string.""" parameter_string = "&".join(f"{key}={value}" for key, value in params.items()) url = f"{base_url}?{parameter_...
def get_argnames(func): """Get the argument names from a function.""" # Get all positional arguments in __init__, including named # and named optional arguments. `co_varnames` stores all argument # names (including local variable names) in order, starting with # function arguments, so only grab `co...
def insertion(arr): """ :param arr: an array to be sorted :returns: sorted array """ # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current ...
def _json_clean(value): """JSON-encodes the given Python object.""" # JSON permits but does not require forward slashes to be escaped. # This is useful when json data is emitted in a <script> tag # in HTML, as it prevents </script> tags from prematurely terminating # the javscript. Some json librar...
def ensuretext(val): """Turn strings/lists of strings into unicode strings.""" if isinstance(val, list): return ' '.join([ensuretext(elt) for elt in val]) elif isinstance(val, str): return val elif isinstance(val, dict): return ' '.join(ensuretext(key) for key in val.keys()) ...
def get_normalized_string_from_dict(d): """ Normalized string representation with sorted keys. >>> get_normalized_string_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, }) 'bitrate_kbps_45_max_buffer_sec_5.0' """ return '_'.join(map(lambda k: '{k}_{v}'.format(k=k,v=d[k]), sorted(d.keys())))
def arm_processor_rules(info_data, rules): """Setup the default info for an ARM board. """ info_data['processor_type'] = 'arm' info_data['protocol'] = 'ChibiOS' if 'bootloader' not in info_data: if 'STM32' in info_data['processor']: info_data['bootloader'] = 'stm32-dfu' ...
def format_where_to_sql( ColToSearchIntoName ): """ in: ["Col1", "Col2"] out: "Col1 = %s AND Col2 = %s" """ sqls = [] for col in ColToSearchIntoName: sqls.append( "`{}` = %s".format(col) ) sql = " AND ".join(sqls) return sql
def make_title(string, n=10): """ Make separating title """ return '\n{0} {1} {0}\n'.format('=' * n, string)
def by_blanks(*parts): """return parts joined by blanks""" return ' '.join(parts)
def split(value, key=' '): """Returns the value turned into a list.""" return value.split(key)
def github(deps): """ Format GitHub dependencies. For example: deps = [ ("eresearchsa/flask-util", "ersa-flask-util", "0.4"), ("foo/bar", "my-package-name", "3.141") ] """ return ["https://github.com/%s/archive/v%s.tar.gz#egg=%s-%s" % (dep[0], dep[2], dep[1], dep[2]) ...
def naive_tokenizer(sentence): """Naive tokenizer: split the sentence by space into a list of tokens.""" return sentence.split()
def extract_test_prefix(raw_fullname): """Returns a (prefix, fullname) tuple corresponding to raw_fullname.""" fullname = raw_fullname.replace('FLAKY_', '').replace('FAILS_', '') test_prefix = '' if 'FLAKY_' in raw_fullname: test_prefix = 'FLAKY' elif 'FAILS_' in raw_fullname: # pragma: no cover te...
def unique_items(seq): """A function that returns all unique items of a list in an order-preserving way""" id_fn = lambda x: x seen_items = {} result = [] for item in seq: marker = id_fn(item) if marker in seen_items: continue seen_items[marker] = 1 result.append(item...
def all_in(word: str, match: str) -> bool: """ Return true if all letters in match are in the word """ for letter in match: if letter not in word: return False return True
def ifd(d, v1, v2, v3): """ Conditionally select a value depending on the given dimension number. Args: d (int): Dimension number (1, 2, or 3). v1: The value if d = 1. v2: The value if d = 2. v3: The value if d = 3. Returns: v1, v2 or v3. """ if d == 1:...
def element_0(c): """Generates first permutation with a given amount of set bits, which is used to generate the rest.""" return (1 << c) - 1
def reactionStrToInt(reactionStr): """ Groups GENIE reaction string into following categories Reactions can be divided into two basic categories: 1) CC, 2) NC These can then be further divided into subcategories of interaction modes 1) QES, 2) RES, 3)DIS, 4) COH And the target nucleon can b...
def normalize_dict(dict_): """ Replaces all values that are single-item iterables with the value of its index 0. :param dict dict_: Dictionary to normalize. :returns: Normalized dictionary. """ return dict([(k, v[0] if not isinstance(v, str) and len(v) == 1 else v) ...
def bounding_box(point, width): """Return bounding box of upper-left and lower-right corners.""" # pylint: disable=invalid-name d = width / 2. x, y = point return x - d, y - d, x + d, y + d
def find_prerequisites(reqs_in): """Add build-time pre-requisites for older libraries""" result = [] reqs_set = set(reqs_in.splitlines()) if any(line.startswith('markupsafe==1.0') for line in reqs_set): result.append('setuptools < 46') return '\n'.join(result)
def get_Uout_mean(membrane_geometry): """ dimensionless cross-sectional averaged Uout = 1 - (y/R)^2 (following Hagen-Poiseiulle-type flow profile) The cross-sectional average is taking as Eq. (22) in [2]. """ Uout_mean = 1/2. if (membrane_geometry=='FMM'): Uout_mean = 2/3. elif (membrane...
def check_int(s): """Sourced from helpful post from SO https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except""" if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()
def latlon_to_zone_number(latitude, longitude): """ Find the UTM zone number for a give latitude and longitude. If the input is a numpy array, just use the first element user responsibility to make sure that all points are in one zone :param latitude: float :param longitude: float :return: int """ if 56 <= l...
def get_new_goal(current_pos, current_dest, home_pos, rally_point, batt_level, blocking_time=10, speed=5, energy_consumption=1): """ Function for deciding the new goal All the input coordinates are in the format [LAT, LON] (deg). returns a [int, int] list with [X, Y] coordinates of n...
def invert_y_coord(coord_list): """ Convert [(x1,y1),(x2,y2),...] to [(x1,-y1),(x2,-y2),...] """ return [(x, -1 * y) for (x, y) in coord_list]
def get_case(detector): """select the way data are read """ if detector in ['id10_eiger_single_edf', 'pilatus_single_cbf', 'id02_eiger_single_edf']: case = 0 elif detector in ['p10_eiger_h5', 'converted_h5', 'lambda_nxs']: case = 1 elif detector == 'xcs_cspad_h5': case = 2 ...
def captured_article_ok(save_option, saved, post_option, posted): """ Given four boolean variables, return whether or not the article should be considered captured or not. save_option: Was the code required to save the article? saved: Did the code save the article? post_option: Was t...
def _both_names(meta, to_prom_name): """If the pathname differs from the promoted name, return a string with both names. Otherwise, just return the pathname. """ name = meta['pathname'] pname = to_prom_name[name] if name == pname: return "'%s'" % name else: return "'%s' (%s)"...
def query_decode(query): # type: (str) -> str """Replaces '+' for ' '""" return query.replace("+", " ")
def returnMarble(number): """Returns a string, red X for AI and black X for human player""" if (number =="1"): return "\033[91mX\033[0m" elif (number == "0"): return "X" else: return number
def standardize_uppercase(input: str) -> str: """Standardize string to upper case.""" return input.upper()
def _diff_dict(orig, new): """Return a dict describing how to change orig to new. The keys correspond to values that have changed; the value will be a list of one or two elements. The first element of the list will be either '+' or '-', indicating whether the key was updated or deleted; if the key...
def _shared_ptr(name, nbytes): """ Generate a shared pointer. """ return [ ("std::shared_ptr<unsigned char> {name}(" "new unsigned char[{nbytes}], " "[](unsigned char *d) {{ delete[] d; }});" .format(name=name, nbytes=nbytes)) ]
def break_syl(word): """ Splits a word in elements taking into account the semisyllabic nature of most of the iberian scripts (all letters but ka, ta, ba, etc.). E.g. biderogan --> ['bi', 'de', 'r', 'o', 'ga', 'n'] """ output = [] word = word.strip().replace(" ", "") for i, str_chr...
def shape2d(a): """ Ensure a 2D shape. Args: a: a int or tuple/list of length 2 Returns: list: of length 2. if ``a`` is a int, return ``[a, a]``. """ if type(a) == int: return [a, a] if isinstance(a, (list, tuple)): assert len(a) == 2 return list(a) ...
def reverse_dict(d): """ >>> reverse_dict({1: 'one', 2: 'two'}) # doctest: +SKIP {'one': 1, 'two': 2} """ new = dict() for k, v in d.items(): if v in d: raise ValueError("Repated values") new[v] = k return new
def genmatrix(list, combinfunc, symmetric=False, diagonal=None): """ Takes a list and generates a 2D-matrix using the supplied combination function to calculate the values. PARAMETERS list - the list of items combinfunc - the function that is used to calculate teh value in a cell. ...
def get_frame_shift(op): """ :param op: :return: """ if op[1] == "I": return len(op[2]) elif op[1] == "S": return 0 elif op[1] == "D": return -op[2]
def _check_last_word_phrased(phrased_word, word): """Check if a word is the last word of a phrased word.""" words_list = phrased_word.split("_") last_word = words_list[-1] return word == last_word
def mate_in_region(aln, regtup): """ Check if mate is found within region Return True if mate is found within region or region is None Args: aln (:obj:`pysam.AlignedSegment`): An aligned segment regtup (:tuple: (chrom, start, end)): Region Returns: bool: True if mate is within ...
def solve(task: str) -> int: """Count total group score.""" garbage_chars = 0 garbage = False escape = False for token in task.strip(): if escape: escape = False elif token == ">": garbage = False elif token == "!": escape = True e...
def __isnumber(value): """ Helper function to indicate whether an object passed is a float in another format. Example cases of truth: > value is an integer / float data type > value = '1,000', then the float value is 1000 > value = '1 000 000.00' then the float value is 1000000 ...
def memo(em: str, k: int, m: list): """ Helper method for dynamic programming method -> memoize :param em: encoded message :param k: :param m: memo lookup variable :return: int """ if k == 0: return 1 s = len(em) - k if em[s] == '0': return 0 if m[k] is no...
def load_uvarint_b(buffer): """ Variable int deserialization, synchronous from buffer. :param buffer: :return: """ result = 0 idx = 0 byte = 0x80 while byte & 0x80: byte = buffer[idx] result += (byte & 0x7F) << (7 * idx) idx += 1 return result
def gen_problem(params): """Convert parameters to be input to SALib. This function converts the params dictionary into a dictionary formatted to be input at the SALib as mean to generate the samples. Parameters ---------- params : dict Example: {"variable": {"bounds": [0, 1], "type": ...
def calc_average(input_list): """Input List median_distances Output average distance calculated """ if len(input_list) != 0: return sum(input_list)/len(input_list) else: return 0
def time_needed(nb_sec): """ Returns a string with nb_sec converted in hours, minutes and seconds. """ nb_heures = nb_sec // 3600 nb_min = (nb_sec - nb_heures * 3600) // 60 nb_s = (nb_sec - nb_heures * 3600 - nb_min * 60) return str(nb_heures) + " h " + str(nb_min) + "...
def drange(start, stop, step): """Like builtin range() but allows decimals and is a closed interval that is, it's inclusive of stop""" r = start lst = [] epsilon = 1e-3 * step while r <= stop+epsilon: lst.append(r) r += step return lst
def str_to_tuple(state_str: str) -> tuple: """'10-1' -> (1, 0, -1)""" temp = [s for s in state_str] state = [] i = 0 while i < len(temp): try: st = int(temp[i]) i += 1 except ValueError: st = int(''.join(temp[i:i+2])) i += 2 ...
def reverse(network): """Reverses a network """ rev = {} for node in network.keys(): rev[node] = [] for node in network.keys(): for n in network[node]: rev[n].append(node) return rev
def get_count(row): """Get count from a query result ``row``: Row object of a db query result """ if row: count = row.c # c as count by name convention else: count = 0 return count
def convert_sexa(ra,de): """ this peculiar function converts something like '18:29:56.713', '+01.13.15.61' to '18h29m56.713s', '+01d13m15.61s' It's a mystery why the output format from casa.sourcefind() has this peculiar H:M:S/D.M.S format """ ran = ra....
def min_max(values): """ Returns a tuple with the min and max values contained in the iterable ```values``` :param values: an iterable with comparable values :return: a tuple with the smallest and largest values (in this order) """ min_ = None max_ = None for val in values: # Need t...
def table_to_string(a_table): """Convert a table to a string list. Parameters ---------- a_table : astropy.table.table.Table The table to convert to a string Returns ------- result : sequence of strings A sequence of strings, where each string is one row with comma-separat...
def move_down_right(rows, columns, t): """ A method that takes coordinates of the bomb, number of rows and number of columns of the matrix and returns coordinates of neighbour which is located at the right-hand side and bellow the bomb. It returns None if there isn't such a neighbour """ x, y =...
def sort(plugins): """Sort `plugins` in-place Their order is determined by their `order` attribute, which defaults to their standard execution order: 1. Selection 2. Validation 3. Extraction 4. Conform *But may be overridden. Arguments: plugins (list): Plu...
def mock_shutil_which_None(*args, **kwargs): """ Mock a call to ``shutil.which()`` that returns None """ print("[mock] shutil.which - NotFound") #if True: raise FileNotFoundError("Generated by MOCK") return None
def is_mobile(m): """Return whether m is a mobile.""" return type(m) == list and len(m) == 3 and m[0] == 'mobile'
def isMatch(peak, biomarker, tolerance): """Check if spectral peak matches protein biomarker Args: peak: Spectral peak obatained from experiment, float biomarker: An array of biomarker values tolerance: Maximal difference between experimental weight and theoretical one that coul...
def abbreviate(kebab): """Abbreviate a kebab-case string with the first letter of each word.""" kebab_words = kebab.split('-') letters = list() for word in kebab_words: letters.extend(word[0]) return ''.join(letters)
def get_budget_response(budget_name, budget_limit_amount, calculated_actual_spend, calculated_forecasted_spend): """Returns a mocked response object for the get_budget call :param budget_name: (str) the budget name :param budget_limit_amount: (float) the budget value :param calc...
def recombination(temperature): """ Calculates the case-B hydrogen recombination rate for a gas at a certain temperature. Parameters ---------- temperature (``float``): Isothermal temperature of the upper atmosphere in unit of Kelvin. Returns ------- alpha_rec (``float``): ...
def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9)
def conjugate_wc(wc_dict): """Given a dictionary of Wilson coefficients, return the dictionary where all coefficients are CP conjugated (which simply amounts to complex conjugation).""" return {k: v.conjugate() for k, v in wc_dict.items()}
def svg_ellipse_to_path(cx, cy, rx, ry): """Convert ellipse SVG element to path""" if rx is None or ry is None: if rx is not None: rx, ry = rx, rx elif ry is not None: rx, ry = ry, ry else: return "" ops = [] ops.append(f"M{cx + rx:g},{cy:g}")...
def get_rect_ymax(data): """Find maximum y value from four (x,y) vertices.""" return max(data[0][1], data[1][1], data[2][1], data[3][1])
def get_html_lang_attribute(language_code: str) -> str: """ return the HTML lang attribute for a given language code, e. g. "en-us" -> "en", "en" -> "en" """ try: pos = language_code.index("-") except ValueError: # no "-" in language_code return language_code return l...
def replace_spaces(s): """ :param s: original string :return: string without space """ new_s = s.replace(' ', '%20') return new_s
def find_from(string, subs, start = None, end = None): """ Returns a tuple of the lowest index where a substring in the iterable "subs" was found, and the substring. If multiple substrings are found, it will return the first one. If nothing is found, it will return (-1, None) """ string = string...
def show_size(s): """String that translates size in bytes to kB, Mb, etc.""" return '%d %.2f kB %.2f Mb %.2f Gb' % (s, s / 1024., s / (1024. * 1024.), s / (1024. * 1024. * 1024.))
def LCS1(a, b, i, j): """ LCS recursion """ if i >= len(a) or j >= len(b): return 0 elif a[i] == b[j]: return 1 + LCS1(a, b, i+1, j+1) else: return max(LCS1(a, b, i+1, j), LCS1(a, b, i, j+1))
def _find_direct_matches(list_for_matching, list_to_be_matched_to): """ Find all 100% matches between the values of the two iterables Parameters ---------- list_for_matching : list, set iterable containing the keys list_to_be_matched_to : list, set iterable containing the values...