content
stringlengths
42
6.51k
def dequote(text): """ If text has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the text unchanged. """ if (text[0] == text[-1]) and text.startswith(("'", '"')): return text[1:-1] return text
def user_login_data(username, data_id): """Return user login data. :param int data_id: Data id """ return { 'username': username, 'data': { 'id': data_id, 'device': 'device_name', 'is_new': True } }
def fallback(choice_1, choice_2): """Fallback function to use choice_2 if choice_1 is None""" return choice_1 if choice_1 is not None else choice_2
def returnPreds(preds, threshold): """ Return predicted binary values from prediction probabilities based on a given threshold Inputs: - preds: prediction probabilities - threshold: threshold for positive prediction value Output: - predicted_labels list of binary predicted labe...
def _tc_enc(value: str, code: int = 32) -> str: """Encode error message values with terminal colors. See: - <https://i.stack.imgur.com/9UVnC.png> - <https://stackoverflow.com/a/61273717> For Python's somewhat-poorly-documented encodings: <https://docs.python.org/3/library/codecs.ht...
def is_wrapped(sack): """Whether the sack block is wrapped. Args: sack: The sack block. Returns: Whether the sack block is wrapped. """ return sack[1] < sack[0]
def inline(text: str) -> str: """Get the given text as inline code. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "`{}`".format(text)
def cipher(text, shift, encrypt=True): """Uses a basic shift (Caesar) cipher to encrypt text input. Parameters ---------- text : str Text to be encrypted shift : int How many positions down the alphabet should the text be shifted? encrypt: bool Default: True If t...
def get_wandb_project_dict_trainval(project_name): """Return wandb project dictionary Args: project_name (str): wandb project name Returns: dict: dictionary containing best models run_id split_name and dataset_name """ res = None if project_name == "lastfm_dat": res = {...
def normalize(iterable, cols, missing_value=""): """In an iterable of dicts, make sure each dict corresponds to keys in the 'cols' list. Missing values are plugged with 'missing_value' """ result = list() for item in iterable: _item = dict(item) _normalized = dict() for ...
def _format_options(options): """ Format a thrift option dict into a compiler-ready string. """ option_list = [] for option, val in options.items(): if val != None: option_list.append("{}={}".format(option, val)) else: option_list.append(option) return ...
def generate_expected_output(start, end, num_shards): """Generate the expected stdout and stderr for the dummy test.""" stdout = '' stderr = '' for i in range(start, end): stdout += 'Running shard %d of %d\n' % (i, num_shards) stdout += '\nALL SHARDS PASSED!\nALL TESTS PASSED!\n' return (stdout, stderr...
def decode_doy(doy): """ Parse string doy to start_doy, end_doy pair. """ if "-" not in doy: start_doy, end_doy = doy, doy else: start_doy, end_doy = doy.split("-") start_doy = int(start_doy) end_doy = int(end_doy) return start_doy, end_doy
def merge_baseline(ant1, ant2, shift=16): """ Merge two stand ID numbers into a single baseline using the specified bit shift size. """ return (ant1 << shift) | ant2
def read_cassandra_config(cassandra_params): """splits out the cassandra parameters""" config = {} for key, value in cassandra_params.items(): if value and key: if value == 'null': config[key] = 'default' else: config[key] = value return co...
def addr(idx: int) -> str: """ Return an IP address for a given node index """ return '10.0.0.%d' % idx
def get_trial_instance_name(experiment: str, trial_id: int) -> str: """Returns a unique instance name for each trial of an experiment.""" return 'r-%s-%d' % (experiment, trial_id)
def code(str): """ detect str is code? """ try: beg = str.lstrip()[:2] return beg != "//" and beg != "/*" except: pass return False
def calcIPValue(ipaddr): """ Calculates the binary value of the ip addresse """ ipaddr = ipaddr.split('.') value = 0 for i in range(len(ipaddr)): value = value | (int(ipaddr[i]) << ( 8*(3-i) )) return value
def url_path_join(*pieces): """Join components of url into a relative url. Use to prevent double slash when joining subpath. This will leave the initial and final / in place. Copied from `notebook.utils.url_path_join`. """ initial = pieces[0].startswith("/") final = pieces[-1].endswith("/"...
def first(list): """ Return the first thing from a list without crashing if the list is empty or not a list """ if list and len(list) > 0: return list[0] return list
def set_api_key(value): """ Sets the API key that you will use to make API requests with Keyword arguments: value -- Your API key """ global api_key api_key = value return api_key
def clamp(x, floor=1, ceiling=5): """ Clamps a value between the values floor and ceiling :param x: The value to be clamped :param floor: The minimum value for x :param ceiling: The maximum value for x :return: The clamped value of x """ if x > ceiling: x = ceiling elif x < f...
def split_addresses(email_string_list): """ Converts a string containing comma separated email addresses into a list of email addresses. """ return [f for f in [s.strip() for s in email_string_list.split(",")] if f]
def multiply_strings(num1, num2): """Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. :type num1: str :type num2: str :rty...
def queryf(x_new, x_old, i, j, f, valid): """ Query the function x_new new x input x_old old input i position of comparison j position of comparison f query function valid a function that checks if the new input is valid, used in case of mixed inputs """ if valid(x_new, f) == 1....
def pack(arg): """ Pack variables into a list. """ if isinstance(arg, (list, tuple)): return list(arg) else: return [arg]
def _map_output_filter(f): """Some comments here.""" if not isinstance(f, (list, tuple)): return False, 0, f # assume is only filter if isinstance(f, list): f = tuple(f) if len(f) == 1: # (fn,) f = (False, 0) + f elif len(f) == 2: # (ip, fn) f = (Fals...
def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' s1 = min(strs) s2 = max(strs) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
def pattern_match(query, patterns=None): """ Simple helper function to see if a query matches a list of strings, even if partially. Parameters ---------- query : string String to check for matches patterns : list of string or None (optional) Patterns to reference, return False if un...
def positioningHeadlines(headlines): """ Strips unnecessary whitespaces/tabs if first header is not left-aligned """ left_just = False for row in headlines: if row[-1] == 1: left_just = True break if not left_just: for row in headlines: row[-1]...
def list_to_string(word_list, join_word='and', prefix='', empty_word='no one'): """ Given a list of strings, join them intelligently. :param word_list: list<str> - Words to join :param join_word: str - The word used to join the list together :param prefix: str - The characters to add in front of eac...
def combinations_construct(tree_config_path, path=["root"]): """ >>> combinations_construct({"root": ["target", "target teams"], ... "target": ["teams"], ... "target teams": [], "teams": []}) [['target'], ['target', 'teams'], ['target teams']] """ ...
def get_key_by_value(dc: dict, value): """ Returns key from dict by value """ for k, v in dc.items(): if v == value: return k
def is_list_of_ints( intlist ): """ Return True if list is a list of ints. """ if not isinstance(intlist,list): return False for i in intlist: if not isinstance(i,int): return False return True
def calc_probability_interaction_extensible(agent_traits, neighbor_traits): """ Given sets, the overlap and probabilities are just Jaccard distances or coefficients, which are easy in python given symmetric differences and unions between set objects. This also accounts for sets of different length, whi...
def count_increasing(ratings, n): """ Only considering the increasing case """ arr = [1] * n cnt = 1 for i in range(1, n): cnt = cnt + 1 if ratings[i - 1] < ratings[i] else 1 arr[i] = cnt return arr
def trickySplit(line, delim): """trickySplit(line, delim) - split line by delimiter delim, but ignoring delimiters found inside (), [], {}, ''' and "". eg: trickySplit("email(root,'hi there'),system('echo hi, mum')", ',') would return: ["email(root,'hi there'", "system('echo hi, mum')"] """ parenCnt ...
def get_workflow_inputs(inputs, input_fields): """Load workflow inputs from a JSON file. Args: metadata_json (str): Path to file containing metadata json for the workflow. Returns: return_inputs (dict): A dict consisting of workflow inputs information. """ return_inputs = [] fo...
def determine_wager(total_money): """ Determine a wager when given total money When placing bets, one should be careful to bet low amounts to not tip the betting pool too much in one direction. This being said, we should bet at a value high enough to make it worth our time. Args: total...
def _get_display_name(name, display_name): """Returns display_name from display_name and name.""" if display_name is None: return name return display_name
def _as_si(x, ndp): """ https://stackoverflow.com/a/31453961/7728169 """ s = '{x:0.{ndp:d}e}'.format(x=x, ndp=ndp) m, e = s.split('e') return r'{m:s}\times 10^{{{e:d}}}'.format(m=m, e=int(e))
def scalar_add_if(x, y): """ scalar_add_if """ if x > y: return x + y + 10 return x + y + 20
def regex_for_coordinates(field_name): """ X:-19.19 Y:6 Z:7.3 A:846.11 B:0 """ return field_name + ':(.+?) '
def eps(newEps=None): """Get/Set the epsilon for float comparisons. eps(newEps) """ global _eps if newEps is not None: _eps = newEps return _eps
def electric_source(data, meta): """ Fix up electricity for how much the Grids consume @ In, data, dict, data requeset @ In, meta, dict, state information @ Out, data, dict, filled data @ Out, meta, dict, state information """ # flip sign because we consume the electricity E = -1.0 * meta['H...
def merge_dicts(*dict_args): """Merge dictionaries from dict_args. When same keys present the last dictionary in args list has the highest priority. Args: dict_args(tuple(dict)) Returns: dict: merged dictionary """ result = {} for d in dict_args: result.update(d) ...
def is_palindrome(n: int) -> bool: """ Check if an integer is palindromic. >>> is_palindrome(12521) True >>> is_palindrome(12522) False >>> is_palindrome(12210) False """ if n % 10 == 0: return False s = str(n) return s == s[::-1]
def convert_old_command_expansions(command): """Convert expansions from !OLD! style to {new}.""" command = command.replace("!VERSION!", "{version}") command = command.replace("!MAJOR_VERSION!", "{version.major}") command = command.replace("!MINOR_VERSION!", "{version.minor}") command = command.repla...
def is_tool(name): """Check whether `name` is on PATH and marked as executable.""" from shutil import which return which(name) is not None
def get_sum(path, tree): """ Returns the sum of all the numbers in the path for the given tree. """ pathsum = 0 for i, row in enumerate(tree): pathsum += row[path[i]] return pathsum
def get_where_operator(conds): """ [ [where_column, where_operator, where_value], [where_column, where_operator, where_value], ... ] """ where_operator = [] for cond in conds: where_operator.append(cond[1]) return where_operator
def split_array_half(array): """ Splits an array like object in half, into two arrays. If of an odd length, the first half will be larger by 1. :param array: array like object to be split in half :return: Two arrays (first_half and second_half) """ midpoint = len(array) // 2 first_half ...
def digital_root(num, modulo = 9): """ similar to modulo, but 0 and 9 are taken as 9 """ # return the remainder if it is more than zero, else return the modulo return num % modulo or modulo
def check_target(difficulty, hash): """checks whether hash contains a certain number of zeros at the beginning params: :param int difficulty: difficulty applied :param str hash: hash to test :return bol """ return hash[:difficulty] == ('0' * difficulty)
def build_ner_vocab(ners): """ :param ners: :return: ner2index """ ner_set = set() for ner in ners: ner_set.update(ner) ners_vocab = {ner: index + 2 for index, ner in enumerate(ner_set)} return ners_vocab
def print_pad(pad_count, pad_char = "\n"): """ pad strings with a total of n = pad_count, pad_char type characters """ padding = "" for i in range(pad_count): padding += pad_char return padding
def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http'
def is_error(status): """Determine if the response has an error status :param status: HTTP Status string to inspect :return: True if the status code is 400 or greater, otherwise False """ return int(status.split(' ', 1)[0]) >= 400
def _get_key_data(report_data): """ Function to get key data to fetch data from report data :param report_data: Object containing report data :return parsed report """ report = dict() # Iterating over data for each report for key, data in report_data.items(): report[key] = dict() ...
def class_group(cls): """class_group(cls) Converts a class name into a standardized set of classes. Positional arguments: cls (str) - class name Returns: (int) - a standard class ID number (see class_dict above) """ if "no data" in cls or len(cls) < 2: return -1 ...
def INDEX_OF_BYTES(string_expression, substring_expression, start=None, end=None): """ Searches a string for an occurence of a substring and returns the UTF-8 byte index (zero-based) of the first occurence. If the substring is not found, returns -1. https://docs.mongodb.com/manual/reference/operator/agg...
def parse_bytes(possible_bytes): """bytes can be compressed with suffixes but we want real numbers in kb""" try: return int(possible_bytes) except: if possible_bytes[-1].lower() == 'm': return int(float(possible_bytes[:-1]) * 1024) if possible_bytes[-1].lower() == 'g': ...
def parse_name_field(input_dict): """Take a dict with key: value or key: list_of_values mappings and return a list of tuples""" result = [] for key in input_dict: if isinstance(input_dict[key], list): for entry in input_dict[key]: result.append((key, entry)) else...
def remove_disambiguation(doc_id): """ Normalizes and removes disambiguation info from a document ID. """ doc_id = doc_id.replace('_', ' ').replace('-COLON-', ':') if '-LRB-' in doc_id: doc_id = doc_id[:doc_id.find('-LRB-') - 1] return doc_id
def split_by_newline(response): """ Return a list of string split by newline character """ return response.split("\n")
def func_xy(x, y): """func. Parameters ---------- x, y: float Returns ------- x, y: float None, None, None, None, None, None """ return x, y, None, None, None, None, None, None
def to_js_bool(bool_value): """ Convert python True/False to javascript string "true"/"false" for easily adding parameter to top of page scripts so javascript code can use. Handy for placing context values from context into javascript variables on a page :param bool_value: expects python True/False val...
def ensure_trailing_slash(url: str) -> str: """ensure a url has a trailing slash""" return url if url.endswith("/") else url + "/"
def gwrap(some_string): """Wraps a string to be green.""" return "\033[92m%s\033[0m" % some_string
def dict_pathsearch(dict, path): """ Finds a value inside a dictionary of dictionaries given a path-like string of keys separated by periods. Raises KeyError if the requested path doesn't exist. Example ------- Given a dictionary like the following: { foo : "foo" ...
def to_tuple_if_int(value): """ If int is given, duplicate it and return as a 2 element tuple. """ if isinstance(value, int): return (value, value) return value
def calculate_fibonacci(num: int) -> int: """ >>> calculate_fibonacci(-1) Traceback (most recent call last): ... ValueError: num must not be negative. >>> calculate_fibonacci(0) 0 >>> calculate_fibonacci(1) 1 >>> calculate_fibonacci(2) 1 >>> calculate_fibonacci(3) ...
def GetTextInComments(comments): """Gets the comments for the given issue id as a list of text fields. Args: comments: A list of CommentEntry instances. Returns: String of the attached. """ comments_text = [c.content.text for c in comments if c.content.text] return ' '.join(comments_text)
def is_letter(ch): """is letter""" print("is_letter", ch) if ch == -1: return False return ord('a') <= ord(ch) <= ord('z') or ord('A') <= ord(ch) <= ord('Z') or ch == ord('_')
def flatten(s): """Flattens list recursively""" if s == []: return s if isinstance(s[0], list): return flatten(s[0]) + flatten(s[1:]) return s[:1] + flatten(s[1:])
def _get_instances_from_kv(get_from_kv_func, user): """Get component instances from kv store Deployed component instances get entries in a kv store to store configuration information. This is a way to source a list of component instances that were attempted to run. A component could have deployed but f...
def reverseString(s): """ :type s: str :rtype: str """ return s[::-1]
def folder2ver(folder): """get the version number from the E+ install folder""" ver = folder.split("EnergyPlus")[-1] ver = ver[1:] splitapp = ver.split("-") ver = ".".join(splitapp) return ver
def sci_name(value): """Returns genus/species/subspecies list from a scientific name""" values = value.split() list = [] if len(values) >= 2: [list.append(value) for value in values[0:2]] if len(values) == 3: list.append(values[2]) while len(list) < 3: list.append('') ...
def values_list(hits, *fields, **kwargs): """modeled after django's QuerySet.values_list""" flat = kwargs.pop('flat', False) if kwargs: raise TypeError('Unexpected keyword arguments to values_list: %s' % (list(kwargs),)) if flat and len(fields) > 1: raise TypeErro...
def get_Tuple_params(tpl): """Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return tpl.__tuple_params__ except...
def transform_int_list_to_hex_str(key_list): """ Convert key from integer list to hex string. :param key_list: Input key as integer list :return: Key as hex string format """ key_hex_str = "" for key_item in key_list: hex_str_item = format(key_item, 'x') if len(hex_str_item) ...
def levenshtein(s1, s2): """Returns the levenshtein distance (aka edit distance) between two strings. Args: s1 (str) - The first string. s2 (str) - The second string.""" # Implementation from https://code.activestate.com/recipes/576874-levenshtein-distance/ # See also, https://en.wikipedia.or...
def color(string, color=None): """ Change text color for the Linux terminal. """ attr = [] # bold attr.append('1') if color: if color.lower() == "red": attr.append('31') elif color.lower() == "green": attr.append('32') elif color.lower() == "...
def get_overlap(i1, i2, j1, j2): """ Get overlap between spans """ A = set(range(i1, i2)) B = set(range(j1, j2)) overlap = A.intersection(B) overlap = sorted(list(overlap)) return overlap
def clear_comments(content: str) -> str: """Remove all comments from the commit message. Args: content: The content of the commit message. """ return "\n".join(l for l in content.split("\n") if not l.startswith("#"))
def deduplicate_edges(edges): """ Takes an iterable of edges and makes sure there are no reverse edges :param edges: iterable of edges :return: uniq_edges: unique set of edges """ uniq_edges = set() for u, v in edges: if (v, u) not in uniq_edges: uniq_edges.add((u, v)) ...
def reasons_to_paths(reasons): """Calculate the dependency paths to the reasons of the blockers. Paths will be in reverse-dependency order (i.e. parent projects are in ascending order). """ blockers = set(reasons.keys()) - set(reasons.values()) paths = set() for blocker in blockers: ...
def lin_interp(x,x0,x1,y0,y1): """ lin_interp(x,x0,x1,y0,y1) Linearly interpolates for y between y0 and y1, given x0, x1, and x. """ return y0+(y1-y0)*(x-x0)/(x1-x0)
def linear_search(L, v): """ (list, object) -> int Return the index of the first occurrence of v in L, or return -1 if v is not in L. >>> linear_search([2, 3, 5, 3], 2) 0 >>> linear_search([2, 3, 5, 3], 5) 2 >>> linear_search([2, 3, 5, 3], 8) -1 """ i = 0 while i != l...
def variance(values, mean): """Calculate sample variance.""" return sum(map(lambda v: (v - mean)**2, values)) / len(values)
def _safe_slice(array, idx): """Slice an array safely along the row axis""" if array is None: return array elif hasattr(array, 'iloc'): return array.iloc[idx] return array[idx]
def minimax(val, low, high): """ Return value forced within range """ try: val = int(val) except: val = 0 if val < low: return low if val > high: return high return val
def allowed_file(filename, allowed_set): """Checks if filename extension is one of the allowed filename extensions for upload. Args: filename: filename of the uploaded file to be checked. allowed_set: set containing the valid image file extensions. Returns: check: boolean value ...
def busbin(n,ult,lis,ini=1): """ Realiza a BUSca BINaria do valor de "n" na lista ordenada "lis". Parametros: n (int): numero a se verificar ult (int): ultimo indice lis (list): lista ordenada a ser percorrida ini (int): inicio da lista, default=1 Retorna: int: o proprio valor...
def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return tuple(line for line in lineiter if line and not line.startswith("#"))
def SetDsymutilPath(dsymutil_path, full_args): """Linker driver action for -Wcrl,dsymutilpath,<dsymutil_path>. Sets the invocation command for dsymutil, which allows the caller to specify an alternate dsymutil. This action is always processed before the RunDsymUtil action. Args: dsymutil_path: string, T...
def concat_without_dot(args): """ replace blank >>> concat_without_dot('42foo bar') '42foobar' """ return "".join([str(s) for s in args.split()])
def merge_sort(array): """merge_sort(list) - list Recursive divide and conquer >>> merge_sort([3, 2, 13, 4, 6, 5, 7, 8, 1, 20]) [1, 2, 3, 4, 5, 6, 7, 8, 13, 20] """ if len(array) > 1: mid = len(array) / 2 left = array[:mid] right = array[mid:] merge_sort(left) ...