content
stringlengths
42
6.51k
def resolve_metadata_id(title, metadata): """ Resolves an ID of the specified metadata by its ``title``. :param title: Metadata title :type title: str :param metadata: |data-hub|_ metadata list :type metadata: TypedDict('Metadata', {'name': str, 'id': str}) :returns: |data-hub|_ uuid for t...
def uint_to_list(dec_val, num_bits=8): """ Converts hex string to list of 1's and 0's. """ format_str = '0{}b'.format(num_bits) ret_val = format(dec_val, format_str) temp = [int(bit) for bit in ret_val] # str_val in ret_val for bit in str_val] return temp
def toindex(col, row): """ Calculates the index number from the Excel column name. Examples: >>> from sphinxcontrib import exceltable >>> exceltable.toindex('A', 1) (0, 0) >>> exceltable.toindex('B', 10) (1, 9) >>> exceltable.toindex('Z', 2) (25, 1) >>> exceltable.toindex('AA', 27...
def nest_dict(d, prefixes, delim="_"): """Go from {prefix_key: value} to {prefix: {key: value}}.""" nested = {} for k, v in d.items(): for prefix in prefixes: if k.startswith(prefix + delim): if prefix not in nested: nested[prefix] = {} nested[prefix][k.split(delim, 1)[1]] = v ...
def _encode(s): """Creates valid JSON strings that can be decoded by JS in th browser""" return str(s).replace('"', '@DBLQ').replace('<', '@LT').replace('>', '@GT').replace('/', '@SL')
def extended_euclidean_algorithm(a, b): """Extended Euclidean algorithm Returns r, s, t such that r = s*a + t*b and r is gcd(a, b) See <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm> """ r0, r1 = a, b s0, s1 = 1, 0 t0, t1 = 0, 1 while r1 != 0: q = r0 // r1 ...
def find_within_range(repr1, repr2, repr_diff, vertex_set, angle_range_less_180, equal_repr_allowed): """ filters out all vertices whose representation lies within the range between the two given angle representations which range ('clockwise' or 'counter-clockwise') should be checked is determined by:...
def determine_parllelism(num_tiles): """ Try to stay at a maximum of 1500 tiles per partition; But don't go over 128 partitions. Also, don't go below the default of 8 """ num_partitions = max(min(num_tiles // 1500, 128), 8) return num_partitions
def convert_to_list(x): """ "a" --> ["a"] ["a","b"] --> ["a","b"] """ if type(x) != list: return [x] else: return x
def effective_axial_force(H, delta_P, A_i, v, A_s, E, alpha, delta_T): # pragma: no cover """ -> Number [N] Paragraph 411, Equation (4.12) Determine the effective axial force of a totally restrained pipe in the linear elastic stress range """ pressure_term = delta_P * A_i * (1 - 2 * v) ...
def first(it): """ returns the first element in an iterable Returns the first element found in a provided iterable no matter if it is a list or generator type. If no element is found, this call will return a `None` value. Args: it: an iterable type Returns: the first eleme...
def get_run_id_keys(json_results, run_id_list): """This function finds the key used in the json_results dictionary for a given run ID. These dictionary keys are the files names and there are potentially many keys that are associated with a run ID. For the intended purposes of this function (metadata com...
def read_presentation_type(sequence): """ This function extracts the presentation_type variable from a sequence dictionary. """ if sequence["alternatives"][0] in [0, 1]: return "alternatives" elif sequence["attributes"][0] in ["p", "m"]: return "attributes"
def _check_get_or_return(py_name, call): """ Given a call signature extracted by _extract_calls(), figure out how to deal with the outcome of the function call. Valid options are 'return' to just return it, 'check' to just call the Bifrost _check() function, or 'get' to call the Bifrost _get() fun...
def build_string(message, *values, sep = ""): """ build a string with arbitrary arguments. Positional Args: message: original string to build on. values: individual arguments to be added to the string. Keyword only Args: sep: how to divide the parts of the string if you want. (ie. ',' or "/") """ if not va...
def fill_read_resp_body(body): """ build resource from response body :param body: response body from List or Read :return: resource object in read response format """ return { "scaling_group_id": body.get("scaling_group_id"), "scaling_group_status": body.get("scaling_group_statu...
def _get_number_of_variables(tensor_shape): """TBD.""" if not len(tensor_shape): return 0 total_vars = 1 for d in tensor_shape: total_vars *= d return total_vars
def _norm_index(dim, index, start, stop): """Return an index normalized to an farray start index.""" length = stop - start if -length <= index < 0: normindex = index + length elif start <= index < stop: normindex = index - start else: fstr = "expected dim {} index in range [{...
def scale_rgb(rgb): """Convert RGB to hex""" return tuple([i / 255.5 for i in rgb])
def SelectDefaultBrowser(possible_browsers): """Return the newest possible browser.""" if not possible_browsers: return None return max(possible_browsers, key=lambda b: b.last_modification_time())
def sum_all(seq): """ takes a list seq of unknown depth and returns the sum of all values in list """ if not seq: return 0 elif isinstance(seq[0], list): return sum_all(seq[0]) + sum_all(seq[1:]) else: return seq[0] + sum_all(seq[1:])
def false_positive(y_true, y_pred): """ Function to calculate False Positives :param y_true: list of true values :param y_pred: list of predicted values :return: number of false positives """ # initialize fp = 0 for yt, yp in zip(y_true, y_pred): if yt == 0 and yp == 1: ...
def get_seamus_id_from_url(url): """ gets seamus ID from URL """ if url.startswith('http://www.npr.org') or url.startswith('http://npr.org'): url_parts = url.split('/') id = url_parts[-2] if id.isdigit(): return id return None
def _make_bold_stat_signif(value, sig_level=0.05): """Make bold the lowest or highest value(s).""" val = "%.1e" % value val = "\\textbf{%s}" % val if value <= sig_level else val return val
def replace_root_with_path(run_command, path): """Replaces '"root/' with '"path_to_root/' and 'root/' with '"path_to_root"/. """ len_path = len(path) i = 0 k = 0 l = 0 while k != -1: l += 1 j = run_command[i:].find('"root/') k = run_command[i:].find('root/') ...
def get_text(name): """returns some text""" return "Hello "+name
def parse_notification_template(template): """ Template looks like this: email:deepak@ishafoundation.org email:arunkumar.p@ishafoundation.org email:ipc.np.accounts@ishafoundation.org email:ipc.itsupport@ishafoundation.org center:Center Treasurer zone:RCO Acco...
def get_class_prob(predictions_dict): """Get true and predicted targets from predictions_dict. Parameters ---------- predictions_dict : dict Dict of model predictions. Must contain "target_true" and "target_pred" keys with corresponding dict values of the form class_label : probability....
def _fixslash(s): """Fix windowslike filename to unixlike - (#ifdef WINDOWS)""" s = s.replace("\\", "/") if s[0] != "/" and s[1] == ":": s = s[2:] # @@@ Hack when drive letter present return s
def memory_in_bytes(memory_amount, unit): """ Converts an amount of memory (in given units) to bytes :param float memory_amount: An amount of memory :param str unit: The units ('KB', 'MB', 'GB', 'TB', 'PB') :return: Amount of memory in bytes """ if memory_amount is None: return memo...
def GetExtension(wildcard: str) -> str: """Get the extension from the wildcard. :param wildcard: Please refer to wxPython (https://docs.wxpython.org/wx.FileDialog.html?highlight=filedialog#wx.FileDialog) for details. :type wildcard: str :rtype: str """ wildcard = wildcard[wildcard.rfind('|') + ...
def getCountsAndAverages(IDandRatingsTuple): """ Calculate average rating Args: IDandRatingsTuple: a single tuple of (MovieID, (Rating1, Rating2, Rating3, ...)) Returns: tuple: a tuple of (MovieID, (number of ratings, averageRating)) """ movie = IDandRatingsTuple[0] ratings = IDa...
def project_with_revision_exists(project_name, project_revision, working_dir): """Check if a Quartus project with the given name and revision exists. Parameters ---------- project_name : str Name of the Quartus project project_revision : str Name of the project revision working_...
def _filter_import(origin_import_list, working_import_list): """ Create a new set with elements present origin_list or working_list but not on both, this helps to filter classes that could have same name but different modules. """ difference = origin_import_list.symmetric_difference(working_imp...
def mem_binary_search(arr, time, return_ind=False): """ Performs binary search on array, but assumes that the array is filled with tuples, where the first element is the value and the second is the time. We're sorting utilizing the time field and returning the value at the specific time. Args: ...
def deltawords(num, arg): """An adverb to come after the word 'improved' or 'slipped'""" delta = abs(num - arg) # We only pick out changes over 10%; over 30% in 9 months is unheard of. if delta == 0: word = "not at all" elif delta < 10: word = "slightly" elif delta < 20: ...
def _h3_col(h3_lvl): """Make it easy and reporducable to create a h3 column""" return f'h3_{h3_lvl:02d}'
def get_restart_action(restart_action_list): """Returns the highest-weighted restart action of those in the list""" restart_actions = [ 'None', 'RequireLogout', 'RecommendRestart', 'RequireRestart'] highest_action_index = 0 for action in restart_action_list: try: highest_acti...
def parse_hits(query, hit): """ helper to parse and filter given hits """ suspect = str(query.get('num')) not in hit.get('title') return {'suspect': suspect}
def is_prime(n): """ Return whether the input n is prime number or not Parameters ---------- n (int): input number Return ------ result (bool): True if prime """ if not isinstance(n, int) or n < 2: return False for i in range(2, n): if n % i == 0: retu...
def parse_result_line(line): """Take a line consisting of a constituency name and vote count, party id pairs all separated by commas and return the constituency name and a list of results as a pair. The results list consists of vote-count party name pairs. To handle constituencies whose names include a...
def saveRawSerpApiAsDict(serpRawResult): """ Called in getGoogleScholarCitation() concatenate all the results into one JSON object """ extractedResult = {} if('organic_results' in serpRawResult.keys()): lengthResult = len(serpRawResult['organic_results']) if(lengthResult == 1): ...
def KeyValueToDict(pair): """Converts an iterable object of key=value pairs to dictionary.""" d = dict() for kv in pair: (k, v) = kv.split('=', 1) d[k] = v return d
def call_plugin(plugin, f, *args, **kwargs): """Calls function f from plugin, returns None if plugin does not implement f.""" try: getattr(plugin, f) except AttributeError: return None if kwargs: getattr(plugin, f)( *args, **kwargs ) else: ...
def chunks(l, n): """Split a list into chunks of size n""" return [l[i:i+n] for i in range(0, len(l), n)]
def main(args=None): """ Run the main program. This function is executed when you type `pythonscientificcompcourse` or `python -m pythonscientificcompcourse`. Arguments: args: Arguments passed from the command line. Returns: An exit code. """ print("Hello Worl...
def get_local_bin(home): """ Returns the local bin path of the User """ return f"{home}/.local/bin"
def get_sub_indices(seq, sub_seq): """ Compute indices of where the first element of sub sequence locates in the sequence. :param seq: a sequence(list, str, tuple and so on) like: ["a", "b", "c", "b", "c"] :param sub_seq: ["b", "c"] :return: a list of indices, where the first ...
def get_task_type(code, decorator_filter, default): """ Retrieves the type of the task based on the decorators stack. :param code: Tuple which contains the task code to analyse and the number of lines of the code. :param decorator_filter: Typle which contains the filtering decorators. The one used d...
def pad(str_float_value): """ Pad value with zeroes to 8 digits after dot """ return "%.8f"%float(str_float_value)
def info_fn(book_id): """ Construct filename for info.xml file. Args: book_id (int/str): ID of the book, without special characters. Returns: str: Filename in format ``info_BOOKID.xml``. """ return "info_%s.xml" % str(book_id) # return "info.xml"
def tostr(value): """Cast value to str except when None value[in] Value to be cast to str Returns value as str instance or None. """ return None if value is None else str(value)
def handle_connection_error(err): """ connection exception handler """ return 'docker host not found: ' + str(err), 500
def cal_percision(label_list, classify_res): """ calculate the percision""" assert(len(label_list) == len(classify_res)) true_positive_count = 0.0 false_positive_count = 0.0 for i in range(len(label_list)): if classify_res[i] == True: if label_list[i] == True: tru...
def rgb2hex(r, g, b): """RGB to hexadecimal.""" return "#%02x%02x%02x" % (r, g, b)
def data_smooth_get_std(kev, k0=3.458, k1=0.28, k2=0): """Returns the standard deviation for smoothing at kev. Assumes default parameters on data_smooth. """ # 0.5 would be 99% confidence, want that divided by 3. return 0.2 * (k0 + k1 * kev ** 0.5 + k2 * kev)
def zf(s): """ Number digit with a '0' """ s=str(s) if len(s)==1: return '0'+s; else: return s;
def _get_shader_stage_string(shader_stage): """Returns the shader stage string from the given shader stage.""" if (shader_stage == "vertex" or shader_stage == "fragment" or shader_stage == "tesscontrol" or shader_stage == "tesseval" or shader_stage == "geometry" or shader_stage == "compu...
def vis2(n): # DONE """ O .O ..O OO ..O OOO Number of Os: 1 3 5""" result = [] for i in range(n - 1): result.append(('.' * (n - 1) + 'O') + '\n') result.append('O' * n) return ''.join(result).rstrip()
def get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval): """ Adjust the evaluation interval adaptively. If cur_dev_size <= thres_dev_size, return base_interval; else, linearly increase the interval (round to integer times of base interval). """ if cur_dev_size <= thres_dev_size: ...
def func_a_kwargs(a=2, **kwargs): """func. Parameters ---------- a: int, optional kwargs: dict Returns ------- a: int kwargs: dict """ return None, None, a, None, None, None, None, kwargs
def get_region_id(region): """Return Pure region ID from region code. Example: - Hong Kong -> #1 - Singapore -> #2 - Shanghai/CN -> #4 """ regions = { 'HK': 1, 'SG': 2, 'CN': 4, } assert region in regions, ( 'Region "%s" does not exist.' %...
def receptive_field_size( total_layers, num_cycles, kernel_size, dilation=lambda x: 2 ** x ): """Compute receptive field size of WaveNet Args: total_layers (int): total layers num_cycles (int): cycles kernel_size (int): kernel size dilation (lambda): lambda to compute dilati...
def tail(_b, _x): """Determine the number of trailing b's in vector x. Parameters ---------- b: int Integer for counting at tail of vector. x: array Vector of integers. Returns ------- tail: int Number of trailing b's in x. """ # Initialize counter ...
def _GetDataFilesForTestSuite(test_suite_basename): """Returns a list of data files/dirs needed by the test suite. Args: test_suite_basename: The test suite basename for which to return file paths. Returns: A list of test file and directory paths. """ test_files = [] if test_suite_basename in ['Ch...
def mpd_command_provider(cls): """Decorator hooking up registered MPD commands to concrete client implementation. A class using this decorator must inherit from ``MPDClientBase`` and implement it's ``add_command`` function. """ def collect(cls, callbacks=dict()): """Collect MPD command ...
def time_minutes_to_string(time: int) -> str: """ Converts time from an integer number of minutes after 00:00 to string-format :param time: The number of minutes between 'time' and 00:00 :return: A string of the form "HH:MM" representing a time of day """ return "{0:0=2d}".format(int(time/60)) +...
def degree_of_operating_leverage(quantity, variable_cost, price, fixed_cost): """ Summary: Calculate the degree of operating leverage. PARA quantity: Quantity of units sold. PARA type: int PARA variable_cost: The variable cost per unit. PARA type: float PARA fixed_cost: Total ...
def print_train_time(start, end, device=None): """Prints difference between start and end time. Args: start (float): Start time of computation (preferred in timeit format). end (float): End time of computation. device ([type], optional): Device that compute is running on. Defaults to N...
def verror_msg(pos: int, prog: str, msg: str) -> str: """Returns the formatted error message for the given paramters. Args: pos: Thosition of where the error is. prog: The program where the error is. msg: The error message. """ result = f"{prog}\n" result += " " * pos r...
def norm_hours(h): """ """ if (h < 0) : return h+24,1 elif (h > 24) : return h-24,1 else : return h,0
def count_errors(item): """Count process group errors.""" count = 0 if item: for x in item: if x["level"] == "ERROR": count = count + 1 return count
def normalize(value, min, max): """ funtion to normalize ppmi scores :param value: :param min: :param max: :return: """ norm_val = (float(value) - float(min))/(float(max) - float(min)) return norm_val
def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ # First, we put the new angle in the range ]-360...
def pack(my_str): """ implement the function packed the string """ # Empty list of tuple packed_list = [] str_len = len(my_str) count = 1 for i in range(str_len): # Count thr character if current and next character is same if i < str_len - 1 and my_str[i] == my_str[i + 1]...
def cal_multiplier_and_shift(scale): """ In order to use gemmlowp, we need to use gemmlowp-like transform :param scale: :return: multiplier, shift """ assert scale > 0, "scale should > 0, but get %s" % scale assert scale < 1, "scale should < 1, but get %s" % scale multiplier = scale ...
def pascals_triangle(N): """Prints the elements of the Pascal Triangle >>> p = pascals_triangle(5) >>> print_pascals_triangle(p) 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 """ a = [] for i in range(N): a.append([]) a[i].append(1) for j in range(1, i): a...
def partition_rec(n, d, depth=0): """ Recursion for generating partitions of integer d of length n Parameters ---------- n : int Length of partition vector. d : int Maximum sum of the vector. depth : int, optional Depth of recursion. The default is 0. Returns ...
def minimum(a, b): """ return the minimum of two arguments :param a: :param b: :return: maximmu """ if a < b: return a return b
def taglist2str(taglist, filter_tags): """ eg taglist2str([{'Key':'app', 'Value':'isitfit'}], 'boo') returns "" taglist2str([{'Key':'app', 'Value':'isitfit'}], 'is') returns "app = isitfit" """ if filter_tags is not None: # filter the tag list for only those containing the filter-tags string f_...
def get_content_test_data(include_id=True, false_id=False, relative_url=False): """This function returns the test data to use in the various test functions. .. versionadded:: 2.4.0 :param include_id: Determines if the Content ID should be returned (``True`` by default) :type include_id: bool :para...
def subset_meQTL(meQTL, gene_name): """ """ try: index = meQTL.gene == gene_name subset = meQTL.ix[index, :] except AttributeError: # Case where eQTL matrix is already 1 gene subset = meQTL return(subset)
def clusters_to_labels(clusters): """ :param clusters: List of lists, each sublist contains doc ids in that cluster :return labels: Dict of [doc_id, cluster_label] where cluster_label are assigned from positive ints starting at 1 """ labels = dict() for label, cluster in enumerate(clusters): ...
def make_coffee(*options): """makes coffee Args: options: 0 or more extra ingredients """ #Get ingredients ingredients = ['coffee', 'hot water'] if options: for option in options: ingredients.append(option) #print the number of items in ingredients print...
def is_true(s): """Case insensitive string parsing helper. Return True for true (case insensitive matching), False otherwise.""" return type(s) == str and s.lower() == "true"
def serial_ppmap(func, fixed_arg, var_arg_iter): """A serial implementation of the "partially-pickling map" function returned by the :meth:`ParallelHelper.get_ppmap` interface. Its arguments are: *func* A callable taking three arguments and returning a Pickle-able value. *fixed_arg* Any val...
def unique(s): """returns the unique values of a list. Example Usage: >>> x=[1,1,2,3,4,4,5] >>> unique(x) [1, 2, 3, 4, 5] """ n = len(s) if n == 0: return [] u = {} for x in s: u[x] = 1 return u.keys()
def ip_to_binary(ip): """ Convert an IPv4 address to a string containing the binary conversion of the IP address. Args: ip - The ip address to convert """ return "".join([bin(int(x)+256)[3:] for x in ip.split('.')])
def normalize_meaning(source_string): """Escape all HTML tags if any""" flag = 0 index = 0 # Trash is a list containing all the html tags found in the source string trash = [] for c in source_string: if c == '<': # Flag the start of the html tag flag = index ...
def convert_boolean_out(value: bytes) -> bool: """ If the value is from a boolean column, convert it to a bool value. """ _value = value.decode("utf8") return _value == "1"
def factorize(n): """Return prime factorization of n as sorted list""" d = 2 factors = [] while n > 1: if n % d == 0: factors.append(d) n = n/d else: d = d + 1 return factors
def rate_black_pixel_ratio ( ratio: int, thres_1: int = 20, thres_2: int = 50 ) -> int: """ Evaluates the given black-pixel-ratio and returns the detected marking. Args: ratio (int): the ratio of black pixels compared to total pixels thres_1 (int): ...
def create_url(url, data): """ Method which creates new url from base url :param url: base url :param data: data to append to base url :return: new url """ return url + "/" + str(data)
def do(ARGV): """Allow to check whether the exception handlers are all in place. """ if len(ARGV) != 3: return False elif ARGV[1] != "<<TEST:Exceptions/function>>" \ and ARGV[1] != "<<TEST:Exceptions/on-import>>": return False if len(ARGV) < 3: return False exception = A...
def _renameClasses(classes, prefix): """ Replace class IDs with nice strings. """ renameMap = {} for classID, glyphList in classes.items(): if len(glyphList) == 0: groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2]) elif len(glyphList) ...
def _GetMetaDict(items, key, value): """Gets the dict in items that contains key==value. A metadict object is a list of dicts of the form: [ {key: value-1, ...}, {key: value-2, ...}, ... ] Args: items: A list of dicts. key: The dict key name. value: The dict key value. R...
def aquifer_demand(aquifer_area_sqkm, num_correlated_wells): """ Calculates the aquifer demand """ if aquifer_area_sqkm is None or num_correlated_wells == 0: return 'L' num_wells_per_km_sq = num_correlated_wells / aquifer_area_sqkm if num_wells_per_km_sq <= 4: return 'L' eli...
def change_polymer(file): """ """ i = 0 while True: try: capital = file[i].isupper() if capital: if file[i].lower() == file[i+1]: del file[i:i+2] i -= 1 else: i += 1 ...
def get_dict_value(dict_var, key, default_value=None, add_if_not_in_map=True): """ This is like dict.get function except it checks that the dict_var is a dict in addition to dict.get. @param dict_var: the variable that is either a dict or something else @param key: key to look up in dict @param ...
def slice_text(text, eos_token="<s>", sos_token="</s>"): """Slices text from <s> to </s>, not including these special tokens. """ eos_index = text.find(eos_token) text = text[:eos_index] if eos_index > -1 else text sos_index = text.find(sos_token) text = text[sos_index+len(so...