content
stringlengths
42
6.51k
def gql_project_version(fragment): """ Return the GraphQL projectVersion query """ return f''' query ($where: ProjectVersionWhere!, $first: PageSize!, $skip: Int!) {{ data: projectVersions(where: $where, first: $first, skip: $skip) {{ {fragment} }} }} '''
def issubclass_(t1, t2): """ Version of builtin ``issubclass`` but doesn't throw error when the first argument is not a class. """ if not isinstance(t1, type): return False return issubclass(t1, t2)
def empty_to_none(param_mode): """ noticed some tuned hyperparameters come back as {} change to None for consistency """ try: if len(eval(param_mode) ) == 0: return 'None' else: return param_mode except: return param_mode
def artists_to_mpd_format(artists): """ Format track artists for output to MPD client. :param artists: the artists :type track: array of :class:`mopidy.models.Artist` :rtype: string """ artists = list(artists) artists.sort(key=lambda a: a.name) return ', '.join([a.name for a in arti...
def clean_headers(headers): """ Sanitize a dictionary containing HTTP headers of sensitive values. :param headers: The headers to sanitize. :type headers: dict :returns: A list of headers without sensitive information stripped out. :rtype: dict """ cleaned_headers = headers.copy() ...
def increment(dictionary, k1, k2): """ dictionary[k1][k2]++ :param dictionary: Dictionary of dictionary of integers. :param k1: First key. :param k2: Second key. :return: same dictionary with incremented [k1][k2] """ if k1 not in dictionary: dictionary[k1] = {} if 0 not in d...
def split_columns(x): """Helper function to parse pair of indexes of columns This function is called by ArgumentParser """ try: a, b = map(int, x.split(",")) # columns from command line are numbered starting from 1 # but internally we start counting from 0 return a - 1,...
def str_snake_to_camel(term): """Convert a string from snake_case to camelCase. Parameters ---------- term : string Returns ------- string """ camel = term.split("_") return "".join(camel[:1] + list([x[0].upper() + x[1:] for x in camel[1:]]))
def get_union_over_keys(map_to_set): """Compute the union of the map range values. For a map whose range is a set, union the range over keys in the map return the resulting set. """ result = set() for key in map_to_set: value_set = map_to_set[key] result |= value_set; ...
def convert_format(fformat): """ """ fformat = fformat.lower() if 'netcdf' in fformat: fid, term = 'netcdf', 'netcdf' elif 'grib' in fformat: fid, term = 'grib', 'grib' elif 'hdf' in fformat: fid, term = 'hdf', 'hdf' elif fformat == 'um': fid, term = 'binary',...
def _maven_artifact(group, artifact, version, packaging = None, classifier = None, override_license_types = None, exclusions = None, neverlink = None): """ Generates the data map for a Maven artifact given the available information about its coordinates. Args: group: *Required* The Maven artifact c...
def nextGap(gap): """Finds the next gap to increment the sort by""" newGap = (gap * 10) // 13 return 1 if newGap < 1 else newGap
def api_url(lang): """Return the URL of the API based on the language of Wikipedia.""" return "https://%s.wikipedia.org/w/api.php" % lang
def combine_args(supported_args, *arg_sets): """ Combine args with priority from first in the list to last in the list """ base_dict = arg_sets[0] sup_arg_dict = {arg['name']: arg['arg_params'] for arg in supported_args} for i in range(1,len(arg_sets)): this_dict = arg_sets[i] if this_di...
def restrict_by(payload, pkey, dest_table=None, tkey=None): """ 1. Restrict the list of dicts payload by unique instances of a payload key 2. Remove items where payload key is already in the tkey value of the dest_table """ unique_payload = list({v[pkey]: v for v in payload if v[pkey] is not None}.v...
def clamp(x, l, u): """ clamp x to be l <= x <= u >>> clamp(5, 1, 10) 5 >>> clamp(-1, 1, 10) 1 >>> clamp(12, 1, 10) 10 """ return l if x < l else u if x > u else x
def _rescale_param(param, value, dnu): """ Rescales the resolution value if a dnu parameter is chosen. Parameters ---------- param : str Parameter name. value : float, array Value(s) to be rescaled dnu : float Solar value of dnu given in input. Returns -----...
def is_property(k: str) -> bool: """Check if key is a property.""" return k.startswith("__") and k.endswith("__")
def get_compatible_version(version): """Return the compatible version. :arg str version: Version string. :return: The compatible version which could be used as ``~={compatible_version}``. :rtype: str Suppose the version string is ``x.y.z``: * If ``x`` is zero then return ``x.y.z``. ...
def english_score(input_bytes: bytes): """Takes in a byte string. Outputs a score representing likelihood the string is English text (compared to other strings)""" # The following set contains the decimal number that corresponds to the ASCII for the most common english # characters ('ETAOIN SHRDLU') in both upper an...
def _subtract(groupA, groupB): """Returns groupA without elements that are also in groupB""" return [item for item in groupA if not item in groupB]
def split_strip(input, delimiter=','): """ Splits ``input`` on ``delimiter``, stripping each resulting string and returning a list of non-empty strings. """ words = [w.strip() for w in input.split(delimiter)] return [w for w in words if w]
def sfdr(iip3=0, mds=0): """ Calculate SFDR from IIP3 and mds. :param iip3: Input-referred 3rd-order intercept point in dBm. :param mds: Minimum detectable signal in dBm. """ return 2 / 3 * (iip3 - mds)
def writePageHeader(functionName): """ Write the page header for the man page. Takes in the form of: .TH [name of program] [section number] [center footer] [left footer] [center header] """ titleHeader = ".TH " + functionName.upper() + " 3 " \ + "\"Open Source Softwa...
def toggle_modal_sso(n1, n2, is_open): """ Callback for the modal (open/close) """ if n1 or n2: return not is_open return is_open
def get_new_board(dimension): """ Return a multidimensional list that represents an empty board (i.e. string with a space at every position). :param: dimension: integer representing the nxn dimension of your board. For example, if dimension is 3, you should return a 3x3 board :return: For ex...
def return_words(lst, word_set): """ Return combinations in that are words in word_set @type lst: [str] @type word_set: set(str) @rtype: [str] """ returned_list = [] for word in lst: if word in word_set or word.capitalize() in word_set: # Some words are capitalized ...
def era_minus(data, lg_era): """ERA- = ERA / lgERA * 100 :param :returns: """ return data["era"] / lg_era * 100
def fdr_cutoff(entries, cutoff): """ entries should be a list of dictionaries, each of the form {'score':, 'label':, 'peptide':} label is -1 for decoy, 1 for target """ #first, sort by score in descending order. sorted_entries = sorted(entries, key=lambda x: float(x['score']), reverse=True) ...
def count_disordered(arr, size): """Counts the number of items that are out of the expected order (monotonous increase) in the given list.""" counter = 0 state = { "expected": next(item for item in range(size) if item in arr), "checked": [] } def advance_state(): state...
def sanitize_win_path(winpath): """ Remove illegal path characters for windows """ intab = "<>:|?*" if isinstance(winpath, str): winpath = winpath.translate({ord(c): "_" for c in intab}) elif isinstance(winpath, str): outtab = "_" * len(intab) trantab = "".maketrans(intab...
def scalar_prod(n,a): """ This function takes a scalar, n, and multiplies it by every element in a vector. """ c = [n*a[0],n*a[1],n*a[2]] return(c)
def Redact(value, from_nth_char=5): """Redact value past the N-th character.""" return value[:from_nth_char] + '*' * (len(value) - from_nth_char)
def __material_cf(d): """ Fixed length data fields for computer files. """ return (d[0:4], d[4], d[5], d[6:8], d[8], d[9], d[10], d[11:])
def searchkit_aggs(aggs): """Format the aggs configuration to be used in React-SearchKit JS. :param aggs: A dictionary with Invenio facets configuration :returns: A list of dicts for React-SearchKit JS. """ return [ {"title": k.capitalize(), "aggName": k, "field": v["terms"]["field"]} ...
def and_(*children): """Select devices that match all of the given selectors. >>> and_(tag('sports'), tag('business')) {'and': [{'tag': 'sports'}, {'tag': 'business'}]} """ return {'and': [child for child in children]}
def factorial_recursive(n): """ >>> factorial_recursive(3) 6 >>> factorial_recursive(5) 120 >>> factorial_recursive(0) 1 >>> factorial_recursive(1) 1 """ if (n == 1 or n == 0): return 1 # Base Case elif (n > 1): return factorial_recursive(n-1)*n
def pixel2coord(x, y,a,b,xoff,yoff,d,e): """Returns global coordinates from pixel x, y coords""" xp = a * x + b * y + xoff yp = d * x + e * y + yoff return(xp, yp)
def reverse_complement_sequence(sequence, complementary_base_dict): """ Finds the reverse complement of a sequence. Parameters ---------- sequence : str The sequence to reverse complement. complementary_base_dict: dict A dict that maps bases (`str`) to their complementary bases ...
def time_delta(date1,date2): """ we have to write a tiny little script to calcualte time differences it's assumed that date1 is later than date2 """ f = lambda d: map(int,d.split(":")) h,m,s = (d[0] - d[1] for d in zip(f(date1), f(date2))) return h*60*60 + m*60 + s
def es_vocal(letra): """ (str of len == 1) bool Determina si una letra es vocal >>> es_vocal('a') True >>> es_vocal('x') False :param letra: str of len 1 representa un caracter :return: True si es vocal False de lo contrario """ return 1 == len(letra) and letra in 'aeiouAE...
def merge(*objs): """Recursively merges objects together.""" def _merge(a, b): if a is None: a = {} elif not isinstance(a, dict): return a else: a = dict(a) for key, value in b.items(): if isinstance(value, dict): va...
def optimize_frame_access(list_data, ra_n_times_slower=40): """ implemented by Simon Mandlik list_data should be array of nodes, must have .frame_ var returns list of tuples in format (data, ra_access [bool], stay_on_same_frame [bool]) :param list_data: :param ra_n_times_slower: :return: ...
def weighted_position_ranking(top, ranking, j): """ entrada: um ranking (da imagem q), o tamanho do top, e uma imagem j para ser obtido o peso saida: peso da imagem j """ position = -1 for i in range(top): if ranking[i] == j: position = i break if position ...
def get_responses(link): """Returns documented responses based on the @responds decorator. In case no documentation exists, the empty object is returned, instead of a default, which better represents that behavior not to be formally documented. """ if hasattr(link, '_responses'): retur...
def sum_all_to(num: int) -> int: """ Return the sum of all numbers up to and including the input number """ return num * (num + 1) // 2
def _compute_size_by_dict(indices, idx_dict): """Copied from _compute_size_by_dict in numpy/core/einsumfunc.py Computes the product of the elements in indices based on the dictionary idx_dict. Parameters ---------- indices : iterable Indices to base the product on. idx_dict : dicti...
def split_by_punctuation(text, puncs): """splits text by various punctionations e.g. hello, world => [hello, world] Args: text (str): text to split puncs (list): list of punctuations used to split text Returns: list: list with split text """ splits = text.split() sp...
def timestamp(x, year): """Add timestamp YYYY-MM-DD""" DD = "01" MM = str(x) ts = f"{year}-{MM}-{DD}" return ts
def calc_baseflow(satStore, k_sz): """ Calculate baseflow from the saturated zone Parameters ---------- satStore : int or float Storage in the saturated zone [mm] k_sz : float Runoff coefficient for the saturated zone [day^-1] Returns ------- baseflow : floa...
def pre_process(url): """ This method is used to remove the http and / from the url. :param url: The original url read from file. A String. like: https://www.shore-lines.co.uk/ :return: The processed url. A String. Example: www.shore-lines.co.uk """ # delet the http:// or https:// if url.sta...
def min_max_rescale(data, data_min, data_max): """Rescale the data to be within the range [new_min, new_max]""" return (data - data_min) / (data_max - data_min)
def escape_token(token, alphabet): """Escape the token and replace unknown chatacters with uni-code.""" token = token.replace(u'\\', u'\\\\').replace(u'_', u'\\u') escaped = [c if c in alphabet and c != u'\n' else r'\%d;' % ord(c) for c in token] return u''.join(escaped) + '_'
def attributes_pairs(attributes, prefix='', medfix=' - ', suffix=''): """ Make a list of unique pairs of attributes. Convenient to make the names of elements of the mixing matrix that is flattened. """ N = len(attributes) col = [] for i in range(N): for j in range(i+1): ...
def status_for_results(results): """Given a list of (output, ok) pairs, return the ok status for each pair """ return [result[-1] for result in results]
def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension """ filename_lower = filename.lower() return any(filename_lower.endswi...
def transformNull(requestContext, seriesList, default=0): """ Takes a metric or wild card seriesList and an optional value to transform Nulls to. Default is 0. This method compliments drawNullAsZero flag in graphical mode but also works in text only mode. Example: .. code-block:: none &target=transf...
def _open_flag_to_letter(open_flag): """This maps the flag used in a open()system call, to "R" or "W" if this is a read or write access. Used to analyse dependencies. """ if open_flag is None: return "R" if open_flag.startswith("????"): return "R" # ltrace just displays the integer...
def check_length(message): """Length of the subject line should not be more than 72 characters.""" splitted = message.splitlines() return len(splitted[0]) < 73
def pivotize(m): """Creates the pivoting matrix for m.""" n = len(m) ID = [[float(i == j) for i in range(n)] for j in range(n)] for j in range(n): row = max(range(j, n), key=lambda i: abs(m[i][j])) if j != row: ID[j], ID[row] = ID[row], ID[j] return ID
def is_mastercard(card_num): """Return true if first two numbers are 51, 52, 53, 54 or 55""" first_nums = card_num[:2] if int(first_nums) >= 51 and int(first_nums) <= 55: return True return False
def intersect(list1, list2): """ Intersect two list and get components that exists in both list. Args: list1 (list): input list. list2 (list): input list. Returns: list: intersected list. """ inter_list = list(set(list1).intersection(list2)) return(inter_list)
def valid_bins(num: int) -> bool: """Checks valid bin amount. Returns Boolean.""" return 2 <= num and num <= 1000
def iam_policy_to_dict(bindings): """ iam_policy_to_dict takes an iam policy binding in the GCP API format and converts it into a python dict so that it can be easily updated """ bindings_dict = dict() for binding in bindings: role = binding['role'] bindings_dict[role] = set(binding['members']) re...
def _update_ZS(stored_dict,this_dict) -> dict: """Updates stats dictionary with values from a new window result Parameters ---------- stored_dict:dict Dictionary to be updated with new data this_dict:dict New data with which to update stored_dict """ out_dict = stored_dict # loop over admin zones in this_d...
def compute_confidence_intervals(param_estimate, std_dev, critical_value): """Compute confidence intervals (ci). Note assumptions about the distributions apply. Parameters ---------- param_estimate: float Parameter estimate for which ci should be computed variance: float Varianc...
def map_diameter(c: int) -> float: """ Compute the diameter """ return 1. / 3. * (c + 1) * (c - 1)
def find_dups(mappings): """ Searches the mappings for any duplicates in the source or destination paths An error is created for each line that is not unique. :param mappings: dict {(file#,line#):("old_path","int_path","ext_path",...)} :return: errors list [(file#, line#, "Issue")] """ err...
def seq_format_from_suffix(suffix): """ Guesses input format from suffix >>> print(seq_format_from_suffix('gb')) genbank """ suffixes = {'fasta': ['fas','fasta','fa','fna'], 'genbank': ['gb','genbank'], 'embl': ['embl']} found = False for ke...
def check_colour_unique(board): """ (list) -> (bool) Function checks third condition, i.e. unique numbers in each colourful block >>> check_colour_unique(["**** ****","***1 ****","** 3****",\ "* 4 1****"," 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"]) True """ for j in range(...
def ERR_calc(ACC): """ Calculate Error rate. :param ACC: accuracy :type ACC: float :return: error rate as float """ try: return 1 - ACC except TypeError: return "None"
def remove(source: list, els=None): """ Remove elements. :param list source: Source list :param els: Element(s) to be removed :return: list """ r = [] if els is None: els = ['', None] elif not isinstance(els, list): els = [els] for el in source: if el no...
def getJunitTestRunnerClass(version): """ Get the correct junit test running class for the given junit version Parameters ---------- version : int The major version for junit Returns ------- str or None Returns str if `version` is either 3 or 4 Returns None otherwis...
def var_replace(vars, value): """Replace all instances of ${x} in value with the value of vars['x'].""" if value is None: return value for var, rep in vars.items(): if isinstance(rep, str): value = value.replace(f"${{{var}}}", rep) return value
def try_anafas_float(floatstr): """ Try converting a string into a float. Trims empty space and checks whether there is a decimal separator. When a decimal separator is unspecified, assumes two decimals separators by default (Anafas' default) dividing the resulting number by 100. """ try: num = float(...
def extract_value(error): """ Returns the value in the error message (as a string) If error is a ValueError, then the error is guaranteed to be after the final colon. Parameter error: The error object Precondition: error is a ValueError """ assert isinstance(error,ValueError), repr(err...
def eliminateExistingImages(conn, candidate, detections, detectionsWithImages): """ We'd really like to avoid requesting images that we already have. """ imagesToRequest = [] for row in detections: if '%d_%s_%d_%d' % (candidate, row['tdate'], row['imageid'], row['ipp_idet']) not in detecti...
def _repoowner_reponame(repo_str, username): """Returns a repo owner and repo name from a repo string (owner username(or org)/repo name) If only repo is given, username will be provided username who's using the API Arguments: repo_str str -- Full repo string (owner username(or org)/repo name) ...
def canonicalObjName(raw) : """Turn object name to identifier safe in external environment. """ # assume raw is a string return raw.lower().replace(" ", "_").replace(".", "_") # todo: conversion of non-ascii letters, changing non-letters to something...
def abstract_uri(abstract_id): """ generates abstract uri with id""" return "article/"+abstract_id
def return_number(number): """ Returns number as string. If number is None, string 'None' is returned instead. :param number: number to be converted as string :return: number converted to string and round to 2 positions after decimal point or 'None' in case of given None """ if number is None: ...
def fix_public_key(str_key): """eBay public keys are delivered in the format: -----BEGIN PUBLIC KEY-----key-----END PUBLIC KEY----- which is missing critical newlines around the key for ecdsa to process it. This adds those newlines and converts to bytes. """ return ( str_key ...
def convert_index(index_map, pos, M=None, is_start=True): """Working best with lcs_match(), convert the token index to origin text index Parameters ---------- index_map: list of int Typically, it is a map form origin indices to converted indices pos: int The origin index to be conve...
def c2f(celsius): """Convert temperature degree from C to F""" return (celsius * 9/5) + 32
def fit_header(header, value): """Convert headers to fit to our trees.""" if header == "content-type": value = value.split(";")[0] # Remove charset and stuff # All audio/video/javascript/image cts should behave the same # (this is not completly correct, e.g., unsupported cts, but should...
def _include_location_in_line(line, ip, location): """ :param line: Original line to place location string into. :type line: str :param ip: IP address to be replaced with location. :type ip: str :param location: IP address string with location data appended. :type location: str :return: ...
def __fmt_str_quotes(x): """Return a string or list of strings where the input string or list of strings have single quotes around strings""" if isinstance(x, (list, tuple)): return '{}'.format(x) if isinstance(x, str): return "'%s'" % x return str(x)
def gc_fib(x): """Calculate fibonacci numbers.""" if x == 0 or x == 1: return 1 return gc_fib(x - 1) + gc_fib(x - 2)
def modulate(v): """Modulates a value >>> modulate((1, (81740, None))) '110110000111011111100001001111110100110000' >>> modulate(0) '010' >>> modulate(1) '01100001' >>> modulate(-1) '10100001' >>> modulate(81740) '0111111000010011111101001100' """ if v is None: ...
def to_bytes(value, encoding='utf8'): """ cast string to bytes() like object, but for python2 support it's bytearray copy """ if isinstance(value, bytes): return value if isinstance(value, str): return value.encode(encoding) elif isinstance(value, bytearray): return bytes...
def filter_hosts(hosts, query): """ Simple filter to group hosts by some basic criteria We do short acronyms for site and to designate production/test/etc """ matches = set() for host in hosts: if query in host: matches.add(host) return matches
def consolidate_grades(grade_decimals, n_expect=None): """ Consolidate several grade_decimals into one. Arguments: grade_decimals (list): A list of floats between 0 and 1 n_expect (int): expected number of answers, defaults to length of grade_decimals Returns: float, either: ...
def children_to_list(node): """Organize children structure.""" if node['type'] == 'item' and len(node['children']) == 0: del node['children'] else: node['type'] = 'folder' node['children'] = list(node['children'].values()) node['children'].sort(key=lambda x: x['name']) ...
def fourPL(x, A, B, C, D): """4 parameter logistic function""" return ((A-D)/(1.0+((x/C)**(B))) + D)
def __check_list(data, varname=None, dtype=None): """ Checks if data is a list of dtype or turns a variable of dtype into a list Args: data: Data to check varname (str): Name of variable to check dtype (type) Data type to check data against ...
def get_location(my_map, location): """ Get the value of the current location """ (current_x, current_y) = location # Map repeats infinitely on the X axis return my_map[current_y][current_x % len(my_map[current_y])]
def preconvert_preinstanced_type(value, name, type_): """ Converts the given `value` to an acceptable value by the wrapper. Parameters ---------- value : `Any` The value to convert. name : `str` The name of the value. type_ : ``PreinstancedBase`` instance The pre...
def get_text_lines(text): """ Get all lines from a text storing each lines as a different item in a list :param text: str, text to get lines from :return: list<str> """ text = text.replace('\r', '') lines = text.split('\n') return lines
def reset_light(_): """Clean the light waveform plot when changing event""" return {"display": "none"}
def get_progressive_min(array): """Returns an array representing the closest to zero so far in the given array. Specifically, output value at index i will equal `min(abs(array[:i+1]))`. Parameters ---------- array : list of :obj:`~numbers.Number` or :obj:`numpy.array` Input...