content
stringlengths
42
6.51k
def messages_contains_prefix(prefix, messages): """ REturns true if any of the keys of message start with prefix. :param prefix: :param messages: :return: """ return any(map(lambda x: x.startswith(prefix), messages.keys()))
def is_prime(n): """ judege n is prime or not. :param n: a number :return: a boolean """ if n < 2: return False if n == 2: return True for m in range(2, int(n ** 0.5) + 1): if (n % m) == 0: return False else: return True
def from_ms(time: int) -> str: """ Convert millisconds into a string in format mm:ss.ms """ minute = time // 60_000 second = time // 1000 - minute * 60 millisecond = time - minute * 60_000 - second * 1000 if second < 10: second = "0" + str(second) else: second = str(second) if millisecond < 10: millisecond = f"00{millisecond}" elif millisecond < 100: millisecond = f"0{millisecond}" else: millisecond = str(millisecond) return f"{minute}:{second}.{millisecond}"
def square_digits(num): """Function takes an integer and returns an integer.""" temp = [int(x) ** 2 for x in list(str(num))] return int(''.join(map(str, temp)))
def package_name(s): """Validate a package name for argparse.""" if s[0] == '-': raise ValueError return s
def __get_windazimuth(winddirection): """Get an estimate wind azimuth using the winddirection string.""" if not winddirection: return None dirs = {'N': 0, 'NNO': 22.5, 'NO': 45, 'ONO': 67.5, 'O': 90, 'OZO': 112.5, 'ZO': 135, 'ZZO': 157.5, 'Z': 180, 'ZZW': 202.5, 'ZW': 225, 'WZW': 247.5, 'W': 270, 'WNW': 292.5, 'NW': 315, 'NNW': 237.5, 'NNE': 22.5, 'NE': 45, 'ENE': 67.5, 'E': 90, 'ESE': 112.5, 'SE': 135, 'SSE': 157.5, 'S': 180, 'SSW': 202.5, 'SW': 225, 'WSW': 247.5 } try: return dirs[winddirection.upper()] except: # noqa E722 return None
def get_position(row_index, col_index, board_size): """ (int, int, int) -> int Precondition: 0 < row_index <= board_size and 0 < col_index <= board_size and 1 <= board_size <= 9 Return the str_index of the cell in the string representation of the game board corresponding to the given row and column indices. >>> get_position(2, 1, 4) 4 >>> get_position(3 ,1, 3) 6 """ return (row_index - 1) * board_size + col_index - 1
def subs_tvars(obj, params, argitems): """If obj is a generic alias, substitute type variables params with substitutions argitems. For example, if obj is list[T], params is (T, S), and argitems is (str, int), return list[str]. If obj doesn't have a __parameters__ attribute or that's not a non-empty tuple, return a new reference to obj. """ subparams = getattr(obj, "__parameters__", ()) if not subparams or not isinstance(subparams, tuple): return obj nparams = len(params) nsubparams = len(subparams) subargs = [] for arg in subparams: try: arg = argitems[params.index(arg)] except ValueError: pass subargs.append(arg) return obj[tuple(subargs)]
def join_ingredients(ingredients_listlist): """Join multiple lists of ingredients with ' , '.""" return [' , '.join(i) for i in ingredients_listlist]
def filter_hostname(host: str): """Remove unused characters and split by address and port.""" host = host.replace('http://', '').replace('https://', '').replace('/', '') port = 443 if ':' in host: host, port = host.split(':') return host, port
def versiontuple(v): """utility for compare dot separate versions. Fills with zeros to proper number comparison""" filled = [] for point in v.split("."): filled.append(point.zfill(8)) return tuple(filled)
def pytest_make_parametrize_id(config, val, argname): """Pytest hook for user-friendly test name representation""" def get_dict_values(d): """Unwrap dictionary to get all values of nested dictionaries""" if isinstance(d, dict): for v in d.values(): yield from get_dict_values(v) else: yield d keys = ["device", "model"] values = {key: val[key] for key in keys} values = list(get_dict_values(values)) return "-".join(["_".join([key, str(val)]) for key, val in zip(keys, values)])
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = "&><\"'" to_symbols = ("&" + s + ";" for s in "amp gt lt quot apos".split()) for from_, to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) return data
def safe(val): """Be careful """ if val is None: return None return float(val)
def if_init(net, name, dat_name, dat_layout, mode=None): """Return value for interface parameter / variable. Parameters: ----------- net : dict Complete network dictionary containing all nps, sps, plasts, ifs. name : str The unique string identifier for the interface. ident : int The unique process id for the process of this interface. param : dict Dictionary of core parameters. mn : MetaNetwork deprecated """ # Default return is None. dat_value = None # Return initialized value. return dat_value
def camelcase_text(text: str): """Converts text that may be underscored into a camelcase format""" return text[0] + "".join(text.title().split('_'))[1:]
def keypad(coords): """ Takes a tuple of coordinates (x,y) and returns corresponding keypad number """ x = coords[0] y = coords[1] key = [ ["N", "N", 1, "N", "N"], ["N", 2, 3, 4, "N"], [5, 6, 7, 8, 9], ["N", "A", "B", "C", "N"], ["N", "N", "D", "N", "N"]] return key[x][y]
def generate_roman_number(n: int) -> str: """ Allowed roman numbers: IV, VI, IX, XI, XC, LC, XXXIX, XLI Disallowed: IIV, VIIII, XXXX, IXL, XIL """ if n > 4000: raise ValueError(f'Input too big: {n}') number_list = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] string_as_list = [] for divisor, character in number_list: if n >= divisor: count, n = divmod(n, divisor) string_as_list.extend(count * [character]) return ''.join(string_as_list)
def get_car_changing_properties(car): """ Gets cars properties that change during a trip :param car: car info in original system JSON-dict format :return: dict with keys mapped to common electric2go format """ return { 'lat': car['Lat'], 'lng': car['Lon'], 'address': car['Address'], 'fuel': car['Fuel'] }
def binomial(n, k): """ Binomial coefficients, thanks to Andrew Dalke. """ if 0 <= k <= n: n_tok = 1 k_tok = 1 for t in range(1, min(k, n - k) + 1): n_tok *= n k_tok *= t n -= 1 return n_tok // k_tok else: return 0
def is_command(text: str) -> bool: """ Checks if `text` is a command. Telegram chat commands start with the '/' character. :param text: Text to check. :return: True if `text` is a command, else False. """ if text is None: return False return text.startswith('/')
def _slice_list(obj): """ Return list of all the slices. Example ------- >>> _slice_list((slice(1,2), slice(1,3), 2, slice(2,4), 8)) [slice(1, 2, None), slice(1, 3, None), slice(2, 3, None), slice(2, 4, None), slice(8, 9, None)] """ result = [] if not isinstance(obj, (tuple, list)): return result for i, o in enumerate(obj): if isinstance(o, int): result.append(slice(o, o+1)) elif isinstance(o, slice): result.append(o) return result
def inc_statement(revenue, cogs, sg_a, d_and_a, int_exp, tax, other_revenue = 0): """ Computes the main income statement items. Parameters ---------- revenue : int or float Revenue for the period cogs : int or float Cost of goods sold sg_a : int or float Selling, general and administrative cost d_and_a : int or float Depreciation and amortizatin int_exp : int or float Interest expense tax : int or float Income tax other_revenue : int or float Optional, other revenue Returns ------- out : dict Returns a dictionary with income statement items; total revenue, gross profit, ebitda, ebit, ebt, net income """ total_revenue = revenue + other_revenue gross_profit = total_revenue - cogs ebitda = gross_profit - sg_a ebit = ebitda - d_and_a ebt = ebit - int_exp net_income = ebt - tax income_dict = { "total_revenue" : total_revenue, "gross_profit" : gross_profit, "ebitda" : ebitda, "ebit" : ebit, "ebt" : ebt, "net_income" : net_income } return income_dict
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. Args: inlist (list): The list to print. endsep (str, optional): If set, the last item separator will be replaced with this value. Oxford comma used for "and" and "or". addquote (bool, optional): This will surround all outgoing values with double quotes. Returns: liststr (str): The list represented as a string. Examples: ```python # no endsep: [1,2,3] -> '1, 2, 3' # with endsep=='and': [1,2,3] -> '1, 2, and 3' # with endsep=='that delicious': [7,8,9] -> '7, 8 that delicious 9' # with addquote and endsep [1,2,3] -> '"1", "2" and "3"' ``` """ if not endsep: endsep = "," elif endsep in ("and", "or") and len(inlist) > 2: 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 vote_smart_state_filter(one_state): """ Filter down the complete dict from Vote Smart to just the fields we use locally :param one_state: :return: """ one_state_filtered = { 'stateId': one_state['stateId'], 'name': one_state['name'], } return one_state_filtered
def get_percentage(numerator, denominator, precision = 2): """ Return a percentage value with the specified precision. """ return round(float(numerator) / float(denominator) * 100, precision)
def _compute_metrics(tp, fp, fn): """Computes precision, recall and f1-score from count of TP, TN and FN. Args: tp (int): The number of true positives. fp (int): The number of false positives. fn (int): The number of false negatives. Returns: dict (str -> float): Dictionary including 'precision', 'recall' and 'f1_score'. """ res = {} res['precision']=tp/(tp+fp) res['recall']=tp/(tp+fn) res['f1_score']=2*res['precision']*res['recall']/(res['precision']+res['recall']) return res
def convert_to_demisto_sensitivity(dg_classification: str) -> str: """ Convert dg_classification to demisto sensitivity :param dg_classification: :return: """ demisto_sensitivity = 'none' if dg_classification: if dg_classification[-3:] == 'ext': demisto_sensitivity = 'Critical' elif dg_classification[-3:] == 'IGH': demisto_sensitivity = 'High' elif dg_classification[-3:] == 'MED': demisto_sensitivity = 'Medium' elif dg_classification[-3:] == 'LOW': demisto_sensitivity = 'Low' return demisto_sensitivity
def treat_category(category: str) -> str: """ Treats a list of string Args: category (str): the category of an url Returns: str: the category treated """ return category.lower().strip()
def BuildAdGroupCriterionOperations(adgroid, keywo): """Builds the operations adding a Keyword Criterion to each AdGroup. Args: adgroup_operations: a list containing the operations that will add AdGroups. number_of_keywords: an int defining the number of Keywords to be created. Returns: a list containing the operations that will create a new Keyword Criterion associated with each provided AdGroup. """ criterion_operations = [ { # The xsi_type of the operation can usually be guessed by the API # because a given service only handles one type of operation. # However, batch jobs process operations of different types, so # the xsi_type must always be explicitly defined for these # operations. 'xsi_type': 'AdGroupCriterionOperation', 'operand': { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': adgroid[i], 'criterion': { 'xsi_type': 'Keyword', # Make 50% of keywords invalid to demonstrate error handling. 'text': keywo[i], 'matchType': 'EXACT' } }, 'operator': 'ADD' } for i in range(0, len(adgroid))] return criterion_operations
def args2dict(args): """ Transform string with arguments into dictionary with them. :param args: input string. :return: dictionary with parsed arguments """ arg_dict = {} for argument in args: key, value = argument.split('=') if value.startswith('\\'): arg_dict[key] = value[1:] else: arg_dict[key] = value return arg_dict
def getGlobalParams(config): """Try to parse out global parameters from the places it could be""" globalParams = None try: globalParams = config["GlobalParameters"] except (TypeError, LookupError): pass return globalParams
def low_dim_sim_keops_dist(x, a, b, squared=False): """ Smooth function from distances to low-dimensional simiarlity. Compatible with keops :param x: keops.LazyTensor pairwise distances :param a: float shape parameter a :param b: float shape parameter b :param squared: bool whether input distances are already squared :return: np.array low-dimensional similarities """ if not squared: return 1.0 / (1.0 + a * x ** (2.0 * b)) return 1.0 / (1.0 + a * x ** b)
def _get_effect_strings(*args): """ Given *args[0], figure out which parameters should be printed. 'basic' = fundamental parameters of the model or effect described by args[0] 'additional' = any additional fundamental parameters (an extension of 'basic') 'alternate' = possible substitutions for the fundamental parameters 'optional' = parameters that may also be specified for the given model type. e.g. 'FSPL' returns basic = [t_0, u_0, tE], additional = [rho, s, q, alpha], alternate = [t_eff, t_star], and optional = [pi_E or pi_E_N, pi_E_E] """ basic = None additional = [] alternate = [] optional = [] args_0 = args[0].lower().replace(" ", "") # number of lenses if args_0 == 'pointlens' or args_0[2:4] == 'pl': basic = 'point lens' alternate.append('point lens alt') if args_0 == 'binarylens': basic = 'binary lens' if args_0[2:4] == 'bl': basic = 'point lens' additional.append('binary lens') alternate.append('point lens alt') alternate.append('binary lens alt') # Effects if args_0 == 'finitesource': basic = 'finite source' alternate.append('finite source alt') if args_0[0:2] == 'fs': additional.append('finite source') alternate.append('finite source alt') if args_0 == 'parallax': basic = 'parallax' optional.append('parallax opt') if len(args[0]) == 4: optional.append('parallax') optional.append('parallax opt') if args[0].lower() == 'lens orbital motion': basic = 'lens orbital motion' optional.append('lens orbital motion opt') if len(args[0]) == 4 and args[0][2:4].lower() == 'bl': optional.append('lens orbital motion') optional.append('lens orbital motion opt') return { 'basic': basic, 'additional': additional, 'alternate': alternate, 'optional': optional}
def _seed_npy_before_worker_init(worker_id, seed, worker_init_fn=None): """ Wrapper Function to wrap the existing worker_init_fn and seed numpy before calling the actual ``worker_init_fn`` Parameters ---------- worker_id : int the number of the worker seed : int32 the base seed in a range of [0, 2**32 - (1 + ``num_workers``)]. The range ensures, that the whole seed, which consists of the base seed and the ``worker_id``, can still be represented as a unit32, as it needs to be for numpy seeding worker_init_fn : callable, optional will be called with the ``worker_id`` after seeding numpy if it is not ``None`` """ try: import numpy as np np.random.seed(seed + worker_id) except ImportError: pass if worker_init_fn is not None: return worker_init_fn(worker_id)
def check_accelerator(msgid, msgstr, line_warns): """check if accelrator &x is the same in both strings""" msgid = msgid.lower() msgstr = msgstr.lower() p1 = msgid.find('&') if p1 >= 0: a1 = msgid[p1:p1 + 2] p2 = msgstr.find('&') if p2 < 0 and len(a1) > 1: if a1[-1] in msgstr: # warn if there is no accelerator in translated version # but "accelerated" letter is available line_warns.append('acc1') return 1 else: a2 = msgstr[p2:p2 + 2] if a1 != a2: #line_warns.append('acc2') return 0 # ok they can be different return 0
def first_item_split_on_space(x): """ Brute force extract the first part of a string before a space. """ return str(x).split()[0]
def update_q(reward, gamma, alpha, oldQ, nextQ): """ Where nextQ is determined by the epsilon greedy choice that has already been made. """ newQ = oldQ + alpha * (reward + ((gamma*nextQ) - oldQ)) return newQ
def kind(n, ranks): """Return the first rank that this hand has exactly n of. Return None if there no n-of-a-kind in the hand.""" # Solution for r in ranks: if ranks.count(r) == n: return r return None # # Your code here. # n_of_kind = ranks[0:n] # if len(ranks) == 0: # return None # elif all(rank == ranks[0] for rank in n_of_kind) and ranks[n] != ranks[0]: # if n == 1: # if ranks[0] != ranks[1]: # return ranks[0] # else: # return None # if n == 2: # if ranks[0] == ranks[1]: # return ranks[0] # else: # return None # if n == 3: # if ranks[0] == ranks[1] == ranks[2]: # return ranks[0] # else: # return None # if n == 4: # if ranks[0] == ranks[1] == ranks[2] == ranks[3]: # return ranks[0] # else: # return None # else: # return None
def first_and_last(a): """ Finds first and last elements in a list Args: a: the list Returns: The first and last elements in the list Raises: IndexError: if passed an empty list TypeError: if passed an object which is not a list """ if not isinstance(a, list): raise TypeError if len(a) < 2: raise IndexError return [a[0],a[-1]]
def probe_set_name_starts_with_one_of(gene_prefixes): """Returns a string that can be used with pandas.DataFrame.query""" return " | ".join( f"`Probe.Set.Name`.str.startswith('{prefix}', na=False)" for prefix in gene_prefixes )
def d_y_diffr_dx(x, y): """ derivative of d(y/r)/dx equivalent to second order derivatives dr_dxy :param x: :param y: :return: """ return -x*y / (x**2 + y**2)**(3/2.)
def generate_vm_name_str(vms): """ Generate a str with concatenation of given list of vm name """ # vms is a list of vm_name # example: vms=["vm1", "vm2"] # the return value is a string like this "vm1,vm2"" res = "" for vm in vms: # vm[0] is vm_uuid, vm has format (vm_uuid) res = res + vm res = res + "," if res: res = res[:-1] return res
def divided_and_show_pct(a, b): """ Two period of data change in pecentage (without %) """ return round((float(a) / float(b)) * 100, 2)
def problem3(number): """Prime Factorization""" i = 2 while i * i < number: while number % i == 0: number /= i i += 1 return int(number)
def ignore(*args): """ Calls function passed as argument zero and ignores any exceptions raised by it """ try: return args[0](*args[1:]) except Exception: pass
def class_names(obj): """Format class attribute value. :param obj: class names object :type obj: iterable or dict :returns: class attribute value :rtype: str """ try: class_items = obj.items() except AttributeError: class_list = obj else: class_list = (class_name for class_name, value in class_items if value) return ' '.join(class_name.strip() for class_name in class_list)
def str2bool(val): """ convert string to bool (used to pass arguments with argparse) """ dict = {'True': True, 'False': False, 'true': True, 'false': False, '1': True, '0': False} return dict[val]
def str_to_c2count(string): """ :param string: a str :return: a dict mapping from each one-character substring of the argument to the count of occurrences of that character """ count = {} for character in string: if character in count: count[character] += 1 else: count[character] = 1 return count
def _check_histogram(hist, value): """ Obtains a score of a value according to an histogram, between 0.0 and 1.0 """ i = 0 while i < len(hist[1]) and value > hist[1][i]: i += 1 if i == 0 or i == len(hist[1]): return 0.0 else: return hist[0][i - 1]
def _get_obj_id_from_binding(router_id, prefix): """Return the id part of the router-binding router-id field""" return router_id[len(prefix):]
def binary_search(arr, target): """ Searches for first occurance of the provided target in the given array. If target found then returns index of it, else None Time Complexity = O(log n) Space Complexity = O(1) """ first = 0; last = len(arr) - 1 while first <= last: # calculate mid point mid = (last + first) // 2 # target found then return else adjust first and last if arr[mid] == target: return mid if arr[mid] > target: # search left last = mid - 1 if arr[mid] < target: # search right first = mid + 1 return None
def ensure_bytes(s): """ Turn string or bytes to bytes >>> ensure_bytes(u'123') '123' >>> ensure_bytes('123') '123' >>> ensure_bytes(b'123') '123' """ if isinstance(s, bytes): return s if hasattr(s, 'encode'): return s.encode() msg = "Object %s is neither a bytes object nor has an encode method" raise TypeError(msg % s)
def ensureUtf(s, encoding='utf8'): """Converts input to unicode if necessary. If `s` is bytes, it will be decoded using the `encoding` parameters. This function is used for preprocessing /source/ and /filename/ arguments to the builtin function `compile`. """ # In Python2, str == bytes. # In Python3, bytes remains unchanged, but str means unicode # while unicode is not defined anymore if type(s) == bytes: return s.decode(encoding, 'ignore') else: return s
def paperwork(n, m): """ Your classmates asked you to copy some paperwork for them. You know that there are 'n' classmates and the paperwork has 'm' pages. :param n: integer value. :param m: integer value. :return: calculate how many blank pages do you need. """ return 0 if n < 0 or m < 0 else m * n
def nonalphanum_boundaries_re(regex): """Wrap regex to require non-alphanumeric characters on left and right.""" return rf"(?:^|[^a-zA-Z0-9])({regex})(?:[^a-zA-Z0-9]|$)"
def cli_table_to_recs(table_string): """Takes a table string (like that from a CLI command) and returns a list of records matching the header to values.""" lines = table_string.split('\n') # Take the first line as the header header_line = lines.pop(0).split() route_recs = [] for line in lines: vals = line.split() rec = dict(zip(header_line, vals)) route_recs.append(rec) return route_recs
def append_entry(data, name, path): """Append an entry if it doesn't have it. Returns true if an entry was appened, false otherwise. """ found = False for entry in data: if path == entry[1]: found = True break if not found: data.append((name, path)) return True return False
def div_up(a, b): """Return the upper bound of a divide operation.""" return (a + b - 1) // b
def terms_of_order_n(n, p): """ Parameters ---------- n Order p Dimension of the problem (number of input pi number in the pyVPLM case) Returns The number of terms specifically at order n (not counting the ones below n) ------- """ if n == 0: return 1 if p == 1: return 1 else: w = 0 for i in range(0, n+1): w += terms_of_order_n(i, p-1) return w
def build_written_line_entry(line_list): """ Remove start and end points from all line entries before writing to file. """ def _build_written_line_entry(coords): entry = \ { "geometry": { "coordinates": coords, "type": "LineString" }, "type": "Feature" } return entry ret = [] for line in line_list: ret.append(_build_written_line_entry(line["geometry"]["coordinates"])) return ret
def getSize(picture): """Return the size of a given picture.""" return picture[0], picture[1]
def create_global_ctu_function_map(func_map_lines): """ Takes iterator of individual function maps and creates a global map keeping only unique names. We leave conflicting names out of CTU. A function map contains the id of a function (mangled name) and the originating source (the corresponding AST file) name.""" mangled_to_asts = {} for line in func_map_lines: mangled_name, ast_file = line.strip().split(' ', 1) # We collect all occurences of a function name into a list if mangled_name not in mangled_to_asts: mangled_to_asts[mangled_name] = {ast_file} else: mangled_to_asts[mangled_name].add(ast_file) mangled_ast_pairs = [] for mangled_name, ast_files in mangled_to_asts.items(): if len(ast_files) == 1: mangled_ast_pairs.append((mangled_name, ast_files.pop())) return mangled_ast_pairs
def sort_dict(unsorted_dict, descending=False): """ Sorts a dictionary in ascending order (if descending = False) or descending order (if descending = True) """ if not isinstance(descending, bool): raise ValueError('`descending` must be a boolean') return sorted(unsorted_dict.items(), key=lambda x:x[1], reverse=descending)
def _repair_options(version, ks='', cf=None, sequential=True): """ Function for assembling appropriate repair CLI options, based on C* version, as defaults have changed. @param ks The keyspace to repair @param cf The table to repair @param sequential If the repair should be a sequential repair [vs parallel] """ opts = [] # since version 2.2, default is parallel, otherwise it's sequential if sequential: if version >= '2.2': opts += ['-seq'] else: if version < '2.2': opts += ['-par'] # test with full repair if version >= '2.2': opts += ['-full'] if ks: opts += [ks] if cf: opts += [cf] return opts
def ordinal(n: int): """Utility function that gives the correct string ordinal given a number. For example, 1 gives 1st, 2 give 2nd, 14 gives 14th etc... From: https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement :param int n: integer that the user wants to convert to an ordinal string :return: """ return "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])
def project_length_in_ns(projnum): """Returns a float with the project length in nanoseconds (ns)""" w = {} # 7 fragment hits w[14346] = 1.0 # RL w[14348] = 10.0 # L # 100 ligands w[14337] = 1.0 # RL w[14339] = 10.0 # L # 72 series for i in range(14600, 14613): w[i] = 1.0 # RL for i in range(14349, 14362): w[i] = 10.0 # L # Moonshot 03-23 w[14363] = 1.0 # RL w[14364] = 10.0 # L # Moonshot 03-26 for i in range(14365, 14369): w[i] = 1.0 # RL for i in range(14369, 14373): w[i] = 10.0 # L # MLTN w[14373] = 1.0 # RL w[14374] = 10.0 # L # Moonshot 03-31 w[14375] = 1.0 # RL w[14376] = 10.0 # L # Moonshot 04-06 w[14377] = 1.0 # RL w[14378] = 10.0 # L # Moonshot 04-06-2 w[14379] = 1.0 # RL w[14380] = 10.0 # L # Moonshot MSBR w[14381] = 1.0 # RL w[14382] = 1.0 # RL w[14383] = 1.0 # RL w[14384] = 10.0 # L w[14385] = 10.0 # L w[14386] = 10.0 # L # AGG for i in range(14613, 14628): w[i] = 1.0 # RL for i in range(14630, 14644): w[i] = 10.0 # L # harmonic potential testing w[14398] = 1.0 # RL w[14399] = 1.0 # RL for i in range(14700, 14900): w[i] = 1.0 # RL return w[projnum]
def format_list_items(items, format_string, *args, **kwargs): """ Apply formatting to each item in an iterable. Returns a list. Each item is made available in the format_string as the 'item' keyword argument. example usage: ['png','svg','pdf']|format_list_items('{0}. {item}', [1,2,3]) -> ['1. png', '2. svg', '3. pdf'] """ return [format_string.format(*args, item=item, **kwargs) for item in items]
def row_major_gamma(idx, shape): """ As defined in 3.30 """ assert len(idx) == len(shape) if not idx: return 0 assert idx < shape return idx[-1] + (shape[-1] * row_major_gamma(idx[:-1], shape[:-1]))
def dict_to_str(props): """Returns the given dictionary as a string of space separated key/value pairs sorted by keys. """ ret = [] for k in sorted(props.keys()): ret += [k,props[k]] return " ".join(ret)
def encrypt(name, shift): """Encrypt a name using a Caesar cipher""" encrypted_name = "" for letter in name: if letter.isalpha(): encrypted_name += chr(ord(letter) + shift) else: encrypted_name += letter return encrypted_name
def is_invalid_dessert_key(dessert_key, dessert_json): """ Returns true if key is not blank or an empty string. :param dessert_key: :param dessert_json: :return: """ prefix = 'strIngredient' return str(dessert_key).startswith(prefix) and dessert_json[dessert_key] not in (' ', '')
def triple_step_combinations(step): """Find number of step combinations for maximum of three steps at a time :param step Number of steps left :return Number of step combinations """ if step < 0: return 0 elif step == 0: return 1 return triple_step_combinations(step - 3) + \ triple_step_combinations(step - 2) + \ triple_step_combinations(step - 1)
def make_metadata_sos(): """ aux data for sos kernel """ return { "celltoolbar": "Create Assignment", "kernelspec": { "display_name": "SoS", "language": "sos", "name": "sos" }, "language_info": { "codemirror_mode": "sos", "file_extension": ".sos", "mimetype": "text/x-sos", "name": "sos", "nbconvert_exporter": "sos_notebook.converter.SoS_Exporter", "pygments_lexer": "sos" }, "sos": { "kernels": [ ["Bash", "bash", "bash", "", "shell"], ["C", "c_kernel", "c", "", ""], ["OCaml default", "ocaml-jupyter", "OCaml", "", "text/x-ocaml"], ["Python 3 (ipykernel)", "python3", "python3", "", {"name": "ipython", "version": 3}] # ["Python 3", "python3", "python3", "", {"name": "ipython", "version": 3}] ], "panel": { "displayed": True, "height": 0 }, "version": "0.21.21" } }
def _get_output_filename(dataset_dir, split_name): """Creates the output filename. Args: dataset_dir: The dataset directory where the dataset is stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)
def bib_keys(config): """Return all citation keys.""" if "bib_data" not in config: return set() return {entry["ID"] for entry in config["bib_data"]}
def _stability_filter(concept, stability_thresh): """Criteria by which to filter concepts from the lattice""" # stabilities larger then stability_thresh keep_concept = \ concept[2] > stability_thresh[0]\ or concept[3] > stability_thresh[1] return keep_concept
def _py_list_pop(list_, i): """Overload of list_pop that executes a Python list append.""" if i is None: x = list_.pop() else: x = list_.pop(i) return list_, x
def sortMapping(streamPair): """ Sort mapping by complexity :param streamPair: :return: """ modifiedMapping = streamPair[5] possibleMapping = [] for x in modifiedMapping: modifiedMapping[x] = list(modifiedMapping[x]) modifiedMapping[x].sort(key=lambda x:x.__len__(), reverse=True) possibleMapping.append((x, modifiedMapping[x])) possibleMapping.sort(key=lambda x: x[0].__len__(), reverse=True) return possibleMapping
def break_by_minus1(idata): """helper for ``read_nsm_nx``""" i1 = 0 i = 0 i2 = None packs = [] for idatai in idata: #print('data[i:] = ', data[i:]) if idatai == -1: i2 = i packs.append((i1, i2)) i1 = i2 + 1 i += 1 continue i += 1 #print(packs) return packs
def merge_dicts_by_key_and_value(*dict_args, max_turns=None): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = dict_args[0] for dictionary in dict_args[1:]: for sample_id, oracle_outputs_per_turn in dictionary.items(): result[sample_id].update(oracle_outputs_per_turn) if max_turns is not None: for sample_id, oracle_outputs_per_turn in result.items(): filtered_results = {} for turn, oracle_outputs in result[sample_id].items(): if (len(turn.replace('_', '')) + 1) <= max_turns: filtered_results[turn] = oracle_outputs result[sample_id] = filtered_results return result
def showDifferences(seq1, seq2) : """Returns a string highligthing differences between seq1 and seq2: * Matches by '-' * Differences : 'A|T' * Exceeded length : '#' """ ret = [] for i in range(max(len(seq1), len(seq2))) : if i >= len(seq1) : c1 = '#' else : c1 = seq1[i] if i >= len(seq2) : c2 = '#' else : c2 = seq2[i] if c1 != c2 : ret.append('%s|%s' % (c1, c2)) else : ret.append('-') return ''.join(ret)
def get_instances_ids_and_names(instances): """ Get the instances IDs and names according to nodes dictionary Args: instances (list): Nodes dictionaries, returned by 'oc get node -o yaml' Returns: dict: The ID keys and the name values of the instances """ return { 'i-' + instance.get().get('spec').get('providerID').partition('i-')[-1]: instance.get().get('metadata').get('name') for instance in instances }
def GetRecursionFunctor(depth): """Returns functor that unfolds recursion. Example: P_r0 := P_recursive_head(P_recursive: nil); P_r1 := P_recursive_head(P_recursive: P_r0); P_r2 := P_recursive_head(P_recursive: P_r1); P_r3 := P_recursive_head(P_recursive: P_r2); P := P_r3(); """ result_lines = ['P_r0 := P_recursive_head(P_recursive: nil);'] for i in range(depth): result_lines.append( 'P_r{1} := P_recursive_head(P_recursive: P_r{0});'.format(i, i + 1)) result_lines.append('P := P_r{0}();'.format(depth)) return '\n'.join(result_lines)
def isTrue(value): """ Helper to check for string representation of a boolean True. """ return value.lower() in ('true', 'yes', '1')
def zip_dicts(dict_a, dict_b): """Zip the arrays associated with the keys in two dictionaries""" combined = {} combined.update(dict_a) combined.update(dict_b) zipped_vals = zip(*combined.values()) keys = list(combined.keys()) out = [] for i, zv in enumerate(zipped_vals): obj = {k: v_ for (k,v_) in zip(keys, zv)} out.append(obj) return out
def victoire_diagonale(plateau, joueur): """ Teste si le plateau admet une victoire en diagonale pour le joueur. """ if (all(plateau[2 - i][i] == joueur for i in range(3)) or all(plateau[i][i] == joueur for i in range(3))): return True return False
def clamp(x, min_val, max_val): """ Clamp value between min_val and max_val """ return max(min(x,max_val),min_val)
def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns (0.0,). Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x^4 + 3x^3 + 17.5x^2 - 13.39 >>> print compute_deriv(poly) # 4x^3 + 9x^2 + 35^x (0.0, 35.0, 9.0, 4.0) poly: tuple of numbers, length > 0 returns: tuple of numbers """ # TO DO ... length = float(len(poly)) - 1.0 index = 0.0 der = [] for mono in poly: monoDer = index * mono if index > 0.0: der.append(monoDer) index += 1.0 return tuple(der)
def bufferParser(readbuffer, burst=16): """ Parse concatenated frames from a burst """ out = b'' offset = 1 while len(readbuffer) > 0: length = readbuffer[2] if readbuffer[4] == offset: out += readbuffer[5:3+length] offset += 1 readbuffer = readbuffer[4+length:] return out
def library_path(hsm): """Provide a library_path property to the template if it exists""" try: return hsm.relation.plugin_data['library_path'] except Exception: return ''
def is_continuation(val): """Any subsequent byte is a continuation byte if the MSB is set.""" return val & 0b10000000 == 0b10000000
def file_hash(text): """ Removes the last updated ... line from html file and the data line from svg and then computes a hash. :param text: :return: """ text = text.split('\n') text = [t for t in text if not any(t.startswith(prefix) for prefix in (' This website is built ', ' <dc:date>'))] text = ''.join(text) return hash(text)
def hoop_pressure_thick(t, D_o, P_o, sig): """Return the internal pressure [Pa] that induces a stress, sig, in a thick walled pipe of thickness t - PD8010-2 Equation (5). :param float t: Wall thickness [m] :param float D_o: Outside diamter [m] :param float P_o: External pressure [Pa] :param float sig: Stress [Pa] """ return ((sig * (D_o**2 - (D_o - 2 * t)**2)) / (D_o**2 + (D_o - 2 * t)**2)) + P_o
def merge_dicts_lists(parent_dict, merge_dict): """ Function to add two dictionaries by adding lists of matching keys :param parent_dict: The Dict to which the second dict should be merged with :param merge_dict: Dict to be merge with the parent :return: Dict having the two inputs merged """ for key in merge_dict.keys(): # Check if key is present, if then append the value to the key if key in parent_dict: if not isinstance(merge_dict[key], list): parent_dict[key] += [merge_dict[key]] else: parent_dict[key] += merge_dict[key] # If key is not present construct the key else: if not isinstance(merge_dict[key], list): parent_dict[key] = [merge_dict[key]] else: parent_dict[key] = merge_dict[key] return parent_dict
def numeric_type(param): """ Checks parameter type True for float; int or null data; false otherwise :param param: input param to check """ if ((type(param) == float or type(param) == int or param == None)): return True return False
def overlap(document_tokens, target_length): """ pseudo-paginate a document by creating lists of tokens of length `target-length` that overlap at 50% return a list of `target_length`-length lists of tokens, overlapping by 50% representing all the tokens in the document """ overlapped = [] cursor = 0 while len(' '.join(document_tokens[cursor:]).split()) >= target_length: overlapped.append(document_tokens[cursor:cursor+target_length]) cursor += target_length // 2 return overlapped
def collatz_len_fast(n, cache): """Slightly more clever way to find the collatz length. A dictionary is used as a cache of previous results, and since the dictionary passed in is mutable, our changes will reflect in the caller. """ if n == 1: return 1 if n in cache: return cache[n] if n % 2 == 0: cache[n] = collatz_len_fast(n // 2, cache) + 1 else: cache[n] = collatz_len_fast(3 * n + 1, cache) + 1 return cache[n]
def check_ratio_sum(ratio): """ Check the given ratio is valid or not. Sum of ratio should be 100 """ train_ratio = int(ratio[0]) val_ratio = int(ratio[1]) test_ratio = int(ratio[2]) qa_ratio = int(ratio[3]) total = train_ratio + test_ratio + val_ratio + qa_ratio if total != 100: raise ValueError("Sum of all the input ratio should be equal to 100 ") return train_ratio, val_ratio, test_ratio, qa_ratio
def _re_word_boundary(r): """ Adds word boundary characters to the start and end of an expression to require that the match occur as a whole word, but do so respecting the fact that strings starting or ending with non-word characters will change word boundaries. """ # we can't use \b as it chokes on unicode. however \W seems to be okay # as shorthand for [^0-9A-Za-z_]. return r"(^|\W)%s(\W|$)" % (r,)