content
stringlengths
42
6.51k
def canBeNumeric(inStr): """Determines whether the input can be converted to a float (using a try: float(instr)) """ try: float(inStr) return True except Exception: return False
def connected_components(graph): """ Given an undirected graph (a 2d array of indices), return a set of connected components, each connected component being an (arbitrarily ordered) array of indices which are connected either directly or indirectly. """ def add_neighbors(el, seen=[]): ''...
def comma_list_to_shape(s): """Parse a string of comma-separated ints into a valid numpy shape. Trailing commas will raise an error. Parameters ---------- s : str A string of comma-separated positive integers. Returns ------- tuple """ if not isinstance(s, str): ...
def manhattan(instruction, blank): """is waiting two tuples""" return abs(instruction[0] - blank[0]) + abs(instruction[1] - blank[1])
def increment_char(char): """ Increments a character by one. Example: 'C' --> 'D'. """ return chr(ord(char) + 1)
def integer_ceil(a, b): """Return the ceil integer of a div b.""" quanta, mod = divmod(a, b) if mod: quanta += 1 return quanta
def longest_substring(str_list): """ Finds longest substring among list of strings :param str_list: strings to be searched :type str_list: list (of str) :rtype: str """ lstr = '' if (len(str_list) > 1) and (len(str_list[0]) > 0): for i in range(len(str_list[0])): ...
def change_cat_id(coco_ann, id): """ :param coco_ann: json file containing coco ground truth :param id: id that will replace the former category id :return: json file containing coco ground truth where each object id is replaced by the id given in argument """ idx = 0 for i in range(len(co...
def FitUnsafeText(text, length): """Trim some unsafe (unescaped) text to a specific length. Three periods are appended if trimming occurs. Note that we cannot use the ellipsis character (&hellip) because this is unescaped text. Args: text: the string to fit (ASCII or unicode). length: the length to tr...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. The idea is to put 0 and 2 in their correct positions, which will make sure all the 1s are automatically placed in their right positions Args: input_list(list): List ...
def calc_stops(stops, count): """Calculate stops.""" # Ensure the first stop is set to zero if not explicitly set if 0 not in stops: stops[0] = 0 last = stops[0] * 100 highest = last empty = None final = {} # Build up normalized stops for i in range(count): value =...
def num_ways(n: int) -> int: """ Top-down solution: Recursion with caching. Time complexity: O(n). With the caching. Since for the overlapping subproblems we can access their results in constant time. Space complexity: O(n). We store values only up to n. """ # base cases if n < 1: ...
def clean_query(this_object): """clean_query: remove `_version_` key""" this_object.pop('_version_', None) return this_object
def sumOfDigPow(n, a): # sum of digits powered """ n: an int a: the power of each digits output: sum of each digits of n with power of a """ numStr = str(n) total = 0 for digit in numStr: total += int(digit)**a return total
def init_values(attrs): """ Sets value for every column to None """ for k, v in attrs.items(): attrs[k]["value"] = None return attrs
def int_to_roman(input): """ Convert an integer to Roman numerals. taken from: http://code.activestate.com/recipes/81611-roman-numerals/ Examples: >>> int_to_roman(0) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(-1) Traceback (most ...
def non_zero_suffix(b): """Returns the longest suffix of b that starts with a non-zero byte.""" i = 0 while i < len(b) and b[i] == 0: i += 1 return b[i:]
def ValueOrNone(message): """Return message if message is a proto with one or more fields set or None. If message is None or is the default proto, it returns None. In all other cases, it returns the message. Args: message: An generated proto message object. Returns: message if message is initialize...
def csp_exist(payload): """renvoi la csp du user""" name_csp = payload.get('social_professional_category') if name_csp is None: return (None) else: csp = {'artisans, commercants, chefs entreprise': '1', 'cadres et professions intellectuelles superieures': '2', 'pr...
def _is_shorthand_ip(ip_str): """Determine if the address is shortened. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if the address is shortened. """ if ip_str.count('::') == 1: return True if any(len(x) < 4 for x in ip_str.split(':')): ...
def get_cache_key(request, meta, orgaMode, currentOrga): """Return the cache key to use""" # Caching cacheKey = None if 'cache_time' in meta: if meta['cache_time'] > 0: # by default, no cache by user useUser = False # If a logged user in needed, cache the ...
def sort(l): """ this is a recursive function to sort an array of integers """ if not l: return [] return sort([x for x in l if x<l[0]]) + [x for x in l if x==l[0]] + sort([x for x in l if x>l[0]])
def accuracy(gold_sequences, pred_sequences): """ Return percentage of instances in the test data that our tagger labeled correctly. :param gold_sequences: a list of tag sequences that can be assumed to be correct :param pred_sequences: a list of tag sequences predicted by Viterbi """ c...
def _validate_minmax(minmax, signed): """ [Docstring] """ if minmax[0] >= minmax[1]: return (False, "Error: 'max' is not greater than 'min'") if not signed and minmax[0] < 0: return (False, "Error: Negative 'min' in absolute " "thresholding mode") return (T...
def get_quadrant(station_loc, loc): """ Origin on upper left: 1 | 2 --+-- 3 | 4 """ y0, x0 = station_loc y1, x1 = loc if y1 <= y0: if x1 < x0: quad = 1 else: quad = 2 else: if x1 < x0: quad = 3 else: ...
def clean_uri(uri): """ This method removes the url part of the URI in order to obtain just the property or class :param uri: An uri to be cleaned :return: The name of the property or the class """ if uri.find('#') != -1: special_char = '#' else: special_char = '/' ind...
def set_accounts_filter(account_ids: list) -> dict: """Given a list of account ids, returns parameters with corresponding filters. :returns: accounts_filter: Parameters used to filter the query for given account ids :rtype: dict """ accounts_filter = {"q": "search"} for i, account_id in enumera...
def create_category_dictionary(post): """ This function creates a dictionary from an HTTP Request Post that contains category names as keys and their weights as values. :param post: A dict, the POST from the HTTP Request :return: A dict """ cat_dict = dict() for key, value in post.items(...
def is_palindrome_iterative(text): """Iterative function for determining if text is a palindrome.""" # Best time complexity -- O(1), text is either empty or contains one character # Average time complexity -- O(n/2), text is palindrome text = text.lower() left = 0 right = len(text) - 1 while...
def best_language_match(lang, available_languages): """Return the available language matching best the preferred language.""" if lang is None: lang = "" # full match lang = lang.replace("_", "-") for available_language in available_languages: if lang.lower() == available_language.low...
def squaredError(label, prediction): """Calculates the the squared error for a single prediction. Args: label (float): The correct value for this observation. prediction (float): The predicted value for this observation. Returns: float: The difference between the `label` and `predi...
def _create_tuple(shape, value): """Returns a tuple with given shape and filled with value.""" if shape: return tuple([_create_tuple(shape[1:], value) for _ in range(shape[0])]) return value
def prefix_to_items(items, prefix): """Add a prefix to the elements of a listing. For example, add "Base" to each item in the list. """ return ['{}{}'.format(prefix, x) for x in items]
def calc_percent(whole, total): """ """ try: pct = whole / total except ZeroDivisionError: pct = 0 else: pct * 100 return pct
def clip(x, lowest, highest): """Return x clipped to the range [lowest..highest].""" return max(lowest, min(x, highest))
def select_sort2(seq): """ :param seq: :return: """ def find_smallest_index(seq): smallest = seq[0] smallest_index = 0 for i in range(1, len(seq)): target = seq[i] if target < smallest: smallest = target smallest_index ...
def is_trivial_dir(dname): """input a string return 1 if dname is empty or '.' else return 0 """ if dname == None: return 1 if dname == '' or dname == '.' or dname == './' : return 1 return 0
def fq_typename(obj): """Returns the fully-qualified type name of an object. If the object is a type, returns its fully-qualified name. """ typ = type(obj) if not isinstance(obj, type) else obj return '{}.{}'.format(typ.__module__, typ.__qualname__)
def ci(v): """ Calculate the chemotaxis index """ return ((v[0] + v[3]) - (v[1] + v[2])) / float(v[6])
def nanopb_use_module_import(lines): """Changes #include <pb.h> to include <nanopb/pb.h>""" # Don't let Copybara alter these lines. return [line.replace('#include <pb.h>', '{}include <nanopb/pb.h>'.format("#")) for line in lines]
def check_if_substring_match(lines, substring): """Checks the provided lines and determines if a substring is present. Parameters ---------- lines : list of str The lines to check for a substring match. substring : str The substring to match Returns ------- bool ...
def heading(name, level="-"): """Return the rst-heading for the given heading.""" return f"{name}\n{level * len(name)}\n\n"
def banner(text, width=80): """ """ toFill = width - len(text) left = toFill // 2 right = toFill - left return '%s%s%s' % ('-' * left, text, '-' * right)
def broken_node_lookup_2(selectors): """Returns a list of various garbage, not strings""" return [{"this": "that"}, 7, "node3"]
def jaccard(s1, s2): """ Calculate the Jaccard *distance* between two sets (the length of the intersection / the length of the union). If either or both sets are empty the distance is 1. Note that this returns a distance -- 0 means things are similar, 1 means things are different :param s1: Set on...
def hex_to_bin(hex_num: str) -> int: """ Convert a hexadecimal value to its binary equivalent #https://stackoverflow.com/questions/1425493/convert-hex-to-binary Here, we have used the bitwise right shift operator: >> Shifts the bits of the number to the right and fills 0 on voids left as a resu...
def message_parse(message): """Put line breaks into message string.""" message = message.rstrip(".") message = message.replace(".", "<br>") return message
def timestep(dtime, time, end_time): """ calculates the timestep for a given time returns the timestep if the calculation isnt overstepping the endtime if it would overstep it returns the resttime to calculte to the endtime :param dtime: timestep :param time: current time in simulation :pa...
def mean(l: list) -> float: """ Returns the mean of a list, rounded to two decimal places. """ return round(sum(l)/len(l), 2)
def myfilter(d): """ Only those 'interesting' predictions. Here we just filter half. :param d: json returned from ml_evaluate() """ return d['overtakingProbability'] > 0.5
def sum_of_squares(params): """Multidimensional sum of squares. Args: params: numbers to be squared and summed. Returns: Sum of squares of numbers in params. """ return sum(x ** 2 for x in params)
def image_response(body): """Return an HTTP image/gif response from binary *body*""" payload = ("HTTP/1.1 200 OK\r\n" "Connection: keep-alive\r\n" "Content-Type: image/gif\r\n" "Content-Length: {}\r\n\r\n" "").format(len(body)).encode('utf-8') + body ...
def quote_string_constraints(kwargs): """ For constraints of String variables, the right-hand-side value must be surrounded by double quotes. """ return { k: f'"{v}"' if isinstance(v, str) else v for k, v in kwargs.items() }
def flatten(list_of_lists): """ Returns a list consisting of the elements in the list of lists. e.g. [[1,2,3],[3,4],[5,6]] -> [1,2,3,3,4,5,6] """ return [result for sublist in list_of_lists for result in sublist]
def is_palindrome(string: str) -> bool: """ Checks if the given string is a palindrome or not :param string: String to check :return: bool Example: >>> is_palindrome("ABA")\n >>> True """ if string == string[::-1]: return True return False
def factorial(n): """ Returns the factorial of n. e.g. factorial(7) = 7x6x5x4x3x2x1 = 5040 """ answer = 1 for i in range(n, 1, -1): answer = answer * i return answer
def drop_duplicate_fill0(result_dict): """ Drop value-0 from detection result """ labels = result_dict['labels'] num_items = len(labels) label_set = set() keep_index = [] for i in range(num_items): if labels[i] not in label_set: label_set.add(labels[i]) k...
def allowed_file(file_name_list: list) -> bool: """Return True if file extension of all passed file names is allowed""" allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'} for file_name in file_name_list: if not file_name: return False if file_name.split('.')[-1].lower() not in al...
def adapt_gender(gender: str): """ Args: gender (str): sexo da pessoa Returns: str: tratamento ao sexo """ if gender == 'm': return 'o aluno' elif gender == 'f': return 'a aluna' else: return ''
def is_int(s): """Check if a string is an int""" try: int(s) return True except ValueError: return False
def service_tracker(volume, service, service_tracker): """ service_tracker: Going to create the search json file with volume names """ if service in service_tracker.keys(): service_tracker[service].append(volume) # Keep Unique Values in list as there should not be same Search servi...
def bold(value, arg): """ Makes a word bold for rendering Inserts a span tag with appropriate class, such that the term will be bold after rendering. Args: value: arg: The word to be "bolded" Returns: The modified string """ arg_lower = arg.lower() arg_upper = arg.u...
def sentence_index_for_fragment_index(fragment_index: int, sentences: list) -> int: """Index of sentence within sentences list in which `fragment_index` is located.""" cur_start = 0 cur_end = -1 total_length = sum([len(s) for s in sentences]) + len(sentences) - 1 a = '\n'.join(sentences) asser...
def solution(a: list, k: int): """ Rotate an array to the right k steps. :param a: an array of integers :param k: number of times to shift to cycle the list :return: an array of reverser ints after k cycles """ # if not a: # raise IndexError("Empty List!") if not...
def cast_to_schema_type(field, schema_type): """ generates cast expression to the type specified by the schema :param field: field name :param schema_type: type of the field as specified in the schema :return: string of cast expression """ bq_int_float = {'integer': 'INT64', 'float': 'FLOAT...
def gustafsons_law(num_proc, a_seq): """Gustafson-Barsis law for data parallelism Gustafson-Barsis' Law states that the optimal speedup is asymptotically `speedup(P) = P * \alpha_{par}`. When the problem size increases for a fixed serial problem, our speedup grows as more processors are added. ...
def calcAbsolutePercentageError(actualResult, forecastResult): """ Calculates Absolute Percentage Error. """ return (abs((actualResult - forecastResult)/actualResult)) * 100
def get_column(square_size, square, i): """Returns an i-th column of a square.""" expected_modulo = i % square_size col = [] for i, item in enumerate(square): if i % square_size == expected_modulo: col.append(item) return col
def _expand_font_names(font_names, result=None): """font names can include names of files containing a list of names, open those recursively and add to the set.""" def strip_comment(line): ix = line.find('#') if ix != -1: line = line[:ix] return line.strip() if result is None: result = se...
def format_title(title): """ Function is used to create the title of a graph based on the measurement concept and unit concept being used. This ensures that the new title has capitalized letters and lacks underscores. Parameters ---------- title (string): name of the image of the format...
def update_newlist(ques, new, user_input): """Edit the string with user's input.""" new = new.replace(ques, user_input, 1) return(new)
def hill_eq_brentq(xvalues_for_curve, hill_constants, y_value_curve_center): """ Residual function for the four parameter sigmoidal Hill equation. For further detail on the Hill equation, see the relevant docstring for hill_eq. y = hill_eq(x) - y_value_curve_center Parameters ---------- xvalu...
def reverse_dict(mapping:dict, always_list:bool=True)->dict: """Switches keys and values of a dictionary. As values can be duplicates, keys can and up in lists. If always_list==True, former keys are always encapsulated in lists even if the values are unique Args: mapping (dict): The dict to rev...
def metadata_with_prefix(prefix, **kw): """Create RPC metadata containing a prefix. Args: prefix (str): appropriate resource path. Returns: List[Tuple[str, str]]: RPC metadata with supplied prefix """ return [("google-cloud-resource-prefix", prefix)]
def IsNumeric(text): """Return true if the string contains a valid number""" try: _ = float(text) except ValueError: return 0 else: return 1
def sanitize(dirty: str, valid: str) -> str: """Removes invalid characters from string""" clean = '' for char in dirty: if char in valid: clean += char return clean
def _generate_collapse(collapse): """Make collapse string for query from collapse configurations. A collapse configuration is a dictionary with following fields: 1. field Field with which to collapse results. 2. null_policy, optional Policy with which to handle missing d...
def tokenize_poem(token_list, word_dict): """ List to tockens word_dict: dictionary of tokens token_list: word list """ aux =[word_dict[w] if w in word_dict else word_dict['<unk>'] for w in token_list] return aux
def _check_electrification_scenarios_for_partition(es): """Checks the electrification scenario input to :py:func:`partition_demand_by_sector` and :py:func:`partition_flexibility_by_sector`. :param str es: The input electrification scenario that will be checked. Can be any of: *'Reference'*, *'M...
def _from_hass_temperature(temperature): """Convert Home Assistant color temperature units to percentage.""" return (temperature - 154) / 346
def dict_add(d1,d2): """ Flatten 2 dictionaries """ d={} if len(d1): for s in d1.keys(): d[s] = d1[s] if len(d2): for s in d2.keys(): d[s] = d2[s] return d
def get_intersection(x1, y1, x2, y2, x3, y3, x4, y4): """Return intersection between segment 1 (p1-p2) and segment 2 (p3-p4).""" p1x = min(x1, x2) p2x = max(x1, x2) p3x = min(x3, x4) p4x = max(x3, x4) if p1x == x1: p1y = y1 p2y = y2 else: p1y = y2 p2y = y1 ...
def _filename_comparator(a_str, b_str): """Compares file name (case insensitive)""" if a_str.lower() < b_str.lower(): return -1 if a_str.lower() > b_str.lower(): return 1 return 0
def tabState(state): """Returns css selector based on tab state""" return 'active' if state else ''
def anonymous_fun_42_(curr_acc_12_): """ curr_acc_12_: Vec Double """ return len(curr_acc_12_) < len([0.0,0.0,0.0,0.0,0.0])
def match_targets_with_normalized_variants(targets, variants): """ After loading variants from normalized variants, we need to create a dictionary of all targets regions with their new variants as values :param targets: dictionary of BED target regions :param variants: dictionary of all variants fro...
def merge_shape(inputs): """ Dummy wrapper function to formally return shape of lambda merge """ return (inputs[0][0], 1)
def valid_temperature(temperature): """Determines whether or not the temperature is valid.""" return temperature > 1e-3 and temperature <= 1.0
def step_factor(t): """ Euler integration suppression factor.""" return (1+t)
def clip(n, start, stop=None): """Return n clipped to range(start,stop).""" if stop is None: stop = start start = 0 if n < start: return start if n >= stop: return stop-1 return n
def calculate_corr_pairs_one_baseline_per_task(tot_stations=3,tot_pols=1,auto_stations=0,auto_pols=1): """ Create array with identificators for all the correlation pairs for all the stations p<station_i><station_j>. Only used in one-baseline-per-task mode. Parameters ---------- tot_st...
def str2bool(w): """ Args: w: Returns: bool: """ if w.lower() in ('yes', 'true', 't', 'y', '1'): return True elif w.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise ValueError('Boolean value expected.')
def isPrime(n): """Test n for any factors, return True if number has no factors (is prime)""" n = abs(int(n)) if n < 2: return False # Zero and 1 are not prime. for i in range(2, n): if n % i == 0: return False return True
def _normalize_counts(counts, val=1): """Normalizes a dictionary of counts, such as those returned by _get_frequencies(). Args: counts: a dictionary mapping value -> count. val: the number the counts should add up to. Returns: dictionary of the same form as counts, except where the...
def removeAllpattern(stringList, patternCharacter): """ Remove the specific character from the list and return """ return([x for x in stringList if x != patternCharacter])
def _get_digits(text: str) -> int: """Gets digits from text. Args: text (str): text Returns: int: digits from text """ s = "" for x in text: if x.isdigit(): s += x else: pass if s: i = int(s) else: i = 0 retu...
def setintersect_ordered(list1, list2): """ returns list1 elements that are in list2. preserves order of list1 setintersect_ordered Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import ...
def side_by_relative_angle(angle): """Assign side axd on relative angle centered on 0 degrees. Negative angles are left. Positive angles are right. Parameters ---------- degrees : :obj:`float` Degrees centered at 180 (e.g., ranging from 0 to 360) Returns ------- :obj:`str`...
def _normalize(options): """Return correct kwargs for setup() from provided options-dict. """ retval = { key.replace("-", "_"): value for key, value in options.items() } # Classifiers value = retval.pop("classifiers", None) if value and isinstance(value, str): classifiers = ...
def catdog(char_list): """Solution to exercise P-1.29. Write a Python program that outputs all possible strings formed by using the characters c , a , t , d , o , and g exactly once. -------------------------------------------------------------------------- Solution: --------------------------...