content
stringlengths
42
6.51k
def handle_events(selection, events, selectors): """Execute functions corresponding to the selector contained in selection.""" results = [] for k, v in selectors.items(): if v in selection: results.append(events[k]()) selection.remove(v) return [res for res in results if ...
def ordered_json(json_dict): """Creates a ordered json for comparison""" if isinstance(json_dict, dict): return sorted((k, ordered_json(v)) for k, v in json_dict.items()) if isinstance(json_dict, list): return sorted(ordered_json(x) for x in json_dict) return json_dict
def makePrettySize(size): # copied from https://github.com/zalando/PGObserver """ mimics pg_size_pretty() """ sign = '-' if size < 0 else '' size = abs(size) if size <= 1024: return sign + str(size) + ' B' if size < 10 * 1024**2: return sign + str(int(round(size / float(1024)))) + ...
def get_offset(args): """Get the page offset, validating or returning 0 if None or invalid.""" offset = args.get('offset', '0') if offset.isdigit(): return int(offset) else: return 0
def set_bit(value, offset): """Set a bit at offset position :param value: value of integer where set the bit :type value: int :param offset: bit offset (0 is lsb) :type offset: int :returns: value of integer with bit set :rtype: int """ mask = 1 << offset return int(value | mask...
def add_to_mean(current_mean, n, new_value, decimals=2): """ This function can be used when wanting to know the new mean of a list after adding one or more values to it. One could use this function instead of recalculating the new mean by adding all the old values with the new one and dividing by n...
def addext(name_str, ext_str): """Add a file extension to a filename :param name_str: The filename that will get the extension :param ext_str: The extension (no leading ``.`` required) :returns: The filename with the extension """ if not ext_str: return name_str return name_s...
def remove_const(argtype): """Remove const from argtype""" if argtype.startswith('const'): return argtype.split('const ')[1] return argtype
def flatten_lists_all_level(list_of_lists: list) -> list: """ Wrapper to unravel or flatten list of lists to max possible levels Can lead to RecursionError: maximum recursion depth exceeded Default = 1000, To increase (to say 1500): sys.setrecursionlimit(1500) """ if not isinstance(list_of_lists...
def merge(ll, rl): """Merge two lists. :param ll: left list :param rl: right list :return: new list with ll and rl in ascending order. """ merged = [] l_idx, r_idx = 0, 0 while l_idx < len(ll) or r_idx < len(rl): if l_idx < len(ll): # Right index reached the end or l...
def primary_schema(search_path): """Return the first schema in the search_path. :param str search_path: PostgreSQL search path of comma-separated schemas :return: first schema in path :raise: ValueError """ search_path = search_path.strip() if not search_path: schemas = None els...
def set_array(input_data, array): """Return data wrapped in array if if array=True.""" if array: return [input_data] return input_data
def _strip_shell(cmd): """Strip a (potentially multi-line) command. For example $ foo \ > --bar baz \ > --quux 10 would becomes `foo --bar baz --quux 10`. """ parts = [] for line in cmd.strip().split("\n"): without_console = line.lstrip("$> ").rstrip("\\ ") ...
def reward(total_reward, percentage): """ Reward for a problem with total_reward done to percentage. Since the first a few test cases are generally very easy, a linear approach will be unfair. Thus, the reward is given in 20:80 ratio. The first 50% gives 20% of the reward, and the last 50% gives 8...
def cleanup_test_name(name, strip_tags=True, strip_scenarios=False): """Clean up the test name for display. By default we strip out the tags in the test because they don't help us in identifying the test that is run to it's result. Make it possible to strip out the testscenarios information (not to ...
def divide_by(array_list, num_workers): """Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return: """ for i, x in enumerate(array_list): array_list[i] /= num_workers return array_list
def clip_path(filepath): """ Clip path to get file name """ fileslist = filepath.split('/') return fileslist[-1]
def check_qcs_on_files(file_meta, all_qcs): """Go over qc related fields, and check for overall quality score.""" def check_qc(file_accession, resp, failed_qcs_list): """format errors and return a errors list.""" quality_score = resp.get('overall_quality_status', '') if quality_score.upp...
def remapE24(digit1, digit2): """The E24 series which includes E12 and E6 as subsets has a few values which do not map exactly to the mathematical values.""" e24_digit2 = digit2 if (digit1 == 2 and digit2 == 6 or digit1 == 3 or digit1 == 4): e24_digit2 += 1 elif digit1 == 8: ...
def except_keys(dic, keys): """Return a copy of the dict without the specified keys. :: >>> except_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]) {'B': 2} """ ret = dic.copy() for key in keys: try: del ret[key] except KeyError: pass return re...
def checkfname(fname, extension): """ Check if string ends with given extension ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fname String with file name extens...
def get_subdict(adict, keys): """ Get a sub-dictionary of `adict` with given `keys`. """ return dict((key, adict[key]) for key in keys if key in adict)
def weekday_name(day_of_week): """Return name of weekday. >>> weekday_name(1) 'Sunday' >>> weekday_name(7) 'Saturday' For days not between 1 and 7, return None >>> weekday_name(9) >>> weekday_name(0) """ day = { 1:"Sunday", 2:"Monday",...
def dir2text(mydir): """Convert a direction to its plain text equivalent""" if mydir is None: return "N" mydir = int(mydir) if mydir >= 350 or mydir < 13: return "N" elif mydir >= 13 and mydir < 35: return "NNE" elif mydir >= 35 and mydir < 57: return "NE" eli...
def topo_classes_subsets_defined_by_state_count(topo_classes_with_counts): """ Input: List: [x_i,x_2,...,x_n]; x_i = [t_i,c_i] = [topo_class_hash_i, count_of_states_i] Output: [ y_1,y_2,...,y_n]; y_i= [t_1,t_2,...t_n]; t_i= topo_class_hash; yi is constrained by sum(c_i)<= fixed amount ""...
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4): """ Compute the intersection point of two lines. Taken from https://stackoverflow.com/a/20679579 . Parameters ---------- x1 : number x coordinate of the first point on line 1. (The lines extends beyond this p...
def stringify(value): """ Escapes a string to be usable as cell content of a CSV formatted data. """ stringified = '' if value is None else str(value) if ',' in stringified: stringified = stringified.replace('"', '""') stringified = f'"{stringified}"' return stringified
def bottom_up_decomposite_n(n: int): """ bottom-up method for dynamic programming """ m = dict() for i in range(n+1): m[(i,i)] = 0 for i in range(1, int(n/2)+1): for j in range(i, n-i+1): total = 0 if j <= i: total = 0 ...
def shiftchunk(chunks, c, which, incr): """Shifts the 'which' endpoint of chunk 'c' by 'incr'. """ ret = [ch[:] for ch in chunks] ret[c][which] += incr last = ret[c][which] if which == 1: for w in range(c+1, len(ret)): oldi, oldj = i, j = ret[w] if i < la...
def lamb_blasius(re): """ Calculate friction coefficient according to Blasius. Parameters ---------- re : float Reynolds number. Returns ------- lamb : float Darcy friction factor. """ return 0.3164 * re ** (-0.25)
def sign(x): """Sign indication of a number""" return 1 if x > 0 else -1 if x < 0 else 0
def time_to_kobo(y, m, d='01', h='00', mi='00', s='00'): """Format timestamp for Kobo.""" y = str(y) m = str(m) d = str(d) h = str(h) mi = str(mi) s = str(s) return y + '-' + m + '-' + d + 'T' + h + ':' + mi + ':' + s + 'Z'
def dict_union(*dicts, merge_keys=['history', 'tracking_id'], drop_keys=[]): """Return the union of two or more dictionaries.""" from functools import reduce if len(dicts) > 2: return reduce(dict_union, dicts) elif len(dicts) == 2: d1, d2 = dicts d = type(d1)() # union ...
def is_empty_file(file_field): """ Return True if the given file field object passed in is None or has no filename Args: file_field (django.db.models.FileField or None): A file field property of a model object Returns: bool: True if the given file field object passed in is None or has ...
def odds(p): """ definition of odds ratio, without Laplace correction :param p: probability :param n: number of training instances :param k: cardinality of y :return: odds ratio """ assert 0 <= p <= 1, "Probability out of [0, 1]!" y = p / (1 - p) return y
def get_winner(board): """ finds out if there is a winner and who won """ def who_won(in_a_row, board_size, cur_player): """ a function private to get_winner() (yes you can do this. Cool huh!?) that tells get_winner if it has a winner """ if in_a_row == board_size: ...
def get_full_class_path(o): """Returns the full class path of an object""" module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ # Avoid reporting __builtin__ else: return module + '.' + o.__class__.__name__
def matrix_divided(matrix, div): """matrix """ if (not isinstance(matrix, list) or matrix == [] or not all(isinstance(row, list) for row in matrix) or not all((isinstance(col, int) or isinstance(col, float)) for col in [num for row in matrix for num in row])): ...
def factorial_loop(number): """ loop factorial """ result = 1 for x in range(2, number+1, 1): result *= x return result
def get_properties(value): """ Converts the specified value into a dict containing the NVPs (name-value pairs) :param value: :return: """ rtnval = None if isinstance(value, dict): # value is already a Python dict, so just return it rtnval = value elif '=' in value: ...
def get_micro_secs(real_str: str) -> int: """ If there is a decimal point returns fractional part as an integer in units based on 10 to minus 6 ie if dealing with time; real_str is in seconds and any factional part is returned as an integer representing microseconds. Zero returned if no factional part ...
def classify(instruction): """Classify instruction. Return name of instruction handler and arguments. """ if instruction in (0x00e0, 0x00ee): return f"op_{instruction:04x}", opcode = instruction >> 12 if 0 <= opcode <= 2: return f"op_{opcode}nnn", instruction & 0x0fff if 3...
def stringize(contents): """Convert contents into a valid C string, escaped if necessary""" contents = str(contents).rstrip().lstrip().replace('\\', '\\\\') contents = contents.replace('"', '\\"') return contents
def is_pos_idx(arg: int) -> bool: """Return True if arg matches positional index notation""" if not isinstance(arg, int): return False return bool(0 <= arg <= 63)
def version_param(params): """Return the value of the HTTP version parameter, or `None` if no version parameter is supplied. """ for k, v in params.items(): if k.lower() == "version": return v
def c_to_k(t_c): """Convert Celsius to Kelvin.""" if t_c is None: return None return t_c + 273.15
def get_img_extension(path: str) -> str: """ Parse the path and return the image's extension (replacing jpg to jpeg with accordance with EPUB spec) """ path_list = path.rsplit(".", 1) if len(path_list) == 2: ext = path_list[1] else: ext = "jpeg" if ext == "jpg": ext =...
def remove_stop_words(string, stop_words): """Sanitize using standard list comprehension""" return ' '.join([w for w in string.split() if w not in stop_words])
def check_win(word, guessed): """Returns True if every letter in word has been guessed, else False""" for letter in word: if letter not in guessed: return False return True
def intify_keys(d): """Convert string keys in a dictionary to integers""" return {int(k): v for k, v in d.items()}
def indexes(dic, keys=None): """ index dictionary by multiple keys Parameters ---------- dic : dict keys : list Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"}} >>> indexes(d,[1,'a']) 'A' """ keys = [] if keys is None else keys assert hasattr(dic, 'keys') ...
def default(row, index) -> str: """If a index out of range occurs return a empty string.""" if len(row) > index: return row[index] return ''
def sum_of_args(*args, **kwargs): """Sums the args, and returns a copy of kwargs with the sum of args added to each value. >>> sum_of_args(1,2,3, a=0, b=10) {'a': 6, 'b': 16} """ t = sum(args) return {k: t + v for k, v in kwargs.items()}
def get_index(i,j,num_of_nodes): """ give the row and column index, return the location in a matrix """ return (i*num_of_nodes+j)
def initialize_float_from_method_call(floatPtr, instance, mayThrowOnFailure): """Internal function to try converting 'instance' to a float. Args: floatPtr - a PointerTo(float) that we're supposed to initialize instance - something with a __float__method mayThrowOnFailure - if True, then...
def pkg_mount_type_to_string(_type): """ Converts the PKG_MOUNT_ TYPE_* contstants to a human readable string. """ if _type == 0: return "UNKNOWN" elif _type == 1: return "AMBIG" elif _type == 2: return "TH" elif _type == 3: return "SMT" else: return "*ERR(%s)*" % str(_type)
def format_float(numpy_float): """ Converts a numpy64 type to a formatted string. Ex: Input => numpy64(99999.6577) Output => '99,999.658' @param nupmy64 numpy_float: this is a first param @return: this is a description of what is returned """ python_float = numpy_float if not isinstanc...
def ternary_search(f, l, r, min_=True, maxiter=100, tol=1e-6): """Optimize f(x) using the ternary search f(x) is unimodal (only one optima) in a [l, r] """ i = 0 while r - l > tol and i < maxiter: # split (r - l) in 3 parts a = (l * 2 + r) / 3 # l + 1/3 * (r - l) b = (l + 2...
def get_elements(element=None, filename=None): """Get values for selected element from xml file specified in filename""" if filename is None or element is None: return [] import xml.dom.minidom import xml.parsers.expat try: dom = xml.dom.minidom.parse(filename) except IOError: ...
def bracket_sub (sub, comment=False): """ Brackets a substitution pair. Args: sub (tuple): The substitution pair to bracket. comment (bool): Whether or not to comment the bracketed pair. Returns: tuple: The bracketed substitution pair. """ if comment: return ('\(\*\s*...
def quick_clean(raw_str): """ args: - raw_str: a string to be quickly cleaned return - the original string w/ all quotes replaced as double quotes """ return raw_str.replace("''", '" ').replace("``", '" ').strip()
def get_names(rec_list): """ Gets the sequnece IDs from a sequence record list, returns a comma separated string of IDs """ return ", ".join([r["rec"].id for r in rec_list])
def consider(string, font=None): """ Error for command prompt Count=If count is needed, then you have to change countError to something else than None: assign countError to variable put before loop, which equals 1. After the warning you have to implement the incrementation of this va...
def validSpanishNumber(phone): """ Function intended to ensure phone is in spanish format: *** start w/ 9/8/6/7 *** total 9 numbers in format XXX XXX XXX """ try: if len(phone) != 11: return False for i in range(11): if i in [3,7]: ...
def save_class(cls): """ Save given class as a string. :type cls: type :rtype: str """ return '{0.__module__}.{0.__name__}'.format(cls)
def get_indicators(confidence, weights): """Takes a confidence number and a map from weights (confidences) to words with that weight. Returns a set of all words which have a confidence higher that <confidence>""" sorted_weights = weights.keys() sorted_weights = sorted(sorted_weights, reverse=True) i...
def get_event_ends(T_part, n_repeats): """get the end points for a event sequence, with lenth T, and k repeats - event ends need to be removed for prediction accuracy calculation, since there is nothing to predict there - event boundaries are defined by these values Parameters ---------- T_...
def init_game(n_rows, n_columns, red_discs, yellow_discs): """Init an empty game with some initial moves. Game is a 2D grid indexed from top left (0,0) to bottom right. """ game = [[" " for _ in range(n_columns)] for _ in range(n_rows)] for x, y in red_discs: game[x][y] = "R" for x, y...
def delegate(session_attributes, slots): """ Directs Amazon Lex to choose the next course of action based on the bot configuration. """ return { 'sessionAttributes': session_attributes, 'dialogAction': { 'type': 'Delegate', 'slots': slots } }
def duration_to_string(duration): """ Converts a duration to a string Args: duration (int): The duration in seconds to convert Returns s (str): The duration as a string """ m, s = divmod(duration, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s)
def hpa_to_mmhg(pressure: int) -> int: """ Converts pressure in hpa to mmhg Args: pressure: pressure to convert Returns: pressure in mmhg """ return int(pressure * 0.75006156130264)
def human_seconds(seconds, display='.2f'): """ Given `seconds` seconds, return human readable duration. """ value = seconds * 1e6 ratios = [1e3, 1e3, 60, 60, 24] names = ['us', 'ms', 's', 'min', 'hrs', 'days'] last = names.pop(0) for name, ratio in zip(names, ratios): if value / ...
def deep_get(target_dict, key_list, default_value=None): """ Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None :param target_dict: dictionary to...
def strip_indentation_whitespace(text): """Strips leading whitespace from each line.""" stripped_lines = [line.lstrip() for line in text.split("\n")] return "\n".join(stripped_lines)
def key2str(target): """ In ``symfit`` there are many dicts with symbol: value pairs. These can not be used immediately as \*\*kwargs, even though this would make a lot of sense from the context. This function wraps such dict to make them usable as \*\*kwargs immediately. :param target: `Mappin...
def document_keys(doc) : """Returns formatted strings of document keys. """ keys = sorted(doc.keys()) s = '%d document keys:' % len(keys) for i,k in enumerate(keys) : if not(i%5) : s += '\n ' s += ' %s' % k.ljust(16) return s #return '%d doc keys:\n %s' % (len(key...
def color_pixel(index): """ Color the vertex by its index. Note the color index must lie between 0-255 since gif allows at most 256 colors in the global color table. """ return max(index % 256, 1)
def update_vocab(vocab): """Add relevant special tokens to vocab.""" vocab_size = len(vocab) vocab["<unk>"] = vocab_size vocab["<s>"] = vocab_size + 1 vocab["</s>"] = vocab_size + 2 return vocab
def _patch_qichat_script(code): """ Apply modifications to old version qichat script to make it correspond to new behavior format files """ # for now, nothing to do more than the lstrip() made upper return code
def _is_bare_mapping(o): """Whether the object supports __getitem__ and __contains__""" return ( hasattr(o, '__contains__') and callable(o.__contains__) and hasattr(o, '__getitem__') and callable(o.__getitem__) )
def convert_to_bool(value_str: str) -> bool: """ Converts string values to their boolean equivalents. :param value_str: Value string. :return: The boolean value represented by `value_str`, if any. :raise: A ValueError if it is not possible to convert the value string to bool. """ conversion_...
def svg_icons_context_processor(request): """ Provide an empty set, that will be filled with the name of the icon, that was embedded. This is relevant for the svg_icon template tag. """ return {"_embedded_svg_icons": set()}
def split_package_name(p): """Splits the given package name and returns a tuple (name, ver).""" s = p.split('==') if len(s) == 1: return (s[0], None) else: return (s[0], s[1])
def has_no_jump(bigram, peaks_groundtruth): """ Tell if the two components of the bigram are same or successive in the sequence of valid peaks or not For exemple, if groundtruth = [1,2,3], [1,1] or [2,3] have no jump but [1,3] has a jump. bigram : the bigram to judge peaks_groundtruth : the lis...
def compare_range(value, window): """ Compare value with nagios range and return True if value is within boundaries :param value: :param window: :return: """ incl = False if window[0] == '@': incl = True window = window[1:] if ":" not in window: start = 0 ...
def mean(num_lst): """ Calculates teh mean of a list of numbers Parameters ---------- num_lst : list of int or float List of numbers to calculate the average of Returns ------- float of the average/mean of num_lst Examples -------- >>> mean([1, 2, 3, 4, 5]) 3.0 ...
def _merge_yaml(ret, data, profile=None): """ Merge two yaml dicts together at the misc level """ if 'misc' not in ret: ret['misc'] = [] if 'misc' in data: for key, val in data['misc'].items(): if profile and isinstance(val, dict): val['nova_profile'] = pr...
def numberOfChar(stringList): """ Returns number of char into a list of strings and return a int """ return sum(len(s) for s in stringList)
def DataSpeedUnit(speed): """ Convert data speed to the next best suited data size unit by Max Schmeling """ units = ['bps', 'Kbps', 'Mbps', 'Gbps'] unit = 0 while speed >= 1024: speed /= 1024 unit += 1 return '%0.2f %s' % (speed, units[unit])
def _get_links(previous, nexts, children): """Returns graphs edges between two subgraphs.""" links = {} for n in previous: next_children = [] if n not in nexts: next_children = [c.name for c in children.get(n, []) if c in nexts] if len(next_children) > 0: lin...
def mockServerAnswer(word: str, guess: str) -> str: """Function for development purposes""" ans = '' for letter in word: if letter == guess: ans = ans + '1' else: ans = ans + '0' return ans
def _desktop_escape(s): """Escape a filepath for use in a .desktop file""" escapes = {' ': R'\s', '\n': R'\n', '\t': R'\t', '\\': R'\\'} s = str(s) for unescaped, escaped in escapes.items(): s = s.replace(unescaped, escaped) return s
def generate_bounding_box_values(latitude, longitude, delta=0.01): """ Calculate a small bounding box around a point :param latitude: decimal latitude :param longitude: decimal longitude :param float delta: difference to use when calculating the bounding box :return: bounding box values in the ...
def validate_and_build_instance_fleets(parsed_instance_fleets): """ Helper method that converts --instance-fleets option value in create-cluster to Amazon Elastic MapReduce InstanceFleetConfig data type. """ instance_fleets = [] for instance_fleet in parsed_instance_fleets: instance_...
def indent_block(block, level=1): """ Indents the provided block of text. Args: block (str): The text to indent. level (int): The number of tabs to indent with. Returns: str: The indented block. """ tab = "\t" * level sep = "\n{:}".format(tab) return tab + sep.j...
def is_list(klass: type): """Determine whether klass is a List.""" return getattr(klass, "__origin__", None) == list
def _standard_pool_name(given_pool_name): """Return a standard memory pool name. The memory pool names could vary based on the garbage collector enabled. This function returns a standard name we could refer to. Available collectors : https://docs.oracle.com/en/java/javase/11/gctuning/available-col...
def get_completion_word(details): """Find the completed text from some Vim completion data. Args: details (dict[str, str]): Data that comes from Vim after completion finishes. For more information, check out Vim's help documentation. `:help v:completed_item`. Re...
def zero_matrix_no_numpy(matrix): """ First solution relying only on pure Python Scans through the matrix once, storing in sets the indices where zeroes have been detected (sets automatically remove duplicates). A second loop then zeroes the rows and cols as appropriate. Algo is O(M x N) which i...
def mergeDicts(dict1, dict2): """ Merges values from dict2 into dict1. If a key exists in both dictionaries, dict2 will overwrite dict1. """ res = {**dict1, **dict2} return res