content
stringlengths
42
6.51k
def find_index_unsafe(val, bin_edges): """Find bin index of `val` within binning defined by `bin_edges`. Validity of `val` and `bin_edges` is not checked. Parameters ---------- val : scalar Assumed to be within range of `bin_edges` (including lower and upper bin edges) bin_edge...
def makeDictFromCommaSepString(s): """ Reads in comma-separated list and converts to dictionary of successive keyword,value pairs. """ if s.count(",") % 2 == 0: raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s) d = {} items = ...
def calculate_velocity(c, t): """ Calculates a velocity given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the velocity Returns Velocity """ retu...
def cache_hostinfo(environ): """Processes the host information and stores a copy This work was previously done but wasn't stored in environ, nor is it guaranteed to be setup in the future (Routes 2 and beyond). cache_hostinfo processes environ keys that may be present to determine the proper host,...
def processCommandLine(argv): """ parses the arguments. removes our arguments from the command line """ retVal = {} retVal['client'] = '' retVal['server'] = False retVal['port'] = 0 retVal['file'] = '' i = 0 del argv[0] while (i < len(argv)): if (argv[i] == '--port'):...
def negate_mod(operand, modulus): """returns (-1 * operand) % modulus""" if modulus == 0: raise ValueError("Modulus cannot be 0") if operand >= modulus: raise OverflowError("operand cannot be greater than modulus") non_zero = operand != 0 return (modulus - operand) & (-int(non_zero))
def relu_d(x:float)->float: """ This function takes in input in int and returns the computed derivaive of relu which is 1 for x > 0 """ if x > 0: return 1 return 0
def make_link(G, node1, node2): """ DAG """ if node1 not in G: G[node1] = {} (G[node1])[node2] = 1 if node2 not in G: G[node2] = {} (G[node2])[node1] = -1 return G
def ds0_gen(m): """Generates the 2 budgets, 2 bid vectors, and 2m queries for dataset ds0. Keyword arguments: n -- number of advertisers, an integer B -- budget for all advertisers, an integer """ # one advertiser pays 1 for both keywords # and one pays 0.5 for only one ...
def iterate_revert_string(s: list) -> list: """ revert list iterate method """ i = 0 j = len(s) - 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 return s
def find_year(result: list, year: int) -> list: """ Return a list of films made only in specific year. >>> find_year(['"#1 Single" (2006)', 'Los Angeles, California, USA'], 2005) [] >>> find_year(read_file('locations.list', 1), 2006) [['"#1 Single" (2006)', 'Los Angeles, California, USA']] "...
def sp_needs_rebuild(orig_net, new_net, sp_id): """Determines if a synapse-pool needs rebuild for new network dictionary. Parameters: orig_net : dict Dictionary containing the original network. new_net : dict Dictionary containing the new edited network. sp_id : str Stri...
def count(word, lst): """Count number of occurences of word in list.""" n = 0 for elem in lst: if word == elem: n += 1 return n
def _u(s): """ This function is a stupid one, but it really works! convert 's' to utf8 """ if not s: return s s = s.strip() if not s: return s for c in ('utf8','gbk','big5','jp','kr'): try: return s.decode(c).encode('gbk') except: pass return s
def fieldsSame(first, second, fields): """ Checks if all `fields` of `first` are the same as in `second`""" for field in fields: if field not in first or field not in second: return False if first[field] != second[field]: return False return True
def find_sum_of_arithmetic_sequence(requested_terms: int, first_term: int, common_difference: int) -> int: """ Finds the sum of an arithmetic sequence :param requested_terms: :param first_term: :param common_difference: :return: the sum of an arithmetic sequence """ return int((r...
def get_principals(sql_result, username, shell=False): """ Transform sql principals into readable one """ if sql_result is None or sql_result == '': if shell: return username return [username] else: if shell: return sql_result return sql_result...
def discount_calc(price, discount: int) -> str: """ Calculates the final price you'll pay using a discount. Args: price: (int/float) The original price. If int, it will be transformed into a float. discount: (int) The discount value. If float, decimal values will be ignored. Returns:...
def rate_color(rate: int) -> str: """ Get color schema for percentage value. Color schema looks like red-yellow-green scale for values 0-50-100. """ color = '[red]' if 30 > rate > 20: color = '[orange_red1]' if 50 > rate > 30: color = '[dark_orange]' if 70 > rate > 50: ...
def arborist_role_for_permission(permission): """ For the programs/projects in the existing fence access control model, in order to use arborist for checking permissions we generate a policy for each combination of program/project and privilege. The roles involved all contain only one permission, fo...
def rotate90_point(x, y, rotate90origin=()): """Rotates a point 90 degrees CCW in the x-y plane. Args: x, y (float): Coordinates. rotate90origin (tuple): x, y origin for 90 degree CCW rotation in x-y plane. Returns: xrot, yrot (float): Rotated coordinates. """ # Translate ...
def merge(left,right): """ merge two arrays :param left: :param right: :return: """ print(left,right) i_right = 0 res = [] i_left= 0 while i_left < len(left) and i_right < len(right): if left[i_left] < right[i_right]: res.append(left[i_left]) i...
def get_workflow_name(workflow_type): """ Given a workflowType workflow_type, return the name of a corresponding workflow class to load """ return "workflow_" + workflow_type
def tab_in_leading(s): """ Returns True if there are tabs in the leading whitespace of a line, including the whitespace of docstring code samples. """ n = len(s) - len(s.lstrip()) if not s[n:n + 3] in ['...', '>>>']: check = s[:n] else: smore = s[n + 3:] check = s[:n]...
def parse_values_to_append(options): """Manual parsing of --append arguments. :param options: list of arguments following --append argument. :return: dictionary containing key paths with values to be added :rtype: dict """ parsed = {} for argument in options: if len(argument.split('...
def linspace(a, b, n=100): """ return array of floats form a to b in n elements """ dx = (b - a) / (n - 1) return [a + dx * i for i in range(int(n))]
def merge_dicts(dict_1, dict_2): """ Merge dictionary dict_2 into dict_1. In case of conflict dict_1 has precedence """ if dict_1 is None: return dict_2 if dict_2 is None: return dict_1 result = dict_1 for key in dict_2: if key in dict_1: if isinstan...
def format_geo(geography_id): """ Format geography id for use within an SDF :param geography_id: string; corresponds to DV360 geography id :return: string; formatted for SDF usage """ return '{};'.format(geography_id)
def _maybe_append_seq(n, prefix): """Append a sequence value to a prefix if non-zero""" if not n: return prefix return "{} {}".format(prefix, n)
def remove_zeros(res): """ res is expected to be a dictionary of dictionaries representing a flow graph. """ res1 = {} for k in res.keys(): res2 = {} for kk in res[k].keys(): if res[k][kk] > 0: res2[kk] = res[k][kk] if len(res2) > 0: ...
def brief_documentation(method: object) -> str: """ Return first line of an object documentation """ doc = method.__doc__ if doc is not None: lines = doc.splitlines() if len(lines) > 0: return lines[0] return ''
def get_param_cols(columns): """ Get the columns that were provided in the file and return that list so we don't try to query non-existent cols Args: columns: The columns in the header of the provided file Returns: A dict containing all the FPDS query columns that the provi...
def sol(arr, n): """ For every sum of two elements store it in a hash where 'sum' is the key and list of sorted indexes are values. If for a given sum the indexes do not already exist return True """ sh = {} for i in range(n-1): for j in range(i+1, n): s = arr[i]+arr[j] ...
def _handle_docker_port(port): """Translates a Docker-Compose style port to a Kubernetes servicePort """ kube_port = {} try: kube_port["port"] = port.split(":")[1] kube_port["targetPort"] = port.split(":")[0] except IndexError: kube_port["port"] = port.split(":")[0] return k...
def reverse(s): """ Returns s with its characters in reverse order Parameter: s the string to reverse Precondition s is a string """ assert type(s) == str, repr(s) + ' is not a string' # get in the habit # Work on small data (BASE CASE) if s == '': return s # Break up...
def postorderTraversal(root): """Post Order Traversal, Recursive""" res = [] if not root: return res else: res += postorderTraversal(root.left) res += postorderTraversal(root.right) res.append(root.data) return res
def set_params(object,kw,warn=1): """Given an object and a dictionary of keyword arguments, set only those object properties that are already instance variables of the given object. Returns a new dictionary without the key,value pairs that have been used. If all keywords have been used, afterwards...
def energy_n(n): """ Create a function to calculate the energy level of a given principal quantum number. This function should take 1 int argument and return the energy level in eV. Round to 5 decimal places :param: n(int) : nodes :output: float (rounded to 5 decimal places) """ ...
def parse_type(text): """ "normalize" a mime type >>> parse_type('text/plain') 'text/plain' >>> parse_type('text') 'application/octet-stream' >>> parse_type('') 'application/octet-stream' >>> parse_type(None) 'application/octet-stream' """ if not text or '/' not in text:...
def dbc(module, tag): """Mapping for dash bootstrap components. The default assumes that :mod:`dash_bootstrap_components` is imported as ``dbc``, which can be changed by setting `module`. """ if tag in { "Alert", "Badge", "Button", "ButtonGroup", "Card", ...
def is_one_digit(num): """ Check's if number is single digit. :param num: value of integer being checked """ output = '' if num > -10 and num < 10 and num.is_integer(): output = True else: output = False return output
def reportError(template, callstack=(), severity='', message='', errorId='', suppressions=None, outputFunc=None): """ Format an error message according to the template. :param template: format string, or 'gcc', 'vs' or 'edit'. :param callstack: e.g. [['file1.cpp',10],['file2.h','20'], ... ]...
def clean(configs, data): """ Cleans data (array of dicts) using configuration of parse functions """ clean_data = [] for item in data: clean_item = {} for name, friendly_name, convert_function in configs: clean_item[friendly_name] = convert_function(item[name]) c...
def possible_segment_start(idx, min_size = 1, max_size = None): """ Generates the list of all possible starts of segments given the index of its end. Parameters ---------- idx: integer The end of a segment. min_size: integer Minimal length of a segment. max_size: integer...
def pre_process_text(html_text): """ Parameters ---------- html_text : str Article text. Returns ------- words: str lower case, just letters """ words = "".join(filter(str.isalpha, html_text)).lower() return words
def parse_literal(x): """ return the smallest possible data type for a string :param x: a string to be parsed :return a value of type int, float or str """ if isinstance(x, list): return [parse_literal(y) for y in x] elif isinstance(x, (bytes, str)): try: return ...
def contar_palabra(linea: str, palabra: str) -> int: """Cuenta cuantas veces se repite una palabra en una cadena de texto. :param linea: Cadena de texto. :linea type: str :param palabra: Palabra a buscar. :palabra type: str :return: Cuantas veces se repite la palabra en la cadena. :rtyp...
def sizeof_fmt(num, suffix='B', longsuffix=True, usespace=True, base=1024): """ Returns a string representation of the size ``num``. - Examples: >>> sizeof_fmt(1020) '1020 B' >>> sizeof_fmt(1024) '1 KiB' >>> sizeof_fmt(12011993) '11.5 MiB' >>> sizeof_fmt(123456789) '117.7 MiB' ...
def convert_frequency(value: str) -> int: """@brief Applies scale suffix to frequency value string. @param value String with a float and possible 'k' or 'm' suffix (case-insensitive). "Hz" may also follow. No space is allowed between the float and suffix. Leading and trailing whitespace is allow...
def _transform_twodigited_date_into_forudigited_if_needed(indef_digited_str): """ We are turning the string into an int. Depending on its value, we add a quantity to that int, obtaining the year. Examples: receiving 10: 10 + 2000 = 2010. return 2010 as year receiving 98: 98 +...
def rm_prefix(name): """ Removes ironic_ os_ ironicclient_ prefix from string. """ if name.startswith('ironic_'): return name[7:] elif name.startswith('ironicclient_'): return name[13:] elif name.startswith('os_'): return name[3:] else: return name
def strip(raw_input): """Strip strings, convert NaN and None to empty string""" if raw_input is None or raw_input == "NaN": return "" return raw_input.strip()
def _compute_iou(box1, box2): """ Parameters ---------- box1, box2: (x1, y1, x2, y2) """ xx1 = max(box1[0], box2[0]) yy1 = max(box1[1], box2[1]) xx2 = min(box1[2], box2[2]) yy2 = min(box1[3], box2[3]) if xx1 >= xx2 or yy1 >= yy2: return 0. inter = (xx2 - xx1) ...
def lstrip_namespace(s, namespaces): """ Remove starting namespace :param s: input string :type s: ```AnyStr``` :param namespaces: namespaces to strip :type namespaces: ```Union[List[str], Tuple[str], Generator[str], Iterator[str]]``` :returns: `.lstrip`ped input (potentially just the ori...
def avoid_walls(possible_moves: dict, width: int, height: int): """ Removes the moves that will collide with walls """ moves_to_remove = [] for move in possible_moves: if not (0 <= possible_moves[move]["x"] < width and 0 <= possible_moves[move]["y"] < height): moves_to_remove.append(move...
def get_appropriated_part_size(file_size): """ Gets the appropriated part size when uploading or downloading files, given an initial file size. """ if file_size <= 104857600: # 100MB return 128 if file_size <= 786432000: # 750MB return 256 if file_size <= 2097152000: # 200...
def gcd(a, b): """Find the greatest common denominator of two integers. Using Euclid's algorithm. """ b = abs(b) while b != 0: a, b = (b, a % b) return a
def str_to_type (s): """ Get possible cast type for a string Parameters ---------- s : unicode string Returns ------- float,int,str,bool : type Depending on what it can be cast to """ try: f = float(s) if "." not in s: return int return ...
def mean(iterable, length=None): """ Returns the arithmetic mean of the values in the given iterable or iterator. """ if length is None: if not hasattr(iterable, "__len__"): iterable = list(iterable) length = len(iterable) return sum(iterable) / float(length or 1)
def adjustHF(H, F, n_new, n_old): """ adjust hit/false alarm rate for ceiling effects according to Macmillan&Creelman, pp8 urut/nov06 """ if H == 1: H = 1 - 1/(2*n_old) if F == 1: F = 1 - 1/(2*n_new) if H == 0: H = 1/(2*n_old) if F == 0: F = 1/(2*n_ne...
def BezierTransistion (search, handles): """ solving y (progress) of bezier curve for given x (time) using the newton-raphson method """ h1x, h1y, h2x, h2y = handles cx = 3 * h1x bx = 3 * (h2x - h1x) - cx ax = 1 - cx - bx t = search for i in range (100): x = (ax*t**3 + bx*t**2 + cx*t) -...
def toggle_collapse(n, is_open): """ Toggle button to show instructions """ if n: return not is_open return is_open
def ED(first, second): """ Returns the edit distance between the strings first and second.""" if first == '': return len(second) elif second == '': return len(first) elif first[0] == second[0]: return ED(first[1:], second[1:]) else: substitution = 1 + ED(first[1:], se...
def get_likely_script(locale, likely_script_dict): """Find the likely script for a locale, given the likely-script dictionary. """ if locale.count('_') == 2: # it already has a script return locale.split('_')[1] elif locale in likely_script_dict: return likely_script_dict[locale]...
def _policy_profile_generator(total_profiles): """ Generate policy profile response and return a dictionary. :param total_profiles: integer representing total number of profiles to return """ profiles = {} for num in range(1, total_profiles + 1): name = "pp-%s...
def intersperse(interspersed_item, items) -> list: """Put `interspersed_item` between each of the elements of `items`.""" if not items: return [] ret = [items[0]] for item in items[1:]: ret.append(interspersed_item) ret.append(item) return ret
def zone_eval(Dx, Dy, data): """ gives back the formatted list of adjacent seats """ switch_list = [] for i in range(Dy[0], Dy[1] + 1): temp = [data[i][j] for j in range(Dx[0], Dx[1] + 1)] switch_list.append(temp) return switch_list
def clean_data(data_in): """ Cleans data in a format which can be conveniently used for drawing traces. Takes a dictionary as the input, and returns a list in the following format: input = {'key': ['a b c']} output = [key, [a, b, c]] """ key = list(data_in.keys())[0] data_out = [key...
def _is_id(value): """ Check if the value is valid InfluxDB ID. :param value: to check :return: True if provided parameter is valid InfluxDB ID. """ if value and len(value) == 16: try: int(value, 16) return True except ValueError: return False...
def car_maiusculo(car): """ car_maiusculo: string --> string car_maiusculo(car) recebe um caracter e devolve o mesmo caracter na forma maiuscula. """ if 'A' <= car <= 'Z': return car elif 'a' <= car <= 'z': return chr(ord(car) - abs(ord('A') - ord('a'))) else: rai...
def accuracy_score(y_true, y_pred): """Classification performance metric compute the accuracy of y_true and y_pred :param numoy.array y_true: like a shape array :param numoy.array y_pred: like a shape array :return c (float) accuracy score""" correct = 0 for true, pred in zip(y_true,y_pred): ...
def fuzzy_substring(needle, haystack): """Calculates the fuzzy match of needle in haystack, using a modified version of the Levenshtein distance algorithm. The function is modified from the levenshtein function in the bktree module by Adam Hupp""" m, n = len(needle), len(haystack) # base ca...
def string_to_unicode(string_): """Converts a given ASCII string to unicode""" return "".join([c.ljust(2, "\x00") for c in string_])
def tweak_thimble_input(stitch_dict, cmd_args): """ :param stitch_dict: Dictionary produced by stitchr :param cmd_args: command line arguments passed to thimble :return: Fixed stitchr dict (species capitalised, TCR names blanked) """ stitch_dict['species'] = cmd_args['species'].upper() stitc...
def parse_tool_output(text): """Given the tab-delimited output from an invocation of mp3gain or aacgain, parse the text and return a list of dictionaries containing information about each analyzed file. """ out = [] for line in text.split('\n'): parts = line.split('\t') if len(pa...
def repeat_count_with_max_length(x, maxLength, assertAtLeastOneRep=False): """ Compute the number of times a operation sequence x must be repeated such that the repeated string has length <= maxLength. Parameters ---------- x : tuple or Circuit the operation sequence to repeat maxLe...
def rev_dict(dc: dict) -> dict: """ Return dict inversely mapping key-value pairs in ``dc``. """ return dict(tuple((i[1], i[0]) for i in tuple(dc.items())))
def init(P_k__l, tau, n, rho, u_l__l, m, U_l__l): """ Step 3. """ t_k__l = n + tau + 1 T_k__l = tau * P_k__l u_k__l = rho * (u_l__l - m - 1) + m + 1 U_k__l = rho * U_l__l return t_k__l, T_k__l, u_k__l, U_k__l
def chr_set_null(chr_value): """sql util function""" return "null" if chr_value is None or not chr_value else \ ''.join(("'", chr_value, "'"))
def validipaddr(address): """returns True if `address` is a valid IPv4 address""" try: octets = address.split('.') assert len(octets) == 4 for x in octets: assert 0 <= int(x) <= 255 except (AssertionError, ValueError): return False return True
def _find_param_separator(tokens): """ Return the index of the param separator. :param list tokens: list of tokens on the parameter line :returns: integer index of the separator or :data:`None` if no separator is found :rtype: int Different versions of sphinxcontrib-httpdomain/autotorn...
def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to...
def _find_corresponding_multicol_key(key, keys_multicol): """Find the corresponding multicolumn key.""" for mk in keys_multicol: if key.startswith(mk) and 'of' in key: return mk return None
def _str_to_bool(s): """Convert "True" and "False" strings to a boolean. Parameters ---------- s : str String representation of boolean Returns ------- """ if s == "True": return True elif s == "False": return False else: msg = 'Invalid string p...
def find_matches_tables(name, tables): """ This function ... :param name: :param tables: :return: """ # ... if "/" in name: matches = [] dir_name = name.split("/")[0] script_name = name.split("/")[1] for subproject in tables: if dir_name !...
def subList(l, sl) : """return the index of sl in l or None""" lLen = len(l) slLen = len(sl) for i in range(lLen - slLen + 1): j = 0 while j < slLen and l[i + j] == sl[j]: j += 1 if j == slLen: return i return None
def extract_JSON_values(obj, key): """Pull all values of specified key from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict, li...
def get_attr(obj, name): """Emulate built in getattr""" if name in obj.__dict__: print(f"found {name} in obj") return obj.__dict__[name] if name in obj.__class__.__dict__: print(f"found {name} in class") return obj.__class__.__dict__[name] for cls in obj.__class__.__mro...
def find_brackets(text): """Find angle brackets""" start = text.index("<") if "<" in text else -1 stop = text.index(">") if start >= 0 and ">" in text[start + 2 :] else -1 return (start, stop) if start >= 0 and stop >= 0 else None
def resta (num1, num2): """Funcion que resta dos numeros imaginarios, los numeros deben ser parejas ordenadas (list 1D, list 1D) -> list 1D""" ans1 = num1[0] - num2[0] ans2 = num1[1] - num2[1] return (ans1, ans2)
def norm(x, train_stats): """ Normalize the data. """ return (x - train_stats['mean']) / train_stats['std']
def find_area(x_data, y_data): """Finds the area under the curve given by points (x_data, y_data) using the trapezoid rule. Input data must be ordered.""" area = 0 for i in range(len(x_data)-1): a_x = x_data[i] a_y = y_data[i] b_x = x_data[i+1] b_y = y_...
def get_debug_info(nodes_to_debug_info_func, converted_graph): """Returns the debug info for the original nodes in the `converted_graph`. Args: nodes_to_debug_info_func: The method to collect the op debug info for the nodes. converted_graph: A `GraphDef` after optimization and transformation. Retu...
def calculate_bucket_count_in_heap_with_height(k, h): """ Calculate the number of buckets in a k-ary heap of height h. """ assert h >= 0 return ((k**(h+1)) - 1) // (k - 1)
def RemoveRedundantTranscripts(transcripts, peptides): """remove redundant entries. Also check for presence. """ sequences = [] new = [] new.append(transcripts[0]) try: sequences.append(peptides[transcripts[0][0]]) except KeyError: return new for t in transcripts[1:]: ...
def max_safe(iterable): """Creates a wrapper over python max() function. This function is just a wrapper over pthon max(). It catches the exceptions and let max() return without any error. """ try: return max(iterable) except ValueError: # The TypeError is not caught here as th...
def _str_to_ord(content, weights, alphabet): """Converts a string to its lexicographical order. Args: content: the string to convert. Of type str. weights: weights from _get_weights. Returns: an int or long that represents the order of this string. "" has order 0. """ ordinal = 0 for i, c in e...
def withdraw_money(amount, card_balance): """Withdraw given amount of money from the account.""" card_balance -= amount # save new balnace to the database return card_balance
def split_by_resources(tests): """Split a list of tests by the resources that the tests use. :return: a dictionary mapping sets of resources to lists of tests using that combination of resources. The dictionary always contains an entry for "no resources". """ no_resources = frozenset() res...
def consistency_index(sel1, sel2, num_features): """ Compute the consistency index between two sets of features. Parameters ---------- sel1: set First set of indices of selected features sel2: set Second set of indices of selected features num_features: int Total number ...