content
stringlengths
42
6.51k
def is_url(url: str) -> bool: """Determine if this is a tweet URL.""" url = url.lower() return "twitter.com/" in url and "/status/" in url
def is_special_file(path): """ is_special_file returns true if the file path is a special/virtual file. @type path: str @rtype: boolean """ return "::" in path.rpartition("/")[2]
def create_bom(merged_manifest, approved_list, denied_list): """Creates a BOM If a BOM package is approved or denied, the 'copyright_notice', 'interaction_types', and 'resolution' will be copied over. Otherwise, these attributes will be added to the BOM with empty values. Args: merged_mani...
def getNetworkResources(networkDict): """ Get Network Resources """ return networkDict['NetworkResources']
def add_multiple(*arrs): """ this could be seen as np.add(x,y) with unlimited number of arguments """ if len(arrs) > 1: return add_multiple(*arrs[1:]) + arrs[0] else: return arrs[0]
def sumOutputSerializeSizes(outputs): # outputs []*wire.TxOut) (serializeSize int) { """ sumOutputSerializeSizes sums up the serialized size of the supplied outputs. Args: outputs list(TxOut): Transaction outputs. Returns: int: Estimated size of the byte-encoded transaction outputs. ...
def coq_scope(s): """Coq: create scope s Arguments: - `s`: """ return "Open Scope {0!s}.\n".format(s)
def _ensure_wrappability(fn): """Make sure `fn` can be wrapped cleanly by functools.wraps. Adapted from gin-config/gin/config.py """ # Handle "builtin_function_or_method", "wrapped_descriptor", and # "method-wrapper" types. unwrappable_types = (type(sum), type(object.__init__), ...
def list_to_dict(lst, separator='='): """ This converts a list of ["k=v"] to a dictionary {k: v}. """ kvs = [i.split(separator) for i in lst] return {k: v for k, v in kvs}
def get_mean(a, b): """ Find the mid point of two points Inputs: - a, b: floats Outputs: - the coordinate of the mid point: float """ return (a + b) / 2
def as_dms(f_degrees): """Given a floating-point number of degrees, translates it to degrees, minutes, and seconds.""" degrees = int(f_degrees) degrees_fraction = f_degrees - degrees f_minutes = degrees_fraction * 60 minutes = int(f_minutes) minutes_fraction = f_minutes - minutes f_secon...
def select_items_by_bits(lst, i): """ Selects items from lst indexed by the bits in i. :param lst: A list. :param i: A non-negative integer whose most significant bit is at a position lesser than len(lst). :return: A list containing all lst[k] where (i & (1 << k)) == 1. """ result = [] ...
def find_in_data(ohw_data, name): """ Search in the OpenHardwareMonitor data for a specific node, recursively :param ohw_data: OpenHardwareMonitor data object :param name: Name of node to search for :returns: The found node, or -1 if no node was found """ if ohw_data == ...
def str_clean(input: str, **kwargs) -> str: """ Cleans and encodes string for template replacemnt Keyword Arguments: replace_dual (bool, optional): Replace ``::`` with ``.`` Default ``True`` """ _replace_dual = bool(kwargs.get('replace_dual', True)) result = input if _replace_dual: ...
def check_movie_in_tweet(movie, full_text): """ Verifica se um filme foi mencionado no tweet. """ if movie['title'] in full_text: if (movie['words_count'] <= 2) and (movie['score'] < 10.0): return False if (movie['words_count'] <= 3) and (movie['score'] < 9): return False...
def extract_encoding_and_rate_from_wav_header(wav_header): """ Attempt to extract encoding, sample rate from possible WAV header. Args: wav_header (bytes): Possible WAV file header. Returns: Union[bool, str]: False or truthy value, which may be the encoding name...
def get_slash_type(path)-> str : """ Get the slash type of a path. Returns: - string """ if '\\' in path: return '\\' else: return '/'
def get_loopbacks(yaml): """Return a list of all loopbacks.""" ret = [] if "loopbacks" in yaml: for ifname, _iface in yaml["loopbacks"].items(): ret.append(ifname) return ret
def sum_even_fibonacci_numbers(limit): """ Finds the sum of the even-valued terms in the Fibonacci sequence :param limit: :return: """ a, b = 1, 2 total = 0 while a < limit: if a % 2 == 0: total += a tmp = a a = b b = a + tmp return total
def get_display_text_for_event(event): """ Takes an event from a collection exercise and returns a version of it that can be displayed to the user. If the string isn't found in the map, it just returns the string the function was given. :param event: A name of an event from a collection exercise :t...
def fmttime(time): """ Output time elapsed in seconds into a sensible format. INPUTS time : input time elapsed [seconds] """ sc = time % 60. time = (time-sc)/60. result = "{:}s".format(sc) if not time: return result mn = int(time % 60.) time = (time-mn)/...
def cycle_list_next(vlist, current_val): """Return the next element of *current_val* from *vlist*, if approaching the list boundary, starts from begining. """ return vlist[(vlist.index(current_val) + 1) % len(vlist)]
def calculate_sleep_factor(scans_per_read, ljm_scan_backlog): """Calculates how much sleep should be done based on how far behind stream is. @para scans_per_read: The number of scans returned by a eStreamRead call @type scans_per_read: int @para ljm_scan_backlog: The number of backlogged scans in ...
def mapl(function, array): """ Map a function to an array (equivalent to python2 map) :param function: Function to be mapped :param array: List of values :return: List of returns values f = function array = [x0, x1, x2, ... xn] [f(x0), f(x1), f(x2) ... f(xn)] = mapl(f, a...
def average_index(n1, n2, v1=None, v2=None, vr=None): """Compute volume weighted average refractive index Args: n1, n2 (float/ndarray): refractive index of material 1 and 2 v1, v2 (float): volume of materials 1 and 2 vr (float): volume ratio of v1/(v1+v2) used instead of v1 and v2 ""...
def get_app_icon_name(app_id: str) -> str: """Builds the corresponding app icon name from app id.""" return f"icon_{app_id}"
def count_total(P, x, y): """ This function calculates suffix sums, which are the totals of the k last values. Args: P: an array contains the consecutive sums of the first n elements x: an integer, whih is number of elements of a prefix-sum array y: an integer, whih is number of elements of a pr...
def record_mandatory_paths(database, include_path_candidate, header): """Add mandatory path set into include path candidates database. Mandatory include path is detected if the source file location is different than location of included header file location""" if include_path_candidate not in database[h...
def my_cmp(a, b): """ Python 3 replacement for Python 2 builtin cmp """ ret_val = False if a is not None and b is not None: try: ret_val = (a > b) - (a < b) except ValueError as e: print (f"ValueError: {e}") except TypeError as e: print (f...
def suppress_classes(label, list_to_suppress): """ returns 'O' if class in list """ if label in list_to_suppress: return 'O' return label
def annotated_frames(scribbles_data): """ Finds which frames have a scribble. # Arguments scribbles_data (dict): Scribble in the default format. # Returns list: Number of the frames that contain at least one scribble. """ scribbles = scribbles_data['scribbles'] frames_list = [i...
def module_to_str(module): """Convert a Python module to a task name.""" return module.__name__.split(".")[-1]
def calculate_p_EE(R_EE, p_total, N_total, N_in): """ Calculates the p_EE for a clustered network from a given R_EE and the total connection probability :param R_EE: Factor of connection probability inside a cluster per probability of connection outside cluster :param p_total: overall connection probabi...
def iterable_to_string(iterable, separator="\n"): """ Transforms the `iterable` to a string by getting the string value of each item and joining them with `sep`. :param iterable: the iterable :type iterable: Any :param separator: the separator :type separator: str :return: the joined st...
def get_mask_from_alignment(al): """ For a single alignment, return the mask as a string of '+' and '-'s. """ alignment_str = str(al).split("\n")[1] return alignment_str.replace("|", "+")
def flipcoords(xcoord, ycoord, axis): """ Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip acr...
def getSight(m): """Retourn la longueur de la ligne de mire d'un monstre""" return m["sight"]
def parseChoices(optString): """ The option string is basically our "recipe". Example: "time=Q4 2014 dimensions=[time,age,industry] geo="K000000001 obs=obs_col" """ time = None # assumed. geo = None # ... obs = None # . dimensions = [] # Look for opti...
def simpleMsgResp(content: str) -> dict: """ Simple def to put content in following dict: { message: content, len: len(content) } :param content: str - the message to be inserted :return: dict containing the message and it's length :rtype: dict """ return {'message': ...
def extract_annotations(node, category=None): """Extract all annotations that are marked up with the given mark category.""" result = [] if 'marks' in node: for mark in node['marks']: if mark['type'] == 'annotation' and (category is None or mark['attrs']['category'] == category): ...
def recurring(strg): """O(n) solution.""" for idx, c in enumerate(strg): if c in strg[idx + 1:]: return c return None
def _static_hasattr(value, attr): """Returns whether this value has the given attribute, ignoring __getattr__ overrides.""" try: object.__getattribute__(value, attr) except AttributeError: return False else: return True
def bytearray_to_hexstring(ba): """Ugly workaround to create BitVector.""" ba_hex_str = '' for b in ba: hex_digit = hex(b)[2:] # 0x0 ... 0xff if len(hex_digit) == 1: hex_digit = '0' + hex_digit # log.debug('bytearray_to_hexstring: {}, {}'.format(b, hex_digit)) ...
def _all_the_same(items): """ Checks whether all values in a list are the same. """ return all(items[0] == item for item in items)
def sanitize_dict(d): """Remove all keys that have none values from a dict.""" rv = {} for key, value in d.items(): if not value: continue if key == "synonyms": value = sorted(value) rv[key] = value return rv
def merge(left, right): """this is used for merging two halves """ # print('inside Merge ') result = []; leftIndex = 0; rightIndex = 0; while leftIndex < len(left) and rightIndex < len(right): if left[leftIndex] < right[rightIndex]: result.append(left[leftIndex]) ...
def rtd10(raw_value): """Convert platinum RTD output to degrees C. The conversion is simply ``0.1 * raw_value``. """ return (float(raw_value) / 10.0, "degC")
def host_match(c_host, bw_host): """ Check if a cookie `c_host` matches a bw-list `bw_host`. """ if c_host == bw_host: return True elif bw_host.startswith('.') and c_host.endswith(bw_host): return True return False
def human_format(num): """ :param num: A number to print in a nice readable way. :return: A string representing this number in a readable way (e.g. 1000 --> 1K). """ magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 return '%.2f%s' % (num, ['', 'K', 'M', 'G...
def task_wrapper(args): """ Helper for multiprocessing.Pool.imap_unordered. The first argument is a function to call. Rest of the arguments are passed to the function. """ func = args[0] func_args = args[1:] ret = func(*func_args) if ret is None: return True else: ...
def get_average_mos(solution, ignore_non_served=False): """Returns the average MOS of a solution. """ smos = 0 nserved = 0 for u in solution["users"]: if "mos" in u: smos += u["mos"] nserved += 1 if ignore_non_served: # only take into account users that get some video return smos/nse...
def get_participant(encounter): """ get participant from encounter :param practitioner: :return: """ if "participant" in encounter: id = "" if 'individual' in encounter['participant'][0]: id_split = encounter['participant'][0]['individual']['reference'].split("/") ...
def check_clause(clause, implication_graph): """Check the clause If the clause infers contradiction, return False If all literals but one are assigned value 0, use unit resolution, return the valuable and it's assignment Else, we can't get anything useful from this clause,...
def _get_topic_memcache_key(topic_id, version=None): """Returns a memcache key for the topic. Args: topic_id: str. ID of the topic. version: int. The version of the topic. Returns: str. The memcache key of the topic. """ if version: return 'topic-version:%s:%s' % (t...
def get_maximum_overview_level(width, height, minsize=256): """ Calculate the maximum overview level of a dataset at which the smallest overview is smaller than `minsize`. Attributes ---------- width : int Width of the dataset. height : int Height of the dataset. minsize...
def cball(callback, iterable): """Return True if all elements of the iterable are true (or if the iterable is empty) :param callback: callable :param iterable: Sequence :returns: bool """ for v in iterable: if not callback(v): return False return True
def isInt(x): """ Returns True, if x is an integer. >>> isInt(1) True >>> isInt('Hello') False >>> isInt(3.14) False """ return isinstance(x, int)
def get_sum(limit = 1000): """Gets the sum of the multiples of 3 or 5""" sum = 0 for n in range(1, limit): if n % 3 == 0 or n % 5 == 0: sum += n return sum
def field2DME(data, data_catelog): """Converts common field names with dme field names. Returns a dictionary of converted names suitable for archiving. """ converted = {} for collection_type, metadict in data.items(): if collection_type not in converted: converted[collection_typ...
def sub(value, arg): """Subtracts arg from value""" return (value) - (arg)
def extract_turls(indata): """ Extract TURLs from indata for direct i/o files. :param indata: list of FileSpec. :return: comma-separated list of turls (string). """ # turls = "" # for filespc in indata: # if filespc.status == 'remote_io': # turls += filespc.turl if not turls else "...
def order_match(str1, str2): """order_match""" l1 = len(str1) l2 = len(str2) i = 0 j = 0 if l1 > l2: return 0 while i < l1 and j < l2: if str1[i] == str2[j]: i += 1 j += 1 else: j += 1 return 100 * (i / l1)
def get_all_subsets(some_list): """Returns all subsets of size 0 - len(some_list) for some_list""" if len(some_list) == 0: # If the list is empty, return the empty list return [[]] subsets = [] first_elt = some_list[0] rest_list = some_list[1:] '''Strategy: Get all the s...
def thread(read=20, write=20): """Return the kwargs for creating the Thread table.""" return { 'AttributeDefinitions': [ { 'AttributeName': 'ForumName', 'AttributeType': 'S' }, { 'AttributeName': 'Subject', ...
def is_true(value): """Converts GET parameter value to bool""" return bool(value) and value.lower() not in ("false", "0")
def conv_out_shape(in_shape, out_fms, p, k, s): """ Gets the output shape [height, width] for a 2D convolution. (Assumes square kernel). @param in_shape: The input shape [batch, height, width, channels]. @param out_fms: The number of feature maps in the output. @param p: The padding type (eithe...
def column_name_list(columns): """ Gets a comma-separated list of column names. :param columns: The list of columns. :returns: A comma-separated list of column names. """ if not columns: return '' return ', '.join([column.name for column in columns])
def praat_string(text): """Return a string formatted to be recognized by Praat. Parameters ---------- text : str String to be formatted for Praat. Returns ------- str """ return '"' + text.replace('"', '""') + '"'
def draw_on_pattern(shape, pattern): """ Draws a shape on a pattern. >>> draw_on_pattern([(0, 0, 1), (0, 1, 3), (1, 1, 8)], [[0, 0, 0], [0, 0, 0]]) [[1, 3, 0], [0, 8, 0]] """ y_size = len(pattern) x_size = len(pattern[0]) new_pattern = pattern.copy() for cell in shape: y, x, c...
def get_unique_words(documents): """ Helper function that returns every unique word present in a set of documents. :param documents: list of string documents containing words :return: list of all unique lowercase string words across the documents """ unique_words = [] for document in docume...
def metadata_keys_complete(result_keys) -> bool: """ Helper function for tests that assert, that all metdata keys are present in a dictionary that has been returned as the result of a query. :param result_keys: keys of a database-specific dictionary that has been returned by a query, corresponds to ...
def import_from_path(path): """ Import a class dynamically, given it's dotted path. :param path: the path of the module :type path: string :return: Return the value of the named attribute of object. :rtype: object """ module_name, class_name = path.rsplit('.', 1) ...
def get_url_attrs(url, attr_name): """ Return dictionary with attributes for HTML tag, updated with key `attr_name` with value `url`. Parameter `url` is either a string or a dict of attrs with the key `url`. Parameter `attr_key` is the name for the url value in the results. """ url_attrs = {} ...
def convert_distance(val, old_scale="meter", new_scale="centimeter"): """ Convert from a length scale to another one among meter, centimeter, inch, feet, and mile. Parameters ---------- val: float or int Value of the length to be converted expressed in the original scale. old_scale...
def serialize_umd(analysis, type): """.""" return { 'id': None, 'type': type, 'attributes': { 'loss': analysis.get('loss', None), 'gain': analysis.get('gain', None), 'treeExtent': analysis.get('treeExtent', None), 'treeExtent2010': analysis...
def input_data(list_images): """ images are alwyas NHWC. """ assert type(list_images) == list return list_images
def ExpandIncome(e00200, pencon_p, pencon_s, e00300, e00400, e00600, e00700, e00800, e00900, e01100, e01200, e01400, e01500, e02000, e02100, p22250, p23250, cmbtp, ptax_was, benefit_value_total, expanded_income): """ Calculates expanded_income from component in...
def forwardTransform(transform, phi, actVal): """! Forwards transform a configuration and compute Jacobian. """ # there is no transform if transform is None: return phi, actVal, 0 # delegate to the actual transform return transform.forward(phi, actVal)
def GetColumn(data, index): """Extracts the given column from the dataset. data: sequence of rows index: which column Returns: map from int year to float datum """ res = {} for row in data: try: year = int(row[0]) res[year] = float(row[index]) / 10.0 ...
def bad_a_order(a, b): """ A partial order which is not a lattice. """ return (a in ['a', 'b']) and (b in ['c', 'd'])
def imager_view(request): """Display Imager Detail.""" message = "Hello" return {'message': message}
def bounding_box(points): """ The function calculates bounding_box from the coordinates. XY - Min , XY - Max :param points: coordinates list :return: List of bounding box. """ x_coordinates, y_coordinates = zip(*points) return [(min(x_coordinates), min(y_coordinates)), (max(x_coordinates), m...
def set_data_format(array_values): """ Check and set the corresponding format for each value :param list[list[str]] array_values: list of values :return: list[list[str]]: array formatted """ formatted_data = [] for d in array_values: values = [] for v in d: ...
def _create_simple_json_dict(image_anns): """Makes a list of annotations in simple_json format.""" simple_json_anns = [] for ann in image_anns: ann_dict = {} ann_dict["bbox"] = [ann["x_min"], ann["y_min"], ann["width"] + ann["x_min"], ann["height"] + ann["y_min"]] ann_dict["classname...
def to_single_data(input): """Convert an input to a single bcbio data/world object. Handles both single sample cases (CWL) and all sample cases (standard bcbio). """ if (isinstance(input, (list, tuple)) and len(input) == 1): return input[0] else: assert isinstance(input, dict), inpu...
def get_key(iroot, num_states): """ Get energy key for the state of interest. Args: iroot (int): state of interest num_states (int): total number of states Returns: key (str): energy key """ # energy if only one state if iroot == 0 and num_states == 1: key = ...
def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token. Original version was obtained from here: https://github.com/huggingface/transformers/blob/23c6998bf46e43092fc59543ea7795074a720f08/src/transformers/data/processors/squad.py#L38...
def collinear(coordinates): """ Passing thru one pt with some fixed slope \implies must exist only one such line """ A, B, C = coordinates epsilon = 1e-10 slope_AB = (B[1] - A[1]) / (B[0] - A[0]) slope_AC = (C[1] - A[1]) / (C[0] - A[0]) if abs(slope_AB - slope_AC) < epsilon: ...
def most_expensive_menu_item(restaurant): """ Loops through a list of menu items and determines the most expensive item Parameters: restaurant (dict): A dictionary with three lists items, prices, and cals Returns: str: A string with the name of the most expensive item """ highe...
def check_script(script): """ Checks if a given string is a script (hash160) (or at least if it is formatted as if it is). :param script: Script to be checked. :type script: hex str :return: True if the signatures matches the format, raise exception otherwise. :rtype: bool """ if not isins...
def get_dict_field(blob, field_name): """extract the isni from the remote id data for the author""" if not blob or not isinstance(blob, dict): return None return blob.get(field_name)
def is_power_of_2(val): """Returns True if an integer is a power of 2. Only works for x > 0.""" return not val & (val-1)
def bottom_row(matrix): """ Return the last (bottom) row of a matrix. Returns a tuple (immutable). """ return tuple(matrix[-1])
def _parse_csv_item_opts(entry): """Parse the _opts field in a SB Extended CSV item.""" # Accepting even slightly weirdly formatted entries: entry = entry.strip() if len(entry) == 0: return {} opts = {} for opt in entry.split(" "): opt_name, opt_val = opt.split(":") opts[...
def missing_formulas(dataset): """Return boolean of whether each technosphere and biosphere are parameterized. Used to check if datasets which are indicated for combined production can be used as such.""" TYPES = {'from environment', 'to environment', 'from technosphere'} return not all(exc.get('formul...
def _some1(predicate, iterable): """Alternative implementation of :func:`some`.""" return any(map(predicate, iterable))
def xy(x:int, y:int) -> int: """Converts coordinates [x,y] in [(0-8),(0-8)] to [0-80] array location """ return y*9 + x
def _sorter(data): """ Return a tree of tuples (type, items sequence) for each items in a nested data structure composed of mappings and sequences. Used as a sorting key. """ seqtypes = list, tuple maptypes = dict, dict coltypes = seqtypes + maptypes if isinstance(data, maptypes): ...
def get_p_key(episode_info): """ create the primary key field by concatenating episode information :param episode_info: Dictionary of a single episode """ return f'{episode_info["show_stub"]}S{episode_info["season"]}E{episode_info["episode"]}'
def inversao(num): """ Funcao para inverter o numero `param` num: numero para ser invertido """ aux = 0 while (num > 0): remainder = num % 10 aux = (aux * 10) + remainder num = num // 10 return aux