content
stringlengths
42
6.51k
def color_temp_post_response_ok(devid, color_temp): """Return color temp change response json.""" return ''' { "idForPanel": "''' + devid + '''", "colorTemperature": ''' + str(int(color_temp)) + ''' }'''
def moment_from_magnitude(magnitude): """ Compute moment from moment magnitude. Args: magnitude (float): Moment magnitude. Returns: float: Seismic moment (dyne-cm). """ # As given in Boore (2003): # return 10**(1.5 * magnitude + 10.7) # But this appears to ...
def deep_update(a, b): """Updates data structures Dicts are merged, recursively List b is appended to a (except duplicates) For anything else, the value of a is returned""" if type(a) is dict and type(b) is dict: for key in b: if key in a: a[key] = deep_update(a...
def bit_not(n: int, numbits: int = 64): """ Python's ints are signed, so use this instead of tilda """ return (1 << numbits) - 1 - n
def change_from_change_spec(change): """Converts a change in change_spec format to buildbucket format. For more info on change_spec format, see master.chromium_step.AnnotationObserver.insertSourceStamp. Buildbucket change format is described in README.md. """ create_ts = None if 'when_timestamp' in chan...
def string_to_ascii(string: str): """return string of ascii characters with _ as seperator""" return '_'.join(str(ord(c)) for c in string)
def partition(items, low, high): """Return index `p` after in-place partitioning given items in range `[low...high]` by choosing a pivot (The last item) from that range, moving pivot into index `p`, items less than pivot into range `[low...p-1]`, and items greater than pivot into range `[p+1...high]`. ...
def clean_parsons_lines(code_lines): """Return list of lines of code, stripped of whitespace. Args: code (list): Code to be cleaned. Returns: List of cleaned code. """ clean_lines = list() for line in code_lines: stripped_line = line.strip() if stripped_line: ...
def split_thousands(s, tSep='\'', dSep='.'): """ Splits a number on thousands. http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/ >>> split_thousands(1000012) "1'000'012" """ # Check input # if s is None: return 0 # Check for int # if ...
def get_src_ids(sources): """ :returns: a string with the source IDs of the given sources, stripping the extension after the colon, if any """ src_ids = [] for src in sources: long_src_id = src.source_id try: src_id, ext = long_src_id.rsplit(':', 1) ...
def hasZ(pointlist): """ determine if points inside coordinates have Z values """ points = pointlist[0] first = points[0] if len(first) == 3: return True else: return False
def _param_fort_validation(args): """Validates the input parameters for the forward models Returns ------- input_args : dict Dictionary with the input parameters for the forward models. """ temp = args.get('ptemp', 1000) chem = args.get('pchem', 'noTiO') cloud = args.get('c...
def has_one_of_attributes(node,*args) : """ Check whether one of the listed attributes is present on a (DOM) node. @param node: DOM element node @param args: possible attribute names @return: True or False @rtype: Boolean """ if len(args) == 0 : return None if isinstance(args[0], tuple) or isinstance(args[0]...
def latex_float(f): """ Convert floating point number into latex-formattable string for visualize. Might relocate to viz.py Args: f (float): A floating point number Returns: float_str (str): A latex-formatted string representing f. """ float_str = "{0:.3g}".format(f) if...
def f(x): # 2 """Simple recursive function.""" # 3 if x == 0: # 4 return 1 # 5 return 1 + f(x - 1)
def render_user_label(user): """Returns a HMTL snippet which can be inserted for user representation. """ return { 'user': user }
def process_key(key: str) -> str: """ This function is for creating safe keys Currently this only replaces '..', should be expanded to be (or use) a full sanitizer in the future """ key = key.replace("..", "__") # Don't allow keys to traverse back a directory return key
def RefundablePayrollTaxCredit(was_plus_sey_p, was_plus_sey_s, RPTC_c, RPTC_rt, rptc_p, rptc_s, rptc): """ Computes refundable payroll tax credit amounts. """ rptc_p = min(was_plus_sey_p * RPTC_rt, RPTC_c) rptc_s = min(was_plus_sey_s * RP...
def _hostname_simple(hostname): """ Strips off domain name, ".(none)", etc """ if hostname[0].isdigit(): return hostname # IP address return hostname.split('.')[0]
def days_until_launch(current_day, launch_day): """"Returns the days left before launch. current_day (int) - current day in integer launch_day (int) - launch day in integer """ day=launch_day - current_day return( day if day >= 0 else 0)
def tokenize_table_name(full_table_name): """Tokenize a BigQuery table_name. Splits a table name in the format of 'PROJECT_ID.DATASET_NAME.TABLE_NAME' to a tuple of three strings, in that order. PROJECT_ID may contain periods (for domain-scoped projects). Args: full_table_name: BigQuery table name, as ...
def check_if_all_tss_are_bad(tss): """ Check if all time series in a list are not good. 'Not good' means that a time series is None or all np.nan """ def bad(ts): return True if ts is None else ts.isnull().all() return all([bad(ts) for ts in tss])
def get_options(args, mutators, converters={}): """ Returns a list of 2-tuple in the form (option, value) for all options contained in the `mutators` collection if they're also keys of the `args` and have a non-None value. If the option (non- prefixed) is also a key of the `converters` dictionary then the associat...
def parse_int_or_float(src, key, nentries=1): """ Parse a dictionary ``src`` and return an int or float or a list of int or float specified by ``key``. This function checks that the value or values specified by ``key`` is of type int or float or list of int or float and raises a ``ValueError`` ot...
def export_host_info(inventory): """Pivot variable information to be a per-host dict This command is meant for exporting an existing inventory's information. The exported data re-arranges variable data so that the keys are the host, and the values are hostvars and groups. Two top level keys are pr...
def krishnamurti(number) -> bool: """It will check whether the entered number is a krishnamurti number or not.""" s = 0 n = number a = n while(n != 0): f = 1 r = n % 10 for i in range(1, r+1): f = f*i s = s+f n = n//10 if(s == a): retur...
def clean_currency(x): """ Remove comma in currency numeric Add space between currency symbol and value """ if isinstance(x, int) or isinstance(x, float): return ('', x) if isinstance(x, str): numeric_start_at = 0 for i in range(len(x)): if x[i].isnumeric(): ...
def process_addresses_list( addresses_list, idx=0, limit=100, sortby=None, sortdir="asc" ): """Receive an address list as parameter and sort it or slice it for pagination. Parameters: addresses_list: list of dict with the keys (index, address, label, used, utxo, amount) ...
def checkRules(puzzle): """ this function receives a sudoku puzzle as a 9x9 list. and checks if it satisfies the rules of Sudoku, specifically (i): if all the numbers in rows are unique. (ii): if all the numbers in columns are unique (iii): if all the numbers in cells are unique""" # Check...
def is_number(in_value): """Checks if a value is a valid number. Parameters ---------- in_value A variable of any type that we want to check is a number. Returns ------- bool True/False depending on whether it was a number. Examples -------- >>> is_number(1) ...
def _get_tag_value(x, key): """Get a value from tag""" if x is None: return '' result = [y['Value'] for y in x if y['Key'] == key] if result: return result[0] return ''
def _bits_to_bytes_len(length_in_bits): """ Helper function that returns the numbers of bytes necessary to store the given number of bits. """ return (length_in_bits + 7) // 8
def nu(x, beta): """ Eq. (6) from Ref[1] (coeffient of alpha**2) Note that 'x' here corresponds to 'chi = x/rho' in the paper. """ return 3 * (1 - beta**2 - beta**2 * x) / beta**2 / (1+x)
def split_gems(frags, thr): """ Split GEMs into sub-GEMs depending on cutoff threshold thr. Args: frags (list of list): [chrom,start,end] for each fragment thr (int): cutoff threshold in bps Returns: subgems (list of list) """ subgems = [] tmpgem = [frags[0]] for i ...
def get_winner(state): """Return winning player if any""" winning = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] for player in ['X', 'O']: for i, j, k in winning: if [state[i], state[j], state[k]] == [player, player, player]: ...
def get_class(result, class_label='status'): """Get a normalized result for the specified class. Get a normalized result for the specified class. Currently supported classes are only one, 'status'. This returns a single value which defines the class the example belongs to. """ if class_label ==...
def str2bool(v): """ used in argparse, to pass booleans codes from : https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse """ if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False ...
def rtable_q_propagate(route_entry): """ Args: route_entry: (dict) Returns: string: returns route propagation """ if str( route_entry.get('Origin') ) == 'EnableVgwRoutePropagation': return 'True' ...
def merge_dicts(dict1, dict2): """Recursively merge two dictionaries. Values in dict2 override values in dict1. If dict1 and dict2 contain a dictionary as a value, this will call itself recursively to merge these dictionaries. This does not modify the input dictionaries (creates an internal copy). ...
def differ_paths(old, new): """ Compare old and new paths """ if old and old.endswith(('\\', '/')): old = old[:-1] old = old.replace('\\', '/') if new and new.endswith(('\\', '/')): new = new[:-1] new = new.replace('\\', '/') return (new != old)
def chop(lst, n): """ This function returns a list of lists derived from a list that was chopped up into pieces with n elements each. The last element might be any length between 1 and n.""" return [lst[i:i+n] for i in range(0, len(lst), n)]
def do(*exprs): """Helper function for chaining expressions. The expressions have already been evaluated when this function is called, so this function just returns the last one. If the list of expressions is empty, it returns ``None``. """ # You've already done them; just return the right value....
def fib2(n): """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return str(result).strip()
def _scrub_key(key): """ RETURN JUST THE :. CHARACTERS """ if key == None: return None output = [] for c in key: if c in [":", "."]: output.append(c) return "".join(output)
def add_multiple_values(*args): """ Adds a list of integers Arguments: args: A list of integers e.g. 1,2,3,4,5 """ sum_ = 0 for number in args: sum_ = sum_ + number return sum_
def is_clinical_in_cases(clinical_obj, cases): """Checks to see if clinical object representation is part of cases to assess Example: >>> clin_obj = xml_to_raw_clinical_patient("Test_Data/nationwidechildrens.org_clinical.TCGA-MH-A562.xml") >>> cases = set(["ad7ba244-67fa-4155-8f13-424bdcbb12e5"...
def format_message(fname, expected, actual, flag): """ Convenience function that returns nicely formatted error/warning messages """ def _format(types): return ', '.join([str(t).split("'")[1] for t in types]) expected, actual = _format(expected), _format(actual) msg = "'{}' method ".fo...
def oscale(l): """Convert from 0.0-1.0 in linear gamma to gamma table format (0-1023 gamma 2.2)""" omax = 1023 out_gamma = 1/2.2 if l < 0: o = 0 else: o = (l ** out_gamma) * omax oi = int(round(o, 0)) if oi >= omax: oi = omax return oi
def TrimBytes(byte_string): """Trim leading zero bytes.""" trimmed = byte_string.lstrip(b'\x00') if len(trimmed) == 0: # was a string of all zero byte_string return b'\x00' else: return trimmed
def heritingFrom(instanceOrType): """ Return classes name this is heriting from """ klasses = [] if isinstance(instanceOrType, type): bases = instanceOrType.__bases__ else: bases = instanceOrType.__class__.__bases__ for base in bases: klasses.append(base.__name__) ...
def determiner_to_num(tag): """Converts a/an to 1.""" if tag[1] != "DET": return False, None if tag[0].lower() in ("a","an"): return True, ("1","NUM") return False, None
def get_focal_value(tags): """Extracts focal length value from given tags """ if tags and "EXIF FocalLength" in tags: return eval(str(tags["EXIF FocalLength"])) return None
def common_prefix(a: str, b: str) -> str: """Determine the common prefix of *a* and *b*.""" if len(a) > len(b): a, b = b, a for i in range(len(a)): if a[i] != b[i]: return a[:i] return a
def normalize_id(entity_type, entity_id): """return node type and node id for a given entity type and id""" if entity_type == 'Chemical': if entity_id == '': return None if entity_id[:5] == 'CHEBI': return 'ChEBI', entity_id[6:] elif entity_id[0] == 'D' or entity_...
def channels(channel): """Return a mock of channels.""" return [channel("level", 8), channel("on_off", 6)]
def mongodb_generate_run_command(mongodb_config): """ Generate run command for mongodb from config dictionary :param mongodb_config: mongodb config dictionary :return: A list of string representing the running command """ # Return fundamental args return [ mongodb_config["exe"], ...
def _get_descendants(page_dict, page_ids): """ Returnes all descendants for a list of pages using a page dict built with _ordered_pages_to_dict method. """ result = [] for page_id in page_ids: result.append(page_id) children_ids = page_dict.get(page_id, None) ...
def text_first_line(target, strip=False): """ Return the first line of text; if `strip` is True, return all but the first line of text. """ first_line, _, rest = target.partition("\n") if strip: return rest else: return first_line
def subdict(fromdict, fields, default=None, force=False): """ Return a dictionary with the specified selection of keys from `fromdict`. If `default` is not None or `force` is true, set missing requested keys to the value of `default`. (Argument `force` is only needed if the desired default is None)...
def num_conv(number, plural=False): """Converts card numbers into their proper names Args: number (int): The number intended to be converted plural (bool): Determines if the result should be in plural or single form Returns: The proper name to be used for the card number """ ...
def boxed_string(text: str) -> str: """Returns passed text string wrapped in triple backticks.""" return '```' + text + '```'
def is_perfect_square(num): """Test whether a given number is a perfect square. Tests whether a given number is a perfect square or not based on the Babylonian method for computing square roots. Args: num (int): The number to test whether it is a perfect square Returns: bool: True...
def get_sorted_dict(dct: dict): """Returns dictionary in sorted order""" return dict(sorted(dct.items()))
def check_jumbo_opt(enable_jumbo, max_pkt_len): """Check if jumbo frame option is valid. Jumbo frame is enabled with '--enable-jumbo' and max packet size is defined with '--max-pkt-len'. '--max-pkt-len' cannot be used without '--enable-jumbo'. """ if (enable_jumbo is None) and (max_pkt_len is ...
def extract_values(obj, key): """Pull all values of specified key from nested JSON. Taken from: https://hackersandslackers.com/extract-data-from-complex-json-python/""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict)...
def list_dropdownTS(dic_df): """ input a dictionary containing what variables to use, and how to clean the variables It outputs a list with the possible pair solutions. This function will populate a dropdown menu in the eventHandler function """ l_choice = [] for key_cat, value_cat in d...
def intersect(ra, rb): """Given two ranges return the range where they intersect or None. >>> intersect((0, 10), (0, 6)) (0, 6) >>> intersect((0, 10), (5, 15)) (5, 10) >>> intersect((0, 10), (10, 15)) >>> intersect((0, 9), (10, 15)) >>> intersect((0, 9), (7, 15)) (7, 9) """ ...
def get_metric_name(metric_label): """Returns pushgateway formatted metric name.""" return 'mq_queue_{0}'.format(metric_label)
def formSentence(inList,searchChr): """ Checking all words rowwise in list and creating a str contains the first letter of word is same with searched character Parameters: inList(list): the input list searchChr(str): the value going to check returns: String : return rev ...
def checkNearlyEqual(value1, value2, dE = 1e-5): """ Check that two values are nearly equivalent by abs(val1-val2) < abs(dE*val1) """ if abs(value1-value2) <= abs(dE*value1) or abs(value1-value2) <= abs(dE*value2) or abs(value1-value2) <= dE: return True else: return False
def path_escape(path): """Escape a path by placing backslashes in front of disallowed characters""" for char in [' ', '(', ')']: path = path.replace(char, '\%s' % char) return path
def fmt2(f1, f2): """Format two floats as f1/f2 """ return "%.1f/%.1f" % (f1, f2)
def level_points(level: int) -> int: """ Returns the number of points required to reach the given level """ # determined with https://www.dcode.fr/function-equation-finder return int(((5*level**3)/3 + (45*level**2)/2 + 455*level/6))
def sepdelimited_keydata_to_json(data: dict, sep: str='.'): """Store a dict to JSON that originally has the following format: { "a.bc.def": "value1", "a.bc.ghi": "value2", "j": "value3" } The resulting JSON will be as follows: { ...
def lift_split_buffers(lines): """Lift the split buffers in the program For each module, if we find any split buffers with the name "buf_data_split", we will lift them out of the for loops and put them in the variable declaration section at the beginning of the module. Parameters ---------- ...
def wrap_accumulator(acc): """ Wraps accumulator!!! :param acc: :return: """ if acc > 1: acc -= 1 elif acc < -1: acc += 1 else: acc = 0 return acc
def is_relation(s: str) -> bool: """Checks if the given string is a relation name. Parameters: s: string to check. Returns: ``True`` if the given string is a relation name, ``False`` otherwise. """ return s[0] >= 'F' and s[0] <= 'T' and s.isalnum()
def max_team(assignment): """ people are random arrange in team. Search for max value of team. Help function for num_teams""" length = len(assignment) max = -1 for i in range(length): if assignment[i] > max: max = assignment[i] return max + 1
def extract_category(url): """ Extracts category of the article from URL Input : URL Output : Category """ if "/opinion/" not in url : return "regular" elif "/editorial/" in url: return "editorial" elif "/op_ed_commentaries/" in url : return "oped" elif "/lett...
def get_groups_from_list(group_ids, alignments): """ Given a list of IDs and a list of alignments, return a list with all alignments that belong the nodes in the group. """ # Create an inverted list of alignments names from all alignments. inverted_list_alignments = {} alignment_idx...
def _StandardizeTargetLabel(label): """Convert labels of form //dir/target to //dir/target:target.""" if label is None: return label tokens = label.rsplit('/', 1) if len(tokens) <= 1: return label target_base = tokens[0] target = tokens[1] if '...' in target or ':' in target: return label ...
def lustre_client_id(fsname, mnt): """ Return the Lustre client ID """ return "%s:%s" % (fsname, mnt)
def rus_check_json(rus_player_json): """Expected JSON for rus_check model-fixture""" return {"type": "check", "player": rus_player_json}
def is_Chinese(uchar): """unicode char to be Chinese character""" if uchar >= u'\u4e00' and uchar<=u'\u9fa5': return True else: return False
def get_dugaire_image_label(return_format = 'string'): """ Get the default label used when building images. """ default_label_key = 'builtwith' default_label_value = 'dugaire' default_label = {default_label_key: default_label_value} if return_format == 'string': return f'{default_label...
def return_txt(fn: str) -> list: """ Opens a file and returns the whole file as a list Args: fn (str): File name to open Returns: list: return whole file as a list """ try: with open(fn, "r") as f: return f.readlines() except FileNotFoundError as e: ...
def myfunction_ter(x): """Multiply the value by 3.""" if isinstance(x, int): xx = 3 * x else: xx = None return xx
def int2ap(num): """Convert integer to A-P string representation.""" val = '' ap = 'ABCDEFGHIJKLMNOP' num = int(abs(num)) while num: num, mod = divmod(num, 16) val += ap[mod:mod + 1] return val
def convert_login_customer_id_to_str(config_data): """Parses a config dict's login_customer_id attr value to a str. Like many values from YAML it's possible for login_customer_id to either be a str or an int. Since we actually run validations on this value before making requests it's important to parse...
def compare_versions(version_1: str, version_2: str) -> int: """Compares two version strings with format x.x.x.x Returns: -1, if version_1 is higher than version_2 0, if version_1 is equal to version_2 1, if version_1 is lower than version_2 """ version_1 = version_1.strip('v') version_2 = ...
def lift(a): """Lifts a signal from [-1,1] to [0,1]""" return a / 2 + 0.5
def generateFrameRange(first, last, padding): """Generate a string with all numbers in the frame range. Args: Something (str): Shit. First (int): The number that will be starting the string. Last (int): The last number of the string. Padding (int): The padding of the numbers. ...
def int_max_value(bits,signed=True): """Returns the maximum int value of a signed or unsigned integer based on used bits. Arguments: bits -- How many bits, e.g., 16 signed -- True if a signed int Returns: max_value -- The maximum int value based on given parameters """ if signed: ...
def non_negative_int(s, default): """Parse a string into an int >= 0. If parsing fails or the result is out of bounds, return a default.""" try: i = int(s) if i >= 0: return i except (ValueError, TypeError): pass return default
def evaluate_expr(op1, op2, operator): """Operation helper function. Assuming the only operation we will do is addition, substration, multiplication and division """ if operator == '*': return op1 * op2 elif operator == "/": return op1 / op2 elif operator == "+": ret...
def pycli_of_str(s): """ :param s: a string assumed to be python code :return: a string that would correspond to this code written in a python cli (you know, with the >>> and ...) """ ss = '' for line in s.split('\n'): if len(line) == 0: ss += '>>> ' + line + '\n' el...
def append_csv_data(file_strings): """ Append data from multiple csv files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data Returns ------- out_string : string String with all d...
def checkPalindrome(inputString): """ Given any string, check if it is a palindrome. -> boolean """ stringLen = len(inputString) if (stringLen == 1): return True l = stringLen//2 for i in list(range(l)): if (inputString[i] == inputString[-i-1]): pass else...
def str_or_none(value): """ a type function to check if a value cN be either a string or nonr :param value: :return: """ try: return str(value) except BaseException: return None
def micro_avg_precision(guessed, correct, empty=None): """ Tests: >>> micro_avg_precision(['A', 'A', 'B', 'C'],['A', 'C', 'C', 'C']) 0.5 >>> round(micro_avg_precision([0,0,0,1,1,1],[1,0,0,0,1,0], empty=0), 6) 0.333333 >>> round(micro_avg_precision([1,0,0,0,1,0],[0,0,0,1,1,1], empty=0), 6) ...