content
stringlengths
42
6.51k
def convert_eq_to_dict(equationstring): """ Converts an equation string to a dictionary convert_eq_to_dict('1*Be12Ti->10*Be+1*Be2Ti+5*Be') -> {'products': {'Be': 15, 'Be2Ti': 1}, 'educts': {'Be12Ti': 1}} """ eq_dict = {'products': {}, 'educts': {}} product_dict = {} educt_dict = {} ...
def rel_to_abs(vector, cell): """ converts interal coordinates to absolut coordinates in Angstroem. """ if len(vector) == 3: postionR = vector row1 = cell[0] row2 = cell[1] row3 = cell[2] new_abs_pos = [ postionR[0] * row1[0] + postionR[1] * row2[0] + ...
def _gcd(a,b): """ Returns greatest common denominator of two numbers. Example: >>> _gcd(4, 6) 2 """ while b: a,b=b,a%b return a
def lb_lookup(session, lb_name): """Look up ELB Id by name Args: session (Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed lb_name (string) : Name of the ELB to lookup Returns: (bool) : If the...
def tryint(x): """ Used by numbered string comparison (to protect against unexpected letters in version number). :param x: possible int. :return: converted int or original value in case of ValueError. """ try: return int(x) except ValueError: return x
def unit_factor(unit): """Return the factor corresponding to the unit, e.g. 1E-9 for nM. Known units are: mM, uM, nM, pM. Raises ValueError for unknown unit.""" units = ["mm", "um", "nm", "pm"] pos = units.index(unit.lower()) + 1 factor = 10 ** -(pos * 3) return factor
def create_lang(var): """Takes a variable (with an eventual language tag) and it's value and return var,lang,value Only the last _ determines the language, note that it could give the impression _ is ok to use in variables. It is not.""" s_var=var.rsplit('_',1) if len(s_var)==2: if "" in s_var:...
def _findrange(parlist, roots=["JUMP", "DMXR1_", "DMXR2_", "DMX_", "efac", "log10_efac"]): """Rewrite a list of parameters name by detecting ranges (e.g., JUMP1, JUMP2, ...) and compressing them.""" rootdict = {root: [] for root in roots} res = [] for par in parlist: found = False ...
def is_number(uchar): """unicode char to be numbers""" if uchar >= u'\u0030' and uchar<=u'\u0039': return True else: return False
def get_value(d, key): """Return value from source based on key.""" for k in key.split("."): if k in d: d = d[k] else: return None if isinstance(d, list): return ", ".join([str(i) for i in d]) else: return d
def isBitSet(num, k): """Returns True if bit k of num is 1, else False. This is used internally to interpret hitsounds as a TaikoObjectType""" return num & (1 << (k - 1)) > 0
def get_DLP_from_uin(u_ast, lam1, eta_s, R_channel, L_channel): """ this will calculate DLP_ast based on the linear approximation for P """ DLP_ast = u_ast * lam1 * eta_s * L_channel/R_channel**2.0; return DLP_ast
def isActive(edge): """Return 1 if edge is active, else return 0.""" if edge[2] < len(edge[4]): return True return False
def mkfile(name, meta={}): """Return file node.""" return { 'name': name, 'meta': meta, 'type': 'file' }
def _normalize_index_columns(user_columns, data_columns, user_index, data_index): """Normalize user and file-provided column and index names Parameters ---------- user_columns : None, str or list of str data_columns : list of str user_index : None, str, or list of str data_index : list of s...
def least_significant_set_bit(n): """ Returns least-significant bit in integer 'n' that is set. """ m = n & (n - 1) return m ^ n
def scale_joint_params(params, scale): """modify scalable joint parameters""" new_params = params new_params['tabsize'] = params['tabsize'] * scale new_params['tabspace'] = params['tabspace'] * scale new_params['boltspace'] = params['boltspace'] * scale return params
def get_concat_files(pop, score, altpop, basedir): """ locates concatenated component score files to facilitate normalization to neutral replicates """ if score in ['ihs', 'delihh', 'nsl']: concatfilebase = basedir + "neut/concat_" + str(pop) + "_" elif score in ['xpehh', 'fst']: concatfilebase = basedir + "neut...
def charAt(s, c, count = 1): """ Find the nth index of char 'c' in the string 's' """ for i in range(len(s)): if s[i] == c: count = count - 1 if count == 0: return i
def convert_to_bytes(list_of_lists): """Convert lists of integer lists to list of byte lists""" return [bytes(x) for x in list_of_lists]
def add_to_start(solutions, add_num): """The current function gets a list of lists and number. The function will add all sub-lists into an updated list with each sub-list added at the beginning of the list the number the function is gets""" final_list = [] if solutions is None: return ...
def to_external_url(url): """ Convert an internal download file/folder url to the external url. This should eventually be replaced with with a reverse method that gets the correct mapping. """ return url.replace("django_irods/download", "resource", 1)
def _rescale(vector): """Scale values in vector to the range [0, 1]. Args: vector: A list of real values. """ # Subtract min, making smallest value 0 min_val = min(vector) vector = [v - min_val for v in vector] # Divide by max, making largest value 1 max_val = float(max(vector)...
def integrate_rectangle(function, xmin, xmax, intervals): """ Integrate by using the rectangle rule.""" dx = (xmax - xmin) / intervals total = 0 # Perform the integration. x = xmin for interval in range(intervals): # Add the area in the rectangle for this slice. total +...
def remove_duplicate_values(array_like, tol=0.0): """ Removes duplicate values from list (when tol=0.0) or remove approximately duplicate values if tol!=0.0. """ unique_values = [array_like[0]] for element in array_like: element_is_duplicate = False for uval in unique_values: ...
def color_xy_brightness_to_RGB(vX, vY, brightness): """Convert from XYZ to RGB.""" brightness /= 255. if brightness == 0: return (0, 0, 0) Y = brightness if vY == 0: vY += 0.00000000001 X = (Y / vY) * vX Z = (Y / vY) * (1 - vX - vY) # Convert to RGB using Wide RGB D65...
def is_inc_monotonic(lst): """ Check whether the the elements in the list increase monotonically. Arguments --------- lst: list Returns -------- Bool, whether the elements of the list increase monotonically (True) or not (False) """ return all(x < y for x, y in zip(lst,...
def _check_header_footer_match(line: str, terms: list) -> bool: """ Check the line of text if it includes all occurrences of the specified terms. @param line: String holding the line of text @param terms: Terms whose presence in the line are validated @return: True if all the specified terms are in...
def what_is_n(row: int, col: int) -> int: """Determines where the row and column fall in the sequence""" return (row + col - 2) * (row + col - 1) // 2 + col - 1
def swap_item(startlist: list, pull: object, push: object): """ Swap a specified item in a list for another. Parameters ---------- startlist : :class:`list` List to replace item within. pull Item to replace in the list. push Item to add into the list. Returns ...
def is_valid_git_refname(refname): """check if a string is a valid branch-name/ref-name for git Input: refname: string to validate Output: True if 'refname' is a valid branch name in git. False if it fails to meet any of the criteria described in the man page for 'git check-ref-format', al...
def gimme(input_array): """ Function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements. :param input_array: an array of integers. :return: the index of the middle numerical element in the array. """ return input_array.index...
def h3_html(text: str) -> str: """Embed text in subsubheading tag.""" return "<h3>{}</h3>".format(text)
def createList(num): """Create a list of numbers""" return list(range(0, num))
def these(what, where=None): """ Combinator for yielding multiple values with property access. Yields from the values generated by an attribute of the given object, or the values generated by the given object itself if no attribute key is specified. Examples: No attribute key specified; y...
def vdc(k: int, base: int) -> float: """_summary_ Args: k (int): _description_ base (int): _description_ Returns: float: _description_ """ vdc = 0.0 denom = 1.0 while k != 0: denom *= base remainder = k % base k //= base vdc += remain...
def parse_elevations_response(elevations_response): """Extract elevation values in order from API response. Args: elevations_response: list of elevation responses in the deserialized Elevation API response format Returns: a list of elevations (in meters) in the same order as given response """ re...
def _abbr_match(a, b): """ Match abbreviation. """ if a[-1] != '.' and b[-1] != '.': return False if a[-1] == '.': idx = a.index('.') if len(b) > idx and a[:idx] == b[:idx]: return True else: idx = b.index('.') if len(a) > idx and a[:idx] == b...
def get_data_ref_list(butler, run, **kwargs): """Construct and return a list of data_ids. Parameters ---------- butler : `Bulter` The data Butler run : `str` The number number we are reading Keywords -------- imagetype : `str` The type of image, e.g., BIAS or DA...
def hh_mm_ss(seconds): """ Converts seconds into hh:mm:ss padded with zeros. """ hh = int(seconds/3600) mm = int((seconds % 3600)/60) ss = int((seconds % 3600) % 60) out = '{hh:02}:{mm:02}:{ss:02}'.format(hh=hh, mm=mm, ss=ss) return out
def is_sorted( s, strict = True ): """Test if a sequence is sorted""" prev_elem = None for x in s: if prev_elem != None and x < prev_elem or ( x == prev_elem and strict ): return False prev_elem = x return True
def db2a(db): """Returns a ratio of amplitude""" return 10.0**(db/20.0)
def update(d, u): """ update dictionary d with updated dictionary u recursively """ # for k, v in u.iteritems(): for k in u: # if isinstance(v, collections.Mapping): if isinstance(u[k], dict): r = update(d.get(k, {}), u[k]) d[k] = r else: d...
def _GetErrorMessages(errors): """return the errorMessage list from a list of ConfigSync errors.""" return_errors = [] for err in errors: return_errors.append(err['errorMessage']) return return_errors
def back_search(searched, the_list, index=0): """ Search 'searched' from 'the_list' in in backwrd order """ for ikey, key in enumerate(reversed(the_list)): print(f"back_search ikey={ikey} key[index]={key[index]} searched={searched}") if key[index] == searched: return ikey return ...
def isscalar(val): """ Check whether a given value is a scalar Parameters ---------- val Returns ------- bool """ return (isinstance(val, int) or isinstance(val, float) or isinstance(val, complex))
def find(word, letter, start): """Searches word for letter, starting at index start, returns index of first hit or -1 if letter not found""" index = start while index < len(word): if word[index] == letter: return index index = index + 1 return -1
def cyan(s): """Color text cyan in a terminal.""" return "\033[1;36m" + s + "\033[0m"
def find_matching_keys_from_dicts(template_data, verification_data): """ The parameter dictionairs are just normal dicts The dictionaries this method takes as parameters are assumed to be ones containing the KIT and KHT values to avoid on the fly computation""" matches = [] template_keys = templ...
def parse_var_names(var_names): """ """ return ((None,) if var_names is None else (var_names,) if isinstance(var_names, str) else tuple(var_names))
def path_distance(path_1, path_2, feature_names, min_max_feature_values): """path_distance function computes the distance of two paths (rules) Args: path_1: the first path path_2: the second path feature_names: the list of features min_max_feature_values: the min and max possible...
def count_distributions(proposalId, distributionList): """ count number of students distributed to a proposal :param proposalId: :param distributionList: :return: """ count = 0 for d in distributionList: if d.ProjectID == proposalId: count += 1 return count
def clean_multiple_white_spaces(string): """ Merge multiple white spaces in only one :param string: String, Line to apply the format. Ie, " some string with spaces" :return: String, Line with format. Ie, " some string with spaces" """ return ' '.join(string.split())
def bbox_vertices(vertices): """ Return bounding box of this object, i.e. ``(min x, min y, max x, max y)`` :param vertices: List ``[[x1, y1], [x2, y2]]`` or string ``"x1,y1,x2,y2,...,xn,yn"`` """ x, y = zip(*vertices) # convert to two lists return (min(x), min(y), max(x), max(y))
def color(x, y): """triangles. Colors: - http://paletton.com/#uid=70l150klllletuehUpNoMgTsdcs shade 2 """ return '#42359C' # "#CDB95B" if (x - 4) > (y - 4) and -(y - 4) <= (x - 4): # right return '#42359C' # "#CDB95B" elif (x - 4) > (y - 4) and -(y - 4) > (x - 4): ...
def split_inds(num_inds, nproc): """ Evenly slice out a set of jobs that are handled by each MPI process. - Assuming each job takes the same amount of time. - Each process handles an (approx) equal size slice of jobs. - If the number of processes is larger than rows to divide up, then some ...
def get_cluster_key(obj): """Get the cluster key for a given k8s object""" try: namespace = obj["metadata"]["namespace"] name = obj["metadata"]["labels"]["gateway.dask.org/cluster"] return f"{namespace}.{name}" except KeyError: return None
def numberp(thing): """ NUMBERP thing NUMBER? thing outputs TRUE if the input is a number, FALSE otherwise. """ return type(thing) is int or type(thing) is float
def strange(start, end, step=1): """A sensible, or *standard* range that behaves as you would expect. :param start: The start of the range. :type start: int :param end: The end of the range. :type start: int :param step: The increment to be applied. :type step: int :rtype: range ...
def get_resources(name, config): """Retrieve resources for a program, pulling from multiple config sources. """ resources = config.get("resources", {}).get(name, {}) if "jvm_opts" not in resources: java_memory = config["algorithm"].get("java_memory", None) if java_memory: res...
def serialise(instance): """ Serialises an integer to bytes. :param instance: The integer to serialise. :return: The ``bytes`` representing that integer. """ return str(instance).encode("utf_8")
def tags(*tags): """ Given a list of tags as positional arguments TAGS, return a list of dictionaries in the format that the CKAN API wants! """ return [{'name': t.replace("'", "") } for t in tags]
def get_bar(dummy_context, dummy_request): """ View callable for nested resource """ return { 'uri': '/foo/bar', }
def format_key_value(key_value: str) -> str: """ All of our DynamoDB keys must be upper case, with spaces stripped. """ if isinstance(key_value, str): key_value = key_value.upper().replace(" ", "") return key_value
def TransformAlways(r): """Marks a transform sequence to always be applied. In some cases transforms are disabled. Prepending always() to a transform sequence causes the sequence to always be evaluated. Example: some_field.always().foo().bar() will always apply foo() and then bar(). Args: r: A reso...
def _merge_sig_dicts(sig1_dict, sig2_dict): """Merge two signature dicts. A in dict.update(sig1_dict, **sig2_dict), but specialized for signature dicts. If sig1_dict and sig2_dict both define a parameter or return annotation, sig2_dict decides on what the output is. """ return { 'paramet...
def one_or_more(amount, single_str, multiple_str): """ Return a string which uses either the single or the multiple form. @param amount the amount to be displayed @param single_str the string for a single element @param multiple_str the string for multiple elements @return the string represent...
def _equal_two_part(a, b): """Returns True iff a_{2} = b_{2} """ while a % 2 == 0 and b % 2 == 0: a, b = a // 2, b // 2 return a % 2 == 1 and b % 2 == 1
def get_open_comment_count(review_comments, user): """ Return the number of non-obsolete review comments posted on the given PR url, by the given user.""" return sum(1 for review_comment in review_comments # In obsolote comments, the position is None if review_comment['posi...
def xgcd(b, n): """ Compute the extended GCD of two integers b and n. Input: b, n Two integers Output: d, u, v Three integers such that d = u * b + v * n, and d is the GCD of b, n. """ x0, x1, y0, y1 = 1, 0, 0, 1 while n != 0: q, b, n = b // n, n, b % n x...
def tfs(throttlespeed): """time until throttle full stop""" return abs(throttlespeed) / 3600 + 1 / 60
def keep_alpha_numeric(input_text: str) -> str: """ Remove any character except alphanumeric characters """ return ''.join(c for c in input_text if c.isalnum())
def f_bis(n1 : float, n2 : float, n3 : float) -> str: """ ... cf ci-dessus ... """ if n1 < n2: if n2 < n3: return 'cas 1' elif n1 < n3: return 'cas 2' else: return 'cas 5' elif n1 < n3: return 'cas 3' elif n2 < n3: return 'c...
def dpid_to_mac (dpid): """Generate hex MAC address from a given int ID. Args: dpid (int): Integer ID of a switch, e.g. 1,2,3, and so on. Returns: str: MAC address without any colon or comma sign (only hex numbers). """ return "%012x" % (dpid & 0xffFFff...
def winner(board): """ Returns the winner of the game, if there is one. """ # Horizontal / Vertical elems_d_1 = set() elems_d_2 = set() diagonals = [2,1,0] for i in range(len(board)): elems_h = set() elems_v = set() for j in range(len(board)): elems_h....
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ idx = 0 m_idx = 0 n_idx = len(input_list)-1 while idx <= n_idx: if input_list[n_idx] == 2:...
def _limit_es(expected_mb): """Protection against creating too small or too large chunks.""" if expected_mb < 1: # < 1 MB expected_mb = 1 elif expected_mb > 10 ** 7: # > 10 TB expected_mb = 10 ** 7 return expected_mb
def is_podcast_series_id(item_id): """Validate if ID is in the format of a Google Music series ID.""" return len(item_id) == 27 and item_id.startswith('I')
def e_burn(n_burn=400, n=402, e_burn=-1, e_test=1000): """ A vector of -1's followed by a large value This is typically the 'e' that will be used when sending historical data to a skater helper function """ return [e_burn] * n_burn + [e_test] * (n - n_burn)
def digits_num_finder(n, counter): """ Used to find the quantity of the digits :param n: the integer turned into positive already :param counter: each time the counter plus 1 means the quantities of the digit plus 1 :return: the number counting how many digits the integer has """ if n < 10 ** counter: ...
def serialize_table_umd(analysis, type): """ Convert the aggregate_values=false Hansen response into a table""" rows = [] for year in analysis.get('loss', None): rows.append({'year': year, 'loss': analysis.get('loss', None).get(year), 'gain': analysis.get('g...
def unexpected_error(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: {}'.format(e), 500
def replaceItemObj(obj, keystart, newval, exclude_list=[]): """ Function for/to <short description of `netpyne.sim.utils.replaceItemObj`> Parameters ---------- obj : <type> <Short description of obj> **Default:** *required* keystart : <type> <Short description of keysta...
def epoch_time(start_time, end_time): """ Calculate epoch run time """ elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
def has_duplicates(t): """Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence """ d = {} for x in t: if x in d: return True d[x] = True return False
def _LookupDist(dists, i, j, n): """ *Internal Use Only* returns the distance between points i and j in the symmetric distance matrix _dists_ """ if i == j: return 0.0 if i > j: i, j = j, i return dists[j * (j - 1) / 2 + i]
def format_channel_link(name: str, channel_id: str): """ Formats a channel name and ID as a channel link using slack control sequences https://api.slack.com/docs/message-formatting#linking_to_channels_and_users >>> format_channel_link('general', 'C024BE7LR') '<#C024BE7LR|general>' """ retur...
def json_citation_for_ij(query, score, doi): """ Because we are parsing the PDF, we cannot ensure the validity of each subfieldobtained form the parser (CERMINE) i.e title, journal, volume, authors, etc. Instead, we join all the information obtained from the parser in plain text. This plain text is the ...
def is_oppo_dispossessed(event_list, team): """Returns whether an opponent is disposessed""" disposessed = False for e in event_list[:1]: if e.type_id == 50 and e.team != team: disposessed = True return disposessed
def _Unlist(l): """If l is a list, extracts the first element of l. Otherwise, returns l.""" return l[0] if isinstance(l, list) else l
def cluster_idx(idx_ls): """Given a list of idx, return a list that contains sub-lists of adjacent idx.""" if len(idx_ls) < 2: return [[i] for i in idx_ls] else: output = [[idx_ls[0]]] prev = idx_ls[0] list_pos = 0 for idx in idx_ls[1:]: if idx - 1 =...
def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> l...
def sort_1_by_2(x,y,rev=False): """ sort one list by elements in another list """ #print('reverse',rev) if(len(x) == len(y)): y_x = zip(y,x) y_x_sorted = sorted(y_x,reverse=rev) y = [z[0] for z in y_x_sorted] x = [z[1] for z in y_x_sorted] return x,y else: print('lists of different l...
def csharp_string_concat(*args): """A Python version of C#'s ``String.Concat()``. Works like ``.join()``, but joins the parameters instead of an iterable.""" return ''.join(args)
def build_qmcpack_fname(entry): """ inverse of interpret_qmcpack_fname Args: entry (dict): a dictionary of meta data, must include ['id','grouped','group','series','category','ext'] in key Return: str: filename """ order = ['id', 'series', 'category', 'ext'] if entry['grouped']: order.inser...
def get_full_slo_name(slo_config): """Compile full SLO name from SLO configuration. Args: slo_config (dict): SLO configuration. Returns: str: Full SLO name. """ return "{}/{}/{}".format(slo_config['service_name'], slo_config['feature_name'], slo_config[...
def is_tuple(value): """Checks if `value` is a tuple. Args: value (mixed): Value to check. Returns: bool: Whether `value` is a tuple. Example: >>> is_tuple(()) True >>> is_tuple({}) False >>> is_tuple([]) False .. versionadded:: 3....
def untuple(x): """Untuple a single value that was wrapped in a tuple.""" assert type(x) == type(()), 'Expected tuple.' # safety check assert len(x) == 1, 'Expected tuple singleton.' # safety check return x[0]
def get_cloud_attentuation(altitude, cloud_level_m=9000): """Computes the cloud attenuation using a simple model of a single cloud at the given altitude. Note this is effectively the worst case scenario for cloud cover. Parameters ---------- altitude : float The altitude of the obs...
def format_query(query, params=None): """ Replaces "{foo}" in query with values from params. Works just like Python str.format :type query str :type params dict :rtype: str """ if params is None: return query for key, value in params.items(): query = query.replace('...