content
stringlengths
42
6.51k
def to_lower(ctx, param, value): """Callback to lower case the value of a click argument""" return value.lower()
def eq_strict(a, b): """Returns True if both values have the same type and are equal.""" if type(a) is type(b): return a == b return False
def eval_branch(branch, teaching_combo): """Evaluate a branch on a teaching combo :param branch: dict containing comparators and numbers for blickets and non-blickets; used to construct a function representation of the branch :param teaching_combo: string of '*' (blickets) and "." (...
def make_tag(ttag, ttype): """Inverse of parse_tag.""" if ttype is None: return ttag else: return ttag+'-'+ttype
def cos(direction): """naive implementation of cos""" return int(abs(2 - direction) - 1)
def height(ep, m): """ Calculate and return the value of height using given values of the params How to Use: Give arguments for ep and m params *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: ...
def collate_double(batch): """ collate function for the ObjectDetectionDataSet. Only used by the dataloader. """ x = [sample['x'] for sample in batch] y = [sample['y'] for sample in batch] x_name = [sample['x_name'] for sample in batch] y_name = [sample['y_name'] for sample in batch] ...
def _mro(cls): """ Return the I{method resolution order} for C{cls} -- i.e., a list containing C{cls} and all its base classes, in the order in which they would be checked by C{getattr}. For new-style classes, this is just cls.__mro__. For classic classes, this can be obtained by a depth-first...
def sudoku2(grid): """ check if sudoku board is true by checking that the same number didn't appear more than one in its row, col, surrounding 3*3 sub matrix """ for i in range(9): for j in range(9): if i % 3 == 0 and j % 3 == 0: l = [ grid[s_i...
def compare_values(value1, value2): """ In-depth comparison of the two values. If the two are primitives, compare them directly. If the two are collections, go recursive through the elements. """ print("Comparing " + str(value1) + " & " + str(value2) + ".") # if different types, sure not equal ...
def _transform_str_numeric_read_net_per_stock(row): """Transformation fucntion from string to numeric for rows of table net_per_stock. "Month Year", "Ticker", "Available Quantity units",(int) "Average Buy Price brl_unit",(float) "Sold Quantity units",(int) "Average Sell Price brl_unit",(...
def strip(string): """ Strip a unisense identifier string of unnecessary elements such as version string {https://www.unisens.org/unisens2.0} """ if '}' in string: string = string.split('}')[-1] return string
def call_sig(args, kwargs): """Generates a function-like signature of function called with certain parameters. Args: args: *args kwargs: **kwargs Returns: A string that contains parameters in parentheses like the call to it. """ arglist = [repr(x) for x in args] arglist...
def break_s3_file_uri(fully_qualified_file): """ :param fully_qualified_file: in form s3://{0}/{1}/{2} where {0} is bucket name, {1} is timeperiod and {2} - file name :return: tuple (s3://{0}, {1}/{2}) """ tokens = fully_qualified_file.rsplit('/', 2) return tokens[0], '{0}/{1}'.format(tokens...
def listify(value): """If variable, return a list of 1 value, if already a list don't change a list. """ if value is not None: if not isinstance(value, list): value = [value] else: value = [] return value
def adjust_detector_length(requested_detector_length, requested_distance_to_tls, lane_length): """ Adjusts requested detector's length according to the lane length and requested distance to TLS. If requested detector length is negative, the resu...
def pretty_float(x): """Format a float to no trailing zeroes.""" return ('%f' % x).rstrip('0').rstrip('.')
def place_nulls(key, input_keyvals, output_results): """ Useful in a specific case when you want to verify that a mapped list object returns objects corresponding to input list. Hypothetical example: Customer.raw_get_all([1,2,3]) returns [C1, C3] There is no customer with id 2 in db. But this is...
def color(string_name, color_name=None): """ Change text color for the Linux terminal. """ if not string_name: return '' string_name = str(string_name) attr = ['1'] # bold if color_name: if color_name.lower() == "red": attr.append('31') elif color_na...
def findPoisonedDuration(timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ #complexity: O(n) +O(n) = O(n) poisoned = [] for t in timeSeries: #loop over all elements in timeSeries = O(n) poisoned += list(range(t, t+duration)) #O(1) b/c dura...
def update_gd_parameters(parameters, gradients, alpha=0.01): """ subtracting the gradient from the parameters for gradient descent :param parameters: containing all the parameters for all the layers :param gradients: containing all the gradients for all the layers :param alpha: learning rate :re...
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... """ if str(value).lower() in ("yes...
def cleanup_bars(bars, width): """Cleans up a set of bars in staves globally""" if len(bars) > 1: l_diffs = [] for i in range(len(bars) - 1): l_diffs.append(abs(bars[i][0] - bars[i+1][0])) if min(l_diffs) < width: lowest_index = l_diffs.index(min(l_diffs)) ...
def custom_latex_processing(latex): """ Processes a :epkg:`latex` file and returned the modified version. @param latex string @return string """ if latex is None: raise ValueError("Latex is null") # this weird modification is only needed when jenkins run a...
def convert(hours: int, minutes: int) -> int: """Convert hours and minutes to total seconds.""" total_seconds = (minutes * 60) + (hours * 3600) return total_seconds
def minutes_to_hours(time): """ input: time in minutes, output: same in 'HH:MM' """ return str(time // 60) + ':' + str(time % 60)
def has_shape(a): """Returns True if the input has the shape attribute, indicating that it is of a numpy array type. Note that this also applies to scalars in jax.jit decorated functions. """ try: a.shape return True except AttributeError: return False
def fuzzy_collname_match(trial, targets): """ Do a noddy fuzzy match for bits between punctuation, e.g. matthews_cool_database will search for matthews, cool and database in the known collection names. Parameters: trial (str): database search name. targets (list): list of existing datab...
def get(l, i, d=None): """Returns the value of l[i] if possible, otherwise d.""" if type(l) in (dict, set): return l[i] if i in l else d try: return l[i] except (IndexError, KeyError, TypeError): return d
def process_latitude(cell): """Return the latitude from a cell.""" lat = cell.strip().split("/")[0].strip() return float( int( str(lat[0]) + str(lat[1]), ) + int( str(lat[2]) + str(lat[3]), ) / 60 + int( str(lat[4]) + str(lat[5]), ...
def dispatch(obj, replacements): """make the replacement based on type :param obj: an obj in which replacements will be made :type obj: any :param replacements: the things to replace :type replacements: tuple of tuples """ if isinstance(obj, dict): obj = {k: dispatch(v, replacements...
def dict_to_css(css_dict, pretty=False): """Takes a dictionary and creates CSS from it :param css_dict: python dictionary containing css rules :param pretty: if css should be generated as pretty :return: css as string """ seperator = '\n' tab = '\t' if not pretty: seperator = '' ...
def calc_temp(hex_str): """ Convert 4 hex characters (e.g. "040b") to float temp (25.824175824175825) :param hex_str: hex character string :return: float temperature """ adc = int(hex_str[0:2], 16) * 256 + int(hex_str[2:4], 16) temp = (300 * adc / 4095) - 50 return temp
def filter_assigments(all_player_dict, schedule_name_counter, data_screen_names): """Keep only dataset related player assigments""" player_dict = {} for p in all_player_dict: if schedule_name_counter is None: player_dict[p] = all_player_dict[p] else: if p in schedule_...
def eea(m, n): """ Compute numbers a, b such that a*m + b*n = gcd(m, n) using the Extended Euclidean algorithm. """ p, q, r, s = 1, 0, 0, 1 while n != 0: k = m // n m, n, p, q, r, s = n, m - k*n, q, p - k*q, s, r - k*s return (p, r)
def escape_email(email: str) -> str: """ Convert a string with escaped emails to just the email. Before:: <mailto:email@a.com|email@a.com> After:: email@a.com :param email: email to convert :return: unescaped email """ return email.split('|')[0][8:]
def part1(input_data): """ >>> part1([0,3,6]) 436 >>> part1([1,3,2]) 1 >>> part1([2,1,3]) 10 >>> part1([1,2,3]) 27 >>> part1([2,3,1]) 78 >>> part1([3,2,1]) 438 >>> part1([3,1,2]) 1836 """ memory = input_data.copy() for i in range(2020-len(input_dat...
def dob_fun(dob): """This function takes a date of birth and checks whether it's valid or not. Parameters: dob: The date of the birth of the person. Returns: The proper date of birth of the person. """ condition = len(dob) == 10 and (dob[:4] + dob[5:7] + dob[8:]).isdigit() \ ...
def small(txt): """ >>> print(small('I feel tiny')) <small>I feel tiny</small> >>> print(small('In a website I would be small...', tags=False)) In a website I would be small... """ return f'<small>{txt}</small>'
def _make_validation_key(game_id: str) -> str: """Make the redis key for game validation.""" return 'ttt:{}:valid'.format(game_id)
def get_package_name_list(package_list): """Take a list of package loaders and returns a list of package names """ package_name_list = [] for package in package_list: package_name_list.append(package.__name__) return package_name_list
def intersectionOfSortedArrays(a,b): """ less than o(m+n) complexity """ ia=0 ib=0 op=[] while ia<len(a) and ib<len(b): if a[ia] < b[ib]: ia+=1 elif a[ia] > b[ib]: ib+=1 else: op.append(a[ia]) ia+=1 return op
def isprivilege(value): """Checks value for valid privilege level Args: value (str, int): Checks if value is a valid user privilege Returns: True if the value is valid, otherwise False """ try: value = int(value) return 0 <= value < 16 except ValueError: ...
def round_up(value): """Replace the built-in round function to achieve accurate rounding with 2 decimal places :param value:object :return:object """ return round(value + 1e-6 + 1000) - 1000
def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. :Examples: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' ...
def join_name_with_id(stations, data): """ Performs a join on stations and pollution data :param stations: list of stations data for a specific date :param data: pollution data :return: list of joined data """ mapping = {name.lower().strip(): id_station for id_station, name in stations} ...
def _stringify_time_unit(value: int, unit: str) -> str: """ Returns a string to represent a value and time unit, ensuring that it uses the right plural form of the unit. >>> _stringify_time_unit(1, "seconds") "1 second" >>> _stringify_time_unit(24, "hours") "24 hours" >>> _stringify_time_uni...
def is_testharness_baseline(filename): """Checks whether a given file name appears to be a testharness baseline. Args: filename: A path (absolute or relative) or a basename. """ return filename.endswith('-expected.txt')
def swap_list_order(alist): """ Args: alist: shape=(B, num_level, ....) Returns: alist: shape=(num_level, B, ...) """ new_order0 = len(alist[0]) return [[alist[i][j] for i in range(len(alist))] for j in range(new_order0)]
def format_error(error: BaseException) -> str: """Format an error as a human-readible string.""" return f"{type(error).__name__}: {error}"
def escape_env_var(varname): """ Convert a string to a form suitable for use as an environment variable. The result will be all uppercase, and will have all invalid characters replaced by an underscore. The result will match the following regex: [a-zA-Z_][a-zA-Z0-9_]* Example: "my.pri...
def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): """ This prototype should be used to create an iban object from iban correct string @param {String} iban """ return ((num == 0) and numerals[0]) or \ (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]...
def cut_off_string_edge_spaces(string): """ :type string: str :rtype: str """ while string.startswith(" "): string = string[1:] while string.endswith(" "): string = string[:-1] return string
def bisect_left_adapt(a, x): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the leftmost x already there. ...
def check_reporting_status(meta, fname): """Check an individual metadata and return logical status""" status = True if("reporting_status" not in meta): print("reporting_status missing in " + fname) status = False else: valid_statuses = ['notstarted', 'inprogress', 'comp...
def merge_dict(dict1, dict2, path=None): """ Merge two dictionaries such that all the keys in dict2 overwrite those in dict1 """ if path is None: path = [] for key in dict2: if key in dict1: if isinstance(dict1[key], dict) and isinstance(dict2[key], dict): merge_d...
def solution(power): """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ num = 2 ** power string_num = str(num) list_num = list(string_num) sum_of_num = 0 for i in lis...
def get_starlark_list(values): """Convert a list of string into a string that can be passed to a rule attribute.""" if not values: return "" return "\"" + "\",\n \"".join(values) + "\""
def _is_possible_expansion(acro: str, full: str) -> bool: """ Check whether all acronym characters are present in the full form. :param acro: :param full: :return: """ # Empty acronym is presented everywhere if not acro: return True # Non-empty acronym is not presented in e...
def get_parameters(runtime, environment): """ Set up parameters dictionary for format() substitution """ parameters = {'runtime': runtime, 'environment': environment} if environment is None: tmpl = 'enable-mapping-ci-{runtime}' environment = tmpl.format(**parameters) parameters['...
def FlagBelongsToRequiredGroup(flag_dict, flag_groups): """Returns whether the passed flag belongs to a required flag group. Args: flag_dict: a specific flag's dictionary as found in the gcloud_tree flag_groups: a dictionary of flag groups as found in the gcloud_tree Returns: True if the flag belong...
def is_small_calcification(bb_width, bb_height, min_diam): """ remove blobs with greatest dimension smaller than `min_diam` """ if max(bb_width, bb_height) < min_diam: return True return False
def get_value_of_dict(dictionary, key): """ Returns the value of the dictionary with the given key. """ value = 0 try: value = dictionary[str(key)] except KeyError: pass return value
def find_subsequence(subseq, seq): """If subsequence exists in sequence, return True. otherwise return False. can be modified to return the appropriate index (useful to test WHERE a chain is converged) """ i, n, m = -1, len(seq), len(subseq) try: while True: i = seq.index(sub...
def get_largest_value(li): """Returns the largest value in the given list""" m = li[0] for value in li: if value > m: m = value return m
def counting_sort(data, mod): """ :param data: The list to be sorted. :param mod: exp(index of interest) """ buckets = [[] for _ in range(10)] for d in data: buckets[d//mod % 10].append(d) return sum(buckets, [])
def _format_secs(secs: float): """Formats seconds like 123456.7 to strings like "1d10h17m".""" s = "" days = int(secs / (3600 * 24)) secs -= days * 3600 * 24 if days: s += f"{days}d" hours = int(secs / 3600) secs -= hours * 3600 if hours: s += f"{hours}h" mins = int(secs / 60) s += f"{mins}m...
def convert_to_tuples(examples): """ Convert a list of Example objects to tuples of the form: (source, translation, language, author, reference). """ convert1 = lambda e: e.to_simple_tuple() return list(filter(bool, map(convert1, examples)))
def replace_char_with_space(text, chars): """From StackOverflow See: https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string """ for char in chars: text = text.replace(char, ' ') return text
def convert_bytes_in_results_tuple(results_tuple): """ Convert the varbinaries to unicode strings, and return a list of lists. """ return [[x.decode() if type(x) == bytes else x for x in row] for row in results_tuple]
def remove_html_tags(text): """Remove html tags from a string""" import re clean = re.compile('<.*?>') return re.sub(clean, '', text)
def is_twin_response_topic(topic): """Topics for twin responses are of the following format: $iothub/twin/res/{status}/?$rid={rid} :param str topic: The topic string """ return topic.startswith("$iothub/twin/res/")
def simple_request_messages_to_str(messages): """ Returns a readable string from a simple request response message Arguments messages -- The simple request response message to parse """ entries = [] for message in messages: entries.append(message.get('text')) return ','.join(ent...
def formatSearchQuery(query): """ It formats the search string into a string that can be sent as a url paramenter. """ return query.replace(" ", "+")
def create_logout_url(slug): """Creates a logout url.""" # Currently we have no way to implement this on non-GAE platforms # as a stand alone app. return ''
def is_builtin_entity(oid): """Return if the OID hex number is for a built-in entity.""" # More information in get_oid oid_num = int(oid, 16) return oid_num & 0xC0 == 0xC0
def negative_loop(dists): """ Check if the distance matrix contains a negative loop - i.e. you can get from some location back to that location again in negative time. You could just follow this loop many times until you got enough time to save all bunnies and exit """ return any([dists[x][x] < ...
def modexp3(b,m): """e=3, use addition chain""" b2=(b*b)%m b3=(b*b2)%m assert(b3==pow(b,3,m)) return b3
def abv_calc(og, fg, simple=None): """Computes ABV from OG and FG. Parameters ---------- og : float Original gravity, like 1.053 fg : float Final gravity, like 1.004 simple : bool or None, defaults to None. Flag specifying whether to use the simple (linear) equation or ...
def make_run_list(run_csvs): """ Reads list of csvs to give performance of the different hyperparameter settings. Returns ------- data_list : list of numpy.ndarrays performance of different hyperaparameter settings for the csvs given as input. """ import csv data_l...
def hamming_distance(s1, s2): """ Get Hamming distance: the number of corresponding symbols that differs in given strings. """ return sum(i != j for (i,j) in zip(s1, s2) if i != 'N' and j != 'N')
def population_attributable_fraction(a, b, c, d): """Calculates the Population Attributable Fraction from count data Returns population attribuable fraction a: -count of exposed individuals with outcome b: -count of unexposed individuals with outcome c: -count of exposed in...
def get_file_size(fileobj): """ Returns the size of a file-like object. """ currpos = fileobj.tell() fileobj.seek(0, 2) total_size = fileobj.tell() fileobj.seek(currpos) return total_size
def rewrite( string: str, charmap: dict = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'a': 't', 't': 'a', 'c': 'g', 'g': 'c', }, sep: str = '', ) -> str: """ Given a sequence derived from 'ATCG', this function returns t...
def sansa_xor(arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/sansa-and-xor/problem Sansa has an array. She wants to find the value obtained by XOR-ing the contiguous subarrays, followed by XOR-ing the values thus obtained. Determine this value. Solve: By going through and X...
def list_to_string(in_list, conjunction): """Simple helper for formatting lists contaings strings as strings. This is intended for simple lists that contain strings. Input will not be checked. :param in_list: List to be converted to a string. :param conjunction: String - conjunction to be used (e....
def build_cmd(*args, **kwargs): """ >>> build_cmd('script.py', 'train', model_pickle='tmp.pkl', shuffle=True) 'script.py train --model_pickle "tmp.pkl" --shuffle' """ options = [] for key, value in kwargs.items(): if isinstance(value, bool): options.append("--%s" % key) ...
def isWinner(board): """Looks at `board` and returns either '1' or '2' if there is a winner or 'tie' or 'no winner' if there isn't. The game ends when a player has 24 or more seeds in their mancala or one side of the board has 0 seeds in each pocket.""" b = board # Make a shorter variable name to u...
def cell_color(color): """Return the color of a cell given its container and the specified color""" return r'\cellcolor{' + color + '}' if color else ''
def add_if_not_none(a, b): """Returns a/b is one of them is None, or their sum if both are not None.""" if a is None: return b if b is None: return a return a + b
def consecutive_3_double(word): """Checks word for 3 consecutive double letters. Return Boolean""" for i in range(len(word)-5): if word[i] == word[i+1]: if word[i+2] == word[i+3]: if word[i+4] == word[i+5]: return True return False
def echo_magic(rest): """ Echo the argument, for testing. """ return "print(%r)" % rest
def get_relationship_by_type(rels, rel_type): """ Finds a relationship by a relationship type Example:: # Import from cloudify import ctx from cloudify_azure import utils # Find a specific relationship rel = utils.get_relationship_by_type( ctx.instan...
def get_starting_chunk(content, length=1024): """ :param content: File content to get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes. """ # Ensure we open the file in binary mode chunk = content[0:length] return chunk
def anchorName(symId): """HTML links are not case-sensitive, so we have to modify upper/lowercase symbols to distinguish them""" if symId[:1].isupper(): return symId else: return '__'+symId
def qs_uses_ssl(qs): """ By default, we don't use SSL. If ?ssl=true is found, we do. """ for ssl_value in qs.get('ssl', []): if ssl_value == "true": return True return False
def zmqUDS(mnt_pt): """ Set the zmq address as a Unix Domain Socket: ipc://file """ return 'ipc://{}'.format(mnt_pt)
def calc_ongrid(elec, mix, tech_lut, elec_types, emission_type): """ Calculate the emissions for a given electricity and emission type. Parameters ---------- elec : int The quantity of electricity consumption estimated for the settlement. mix : list of dicts Contains the electri...
def get_small_joker_value(deck_of_cards): """ (list of int) -> int Return the second largest value in deck_of_cards as the value of small joker. >>> get_small_joker_value([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 3, 6, 9, \ 12, 15, 18, 21, 24, 27, 2, 5, 8, 11, 14, 17, 20, 23,...
def add_subdir(config): """ Add subdir back into config """ if not config: return config if 'context' in config: config['subdir'] = config['context'] return config