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].startswith(sequences[i]): del(sequences[i]) else: i += 1 return sequences
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 attribute: string :rtype: string """ # Don't sort the values. MPD doesn't appear to (or if it does it's not # strict alphabetical). If we just use them in the order in which they come # in then the musicbrainz ids have a higher chance of staying in sync return ';'.join( getattr(m, attribute) for m in models if getattr(m, attribute, None) is not None )
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 = str(inch_int) + " " + str(test) + "/4" return (str(int(f)), i)
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_format = [] #Empty list. for i in dates: #Iterate over elements of dates. x = i.split(" ")[0] #Split the strings in dates to get rid of the times. data_format.append(x) #append splitted strings to the empty list 'data_format' return data_format #Return the new list 'data_format'.
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] in ('"', "'")) def is_quoted_unicode(s): s = s.strip() return (len(s) >= 3 and s[0] == 'u' and s[1] == s[-1] and s[1] in ('"', "'")) if is_quoted_string(want) and is_quoted_string(got): want = want.strip()[1:-1] got = got.strip()[1:-1] elif is_quoted_unicode(want) and is_quoted_unicode(got): want = want.strip()[2:-1] got = got.strip()[2:-1] return want, got
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 """ return dictionary.get(key, None)
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, 3' with endsep=='and': [1,2,3] -> '1, 2 and 3' with addquote and endsep [1,2,3] -> '"1", "2" and "3"' """ if not endsep: endsep = "," else: endsep = " " + endsep if not inlist: return "" if addquote: if len(inlist) == 1: return "\"%s\"" % inlist[0] return ", ".join("\"%s\"" % v for v in inlist[:-1]) + "%s %s" % (endsep, "\"%s\"" % inlist[-1]) else: if len(inlist) == 1: return str(inlist[0]) return ", ".join(str(v) for v in inlist[:-1]) + "%s %s" % (endsep, inlist[-1])
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) + "_" + str(pop) + ".cms" if suffix is not None: repfilename += suffix if normed: repfilename += ".norm" return repfilename
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)[::-1] if negative: tmp_str = '-' + tmp_str return int(tmp_str)
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>" return html
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 in tuples) n_total = sum(tp[1] for tp in tuples) return 'OVERALL %s acc' % (label), '%d/%d (%0.2f%%)' % ( n_correct, n_total, (n_correct*100.0)/n_total)
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:]): #use (deg+1) because we have ignore first coefficient but #array indexing still starts from 0 #so a^2 will become 2a new_cos.append((deg+1) * prev_co) #return update coefficients return new_cos
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[path[-2]] = path[-1] return tdict
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: The decompressed amount of satoshi. :rtype: int """ if x == 0: return 0 x -= 1 e = x % 10 x //= 10 if e < 9: d = (x % 9) + 1 x //= 9 n = x * 10 + d else: n = x + 1 while e > 0: n *= 10 e -= 1 return n
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 value_0 + t * (value_1 - value_0)
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 comprehension to create the frequency data frequency_data = {c: letters_in_sentence.count(c) for c in set(letters_in_sentence)} return frequency_data
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_string}" return url
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_argcount` varnames. code = getattr(func, '__func__', func).__code__ argcount = code.co_argcount return code.co_varnames[:argcount]
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 position j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr
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 libraries do this escaping by default, # although python's standard library does not, so we do it here. # http://stackoverflow.com/questions/1580647/\ # json-why-are-forward-slashes-escaped return value.replace("</", "<\\/")
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()) else: # n.b. in Python 2, the builtins import makes this mean `unicode`. return str(val)
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' else: info_data['bootloader'] = 'unknown' if 'STM32' in info_data['processor']: info_data['platform'] = 'STM32' elif 'MCU_SERIES' in rules: info_data['platform'] = rules['MCU_SERIES'] elif 'ARM_ATSAM' in rules: info_data['platform'] = 'ARM_ATSAM' return info_data
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]) for dep in deps]
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 test_prefix = 'FAILS' return (test_prefix, fullname)
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) return result
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: return v1 elif d == 2: return v2 elif d == 3: return v3 else: raise ValueError("Invalid dimension: %s." % d)
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 be either: 1) n, 2) p, 3) other (e.g. C12 in case of COH) We use a three digit integer to represent all the different possibilities, with the order being: first digit = target_nucleon second digit = CC_NC third digit = interaction_mode In the case of a string that doesn't fit any of the possibilities, a "0" is returned """ reactionInt = 0 if 'QES' in reactionStr: reactionInt += 1 elif 'RES' in reactionStr: reactionInt += 2 elif 'DIS' in reactionStr: reactionInt += 3 elif 'COH' in reactionStr: reactionInt += 4 if 'CC' in reactionStr: reactionInt += 10 elif 'NC' in reactionStr: reactionInt += 20 if '2112' in reactionStr: reactionInt += 100 elif '2212' in reactionStr: reactionInt += 200 else: reactionInt += 300 return reactionInt
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) for k, v in list(dict_.items())])
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_geometry=='FMS'): Uout_mean = 2/3. return Uout_mean
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 <= latitude < 64 and 3 <= longitude < 12: return 32 if 72 <= latitude <= 84 and longitude >= 0: if longitude < 9: return 31 elif longitude < 21: return 33 elif longitude < 33: return 35 elif longitude < 42: return 37 return int((longitude + 180) / 6) + 1
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 new destination """ new_destination = [None, None] return new_destination
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 elif detector == 'id02_eiger_multi_edf': case = 3 else: case = -1 return case
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 the code required to post the article? posted: Did the code post the article? """ # Nothing to do with article, mark as done. if save_option == False and post_option == False: return True # Only requested saving and it saved: if saved == True and post_option == False: return True # Only requested posting and it posted: if posted == True and save_option == False: return True # Did both saving and posting: if saved == True and posted == True: return True return False
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)" % (name, pname)
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 was updated, the list will contain a second element, giving the updated value. """ # Figure out what keys went away result = {k: ['-'] for k in set(orig.keys()) - set(new.keys())} # Compute the updates for key, value in new.items(): if key not in orig or value != orig[key]: result[key] = ['+', value] return result
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 in enumerate(word): if str_chr in ("k", "g", "d", "t", "b"): output.append(str_chr) if i < len(word) - 1 and (word[i + 1] not in ("a", "e", "i", "o", "u")): output.append("e ") elif i == len(word) - 1: output.append("e ") else: output.append(str_chr) output.append(" ") output = "".join(output).strip() return output.split(" ")
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) raise RuntimeError("Illegal shape: {}".format(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. It has to cope with two arguments. symmetric - Whether it will be a symmetric matrix along the diagonal. For example, it the list contains integers, and the combination function is abs(x-y), then the matrix will be symmetric. Default: False diagonal - The value to be put into the diagonal. For some functions, the diagonal will stay constant. An example could be the function "x-y". Then each diagonal cell will be "0". If this value is set to None, then the diagonal will be calculated. Default: None """ matrix = [] row_index = 0 for item in list: row = [] col_index = 0 for item2 in list: if diagonal is not None and col_index == row_index: # if this is a cell on the diagonal row.append(diagonal) elif symmetric and col_index < row_index: # if the matrix is symmetric and we are "in the lower left triangle" row.append( matrix[col_index][row_index] ) else: # if this cell is not on the diagonal row.append(combinfunc(item, item2)) col_index += 1 matrix.append(row) row_index += 1 return matrix
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 region """ if regtup is None: return True return aln.next_reference_id == regtup[0] and \ regtup[1] < aln.next_reference_start < regtup[2]
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 elif garbage: garbage_chars += 1 elif token == "{": pass elif token == "}": pass elif token == "<": garbage = True return garbage_chars
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 Example cases of false: > Anything else Parameters ---------- value : mixed type Can be an int, float, string, or None type Returns ------- x : Bool A bool indicating whether the object passed is actually a float """ if value == None: # Deal with Null values x = False elif type(value) == int or type(value) == float: # Easy case, numbers x = True elif type(value) == str: # Find the strings that contain numbers test_val = value.replace(',','').replace(' ','') # We need to deal with a couple corner cases - these come from only a couple indicators try: float(test_val) x = True except ValueError: x = False else: raise Exception('Incompatible data type. Review logic.') return x
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 not None: return m[k] result = memo(em, k - 1, m) if k >= 2 and int(em[s:s + 2]) <= 26: result += memo(em, k - 2, m) m[k] = result return result
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": "int"}} Returns ------- dict Formatted to be input into SALib sampling """ n_vars = len(params) problem = {"num_vars": n_vars, "names": [], "bounds": []} for key in params.keys(): problem["names"] += [key] if "type" in params[key].keys(): bd = params[key]["bounds"] if params[key]["type"] == "int": bd[-1] += 1 problem["bounds"] += [bd] else: problem["bounds"] += [params[key]["bounds"]] return problem
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) + " min " + str(nb_s) + "s"
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 state.append(st) return tuple(state)
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.replace(':','h',1).replace(':','m',1)+'s' den = de.replace('.','d',1).replace('.','m',1)+'s' return ran,den
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 to take care of the fact that None < (anything else) if not min_: min_ = val if val < min_: min_ = val if val > max_: max_ = val return min_, max_
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-separated column values """ result = list() for element in a_table: result.append(str(list(element)).strip('[]')) return result
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 = t if x == rows or y == columns: return None else: return (x + 1, y + 1)
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): Plug-ins to sort """ if not isinstance(plugins, list): raise TypeError("plugins must be of type list") plugins.sort(key=lambda p: p.order) return plugins
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 could be considered a match. float Return: True / False """ for each in biomarker: if abs(float(peak) - each) <= float(tolerance): return True return False
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 calculated_actual_spend: (float) the current actual spend :param calculated_forecasted_spend: (float) the forecasted cost according to AWS :return: the response object """ return { "Budget": { "BudgetName": budget_name, "BudgetLimit": { "Amount": str(budget_limit_amount), "Unit": "USD" }, "CostTypes": { "IncludeTax": True, "IncludeSubscription": True, "UseBlended": False, "IncludeRefund": True, "IncludeCredit": True, "IncludeUpfront": True, "IncludeRecurring": True, "IncludeOtherSubscription": True, "IncludeSupport": True, "IncludeDiscount": True, "UseAmortized": False }, "TimeUnit": "MONTHLY", "TimePeriod": { "Start": 1556668800.0, "End": 3706473600.0 }, "CalculatedSpend": { "ActualSpend": { "Amount": str(calculated_actual_spend), "Unit": "USD" }, "ForecastedSpend": { "Amount": str(calculated_forecasted_spend), "Unit": "USD" } }, "BudgetType": "COST", "LastUpdatedTime": 1559530911.092 } }
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``): Recombination rate of hydrogen in units of cm ** 3 / s. """ alpha_rec = 2.59E-13 * (temperature / 1E4) ** (-0.7) return alpha_rec
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}") ops.append(f"A{rx:g},{ry:g},0,0,1,{cx:g},{cy + ry:g}") ops.append(f"A{rx:g},{ry:g},0,0,1,{cx - rx:g},{cy:g}") ops.append(f"A{rx:g},{ry:g},0,0,1,{cx:g},{cy - ry:g}") ops.append(f"A{rx:g},{ry:g},0,0,1,{cx + rx:g},{cy:g}") ops.append("z") return " ".join(ops)
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 language_code[:pos]
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[start:end] last_index = len(string) substring = None for s in subs: i = string.find(s) if i != -1 and i < last_index: last_index = i substring = s if last_index == len(string): return (-1, None) return (last_index, substring)
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 to match to the keys Returns ------- matched : dict all 100% matches """ matches = dict() for entry_a in list_for_matching.copy(): if entry_a in list_to_be_matched_to: matches[entry_a] = entry_a list_for_matching.remove(entry_a) list_to_be_matched_to.remove(entry_a) return matches