content
stringlengths
42
6.51k
def flatten_argument(a): """Flatten the multiple lists generated by append and nargs in argparse""" if a: b = [elem for elements in a for elem in elements] else: b = a return b
def dict2opts(d): """ converts a dictionary to cmdline arguments prepends each key with -- and then optionally outputs the value """ opts = [] for key, value in d.items(): option = '--{}'.format(key) if value: option = '{}={}'.format(option, value) opts.app...
def dequote(string): """Remove quotes from around a string.""" if ((string.startswith('"') and string.endswith('"')) or (string.startswith("'") and string.endswith("'"))): return string[1:-1] else: return string
def calculate_age(year1: int, year2: int) -> int: """Find the difference between years (age).""" age = abs(year2 - year1) return age
def __prime_divisors(n): """ Calculates all prime divisors of n naively. """ candidate = 2 primes = [] while candidate <= n: if n % candidate == 0: primes.append(candidate) while n % candidate == 0: n /= candidate candidate += 1 ret...
def cmset_not(x,y): """ Usage: >>> cmset_not(x,y) returning the index of the elements of array x which are not present in the array y. This is equivalent to using the IDL command SET = CMSET_OP(A, 'AND', /NOT2, B, /INDEX) ; A but not B i.e. performs the same thing as the IDL routine cmset_op from http://cow.phys...
def beautify(text): """Cleanup and indent source file.""" indent = 0 blank = False list0 = [] # Remove extra empty lines and indent. lines = text.splitlines() for line in lines: strip = line.strip() if len(strip) == 0: if blank: continue ...
def millimetre_to_inch(val): """convert millimetres to inches :param float or list val: value to convert :returns: converted value :rtype: float or tuple """ try: return val / 25.4 except TypeError: return [x / 25.4 for x in val]
def getHexColor(red, green, blue): """ convert an (R, G, B) tuple to #RRGGBB """ hexcolor = '#%02x%02x%02x' % (int(red),int(green),int(blue)) # that's it! '%02x' means zero-padded, 2-digit hex values return hexcolor
def _token_str(token): """Shorten token so we do not leak sensitive info into the logs""" if len(token) < 10: # for some reason too short to reveal even a part of it return "???TOOSHORT" return token[:3] + '...'
def check_learnt(num_augments, augment_out, normalisation): """ Determine if there is a learnt component to the model. """ is_learnt = False if any([all([x is not None for x in (num_augments, augment_out)]), isinstance(normalisation, dict)]): is_learnt = True return is_learnt
def vcf_compress(output): """ Pipe stdout to vcf-sort/bgzip and then tabix """ return f" | vcf-sort | bgzip > {output} && tabix {output}"
def c_term_probability(modified_sequence): """ Returns the probability that C term AA was modified. """ if modified_sequence[-1] == ")": return float(modified_sequence[:-1].split("(")[-1]) else: return 0.0
def keysort(keylist): """ Sort a list of (instrument, channel_number) keys where the channel numbers are sorted numerically rather than alphabetically. """ newlist = [(inst, int(chan)) for (inst, chan) in keylist] newlist.sort() return [(inst, str(chan)) for (inst, chan) in newlist]
def copy_bits(v, s, e=-1): """ Copy bits from a value @param v: the value @param s: starting bit (0-based) @param e: ending bit """ # end-bit not specified? use start bit (thus extract one bit) if e == -1: e = s # swap start and end if start > end if s > e: e, s =...
def dict_list2tuple(dict_obj): """ Convert all list element in the dict to tuple """ for key, value in dict_obj.items(): if isinstance(value, dict): for inner_key, inner_v in value.items(): if isinstance(inner_v, list): # empty or None list, mainly for met...
def make_file_rootname(lasfile): """ make a file 'root name' from an input file path input: - a path to an input file (string) output: - a string containing the file name minus extension, assuming the extension is 4 characters long """ filebits = lasfile.split("/") infilename =...
def indices(x_list, v_list, include=True): """ Get indices of elements in x_list which are (not) included in the v_list Args: x_list: the target list v_list: (list of) values include: x_list includes each value or not """ if not isinstance(v_list, list): v_list = [v_list]...
def Q(name: str, quote: str = '"') -> str: """Quote name by adding leading and trailing (double) quote. Args: name (str): name of table or column. quote (str): str to quote with. Returns: str: Quoted name """ return f'{quote}{name}{quote}'
def version_leq(lhs, rhs): """Returns True if version `lhs` is earlier or equal to `rhs`.""" def _try_cast(val): val = val.strip() try: return int(val) except ValueError: return val # remove git version suffixes if present lhs = lhs.split("+", 1)[0] ...
def _is_sequence(arg): """ true if list """ return (not hasattr(arg, "strip") and hasattr(arg, "__getitem__") or hasattr(arg, "__iter__"))
def yuv420sp_size(width, height): """ return yuv420sp size """ return int(width * height * 3 / 2)
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ if len(s) == 0: return 0 maxCounter = 1 currentCounter = 1 currentList = s[0] for i in range(1, len(s)): if s[i] in currentList: # means it's a reptition. i.e. update header (reference from ...
def ackermann(m: int, n: int) -> int: """Implement Ackermann function recursively. Raise: - TypeError for given non integers - ValueError for given negative integers """ if type(m) is not int or type(n) is not int: raise TypeError("m and/or n isn't integer") if m < 0 or n < 0: ...
def add_user_tag(f): """Adds my GitHub username as an attribute ``__user_tag__`` to ``f``. :param f: Function to decorate :type f: function :rtype: function """ f.__user_tag__ = "phetdam" return f
def identify_leaf(exp): """ Find an expression with no parentheses within it that can be resolved. """ for i in range(len(exp)): if exp[i] == "(": for j in range(i+1, len(exp)): if exp[j] == "(": break if exp[j] == ")": ...
def natural_sort(l): """ Returns alphanumerically sorted input #natural sort from the interwebs (http://stackoverflow.com/questions/11150239/python-natural-sorting) """ import re convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [convert(c) for c...
def delete(server_id, **kwargs): """Delete server.""" url = '/servers/{server_id}'.format(server_id=server_id) return url, {}
def _linear_matrix_diagonal_index(ell, mpm): """Index of array corresponding to matrix diagonal element This gives the index based at the first element of the matrix, so if the array is actually a series of matrices (linearized), then that initial index for this matrix must be added. This assumes ...
def around(number): """ Truncate a float to the third decimal """ if number is not None: return int(number * 1000) / 1000. else: return None
def get_train_valid_test_split_(splits_string, size): """ Get dataset splits from comma or '/' separated string list.""" splits = [] if splits_string.find(',') != -1: splits = [float(s) for s in splits_string.split(',')] elif splits_string.find('/') != -1: splits = [float(s) for s in sp...
def make_dict(segments): """Create a dictionary giving an id number for each segment.""" dict_segments = {} for seg in segments: dict_segments[segments.index(seg)] = seg return dict_segments
def point_inside_circle(x,y,center_x,center_y,radius): """Check if a point is inside a circle. Args: x (float): x coordinate of the point. y (float): y coordinate of the point. center_x (float): x coordinate of the center of the circle. center_y (float): y coordinate of the cent...
def getSorteScoresFromScoreDict(queryRunDict): """Take a dictionary of document scores indexed by the document id and produce a list of (document id, score tuples) sorted in the order of decreasing scores. :param queryRunDict: a single-query run info in the dictionary format. """ return list(...
def depth(index: int, text: str): """ Determine depth of scope at a character index. Return 0 if not inside any scope. Note that braces found inside comments or literals are not ignored and will be counted. Note that a scope does not have to be properly balanced for this to return its dept...
def SumString(table : list) -> str: """ Connects all the strings in the list to a single string, optimal for the output of JLua.GetLuaString() :param table: A string list like generated by readlines() or GetLuaString() :return: The Connected string """ sumstring = "" for string in t...
def to_lower(impression): """ """ return impression.lower()
def convert_bool(s): """Convert input string to boolean. Input string must either be ``True`` or ``False``. """ if s == "True": return True elif s == "False": return False else: raise ValueError("Cannot convert bool: %r" % s)
def parse_reg_00h_and_01h_bytes(byte_val_3: int, byte_val_4: int) -> int: """Module address""" assert 0 <= byte_val_3 < 256 assert 0 <= byte_val_4 < 256 # module address has 16 bit = 2 byte # byte_val_3 are high bits of module address # byte_val_4 are low bits of module address # shifting by...
def _f_lcs(llcs, m, n): """ Computes the LCS-based F-measure score Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf :param llcs: Length of LCS :param m: number of words in reference summary :param n: number of words in candidate summar...
def to_grafana_refid(number): """Convert a number to a string starting at character a and incrementing. This only accounts for a to zz, anything greater than zz is probably too much to graph anyway.""" character1 = '' idx = -1 while number > 25: idx = idx + 1 number -= 26 else: ...
def call_if_callable(func, *args, **kwargs): """Call the function with given parameters if it is callable""" if func and callable(func): return func(*args, **kwargs) return None
def cp_binary_filename(file_name, nexus_ordering = True): """Returns a version of the file name with extension adjusted to indicate reseq order and pure binary.""" if file_name[-9:] == '.reseq.db': root_name = file_name[:-9] elif file_name[-3:] == '.db': root_name = file_name[:-3] else:...
def fibonacci(n): """ Return pair of Fibonacci numbers, F(n) and F(n-1). """ if n <= 1: return (n, 0) else: (a, b) = fibonacci(n-1) print(a, b) return (a+b, a)
def groupby_type(resources): """Groups terraform resources by type in order of arg keys""" groups = {} types = set([item["type"] for item in resources]) for t in types: grouped_items = [item for item in resources if item["type"] == t] groups[t] = grouped_items return groups
def overlap(interval1, interval2): """ Returns the total amount of overlap between two intervals in the format of (x,y) Example: input: (0,10) , (5,10) returns: 5 """ return max(0, min(interval1[1], interval2[1]) - max(interval1[0], interval2[0]))
def verify_request_target(replay_json, request_target): """ Verify that the 'url' element of the first transaction contains the request target. """ try: url = replay_json['sessions'][0]['transactions'][0]['client-request']['url'] except KeyError: print("The replay file did not have a...
def check_preconditions(key, value): """ Check if the filter applies to the current element in the syntax tree. :param key: The type of pandoc object. :type key: str :param value: The contents of the object. :type value: list | str :return: ``True`` if the filter applices to the current ele...
def find_disappeared_numbers(nums): """ :type nums: List[int] :rtype: List[int] """ for i in range(len(nums)): index = abs(nums[i]) - 1 nums[index] = - abs(nums[index]) return [i + 1 for i in range(len(nums)) if nums[i] > 0]
def capStrLen(s: str, length: int) -> str: """ Truncates a string to a certain length. Adds '...' if it's too long. Parameters ---------- s : str The string to cap at length l. length : int The maximum length of the string s. """ if length <= 2: raise Except...
def combine(dict1, dict2): """ update in place """ dict1.update(dict2) return dict1
def is_unique_no_ds(sentence): """ Complexity: O(n) time, O(1) space """ x = 0 for c in sentence: if x & (1 << ord(c)) != 0: return False x += 1 << ord(c) return True
def issequence(obj): """ True if given object is a list or a tuple. """ return isinstance(obj, (list, tuple))
def _aggregate_counts(child_counts): """Return aggregated node count as int.""" if not child_counts: return 1 elif len(child_counts) == 1: return child_counts[0] elif len(child_counts) == 2: return child_counts[0] * child_counts[1] else: raise ValueError
def get_properties(obj): """ Returns a list of properties for L{obj} @since: 0.5 """ if hasattr(obj, 'keys'): return obj.keys() elif hasattr(obj, '__dict__'): return obj.__dict__.keys() return []
def extract(s, delimit="-", num=0): """Extract the num_th word from string s Args: s (str): string to be parsed delimit (str, optional): delimiter. Defaults to "-". num (int, optional): . Defaults to 0. Returns: (str, List[str]) """ s_list = s.split(delimit) fir...
def valid(records): """Returns True if all records in the set are valid.""" return all(record.valid() for record in records)
def remove_decorator(srccode: str, decorator: str) -> str: """remove decorator from return value of `inspect.getsource`. :param srccode: return value of `inspect.getsource` :param decorator: remove target ex: '@snippet' :return srccode_without_decorator: srccode removed decorator """ # no decora...
def __get_avr_float(section, name1, name2): """Get the forecasted float from json section.""" try: val1 = float(section[name1]) except (ValueError, TypeError, KeyError): val1 = None try: val2 = float(section[name2]) except (ValueError, TypeError, KeyError): val2 = Non...
def solve_equations(func, derived_func,close_enough, guess): """ Generic equation solver using newton Raphson func : Function f(x), we are trying to solve f(x) = = derived_func: f'(x) close_enough: validation """ f = func(guess) df = derived_func(guess) cl = close_enough(guess) new_guess = guess - f / df i...
def sub_ranges(max_n, max_ranges): """ Calculate equal ranges for a maximum number. :returns: list of equal ranges. """ ranges = [] range_len = max_n // max_ranges for i in range(max_ranges): ranges.append((i*range_len, i*range_len + range_len - 1)) return ranges
def dict_to_les_stats_file(file_dict: dict, log_path: str) -> bool: """ Turns a dictionary into a delphin les stats file. :param file_dict: Dictionary holding the information for the les stats file :param log_path: Path to were the les stats file should be written :return: True """ file_ob...
def get_mean(lis): """ returns the mean of the items in a list """ return sum(lis)/len(lis)
def unique_counts(data_set): """ Gets the unique counts of the number each target class """ results = {} for feature in data_set: target = feature[-1] if target not in results: results[target] = 0 results[target] += 1 return results
def string_to_number(s): """ Convert a bytes string into a single number. Example: >>> string_to_number('foo bar baz') 147948829660780569073512294 """ return int.from_bytes(s.encode(), "little")
def tmap(function, *iterables): """ >>> tmap(pow, (2, 3, 10), (5, 2, 3)) (32, 9, 1000) """ return tuple(map(function, *iterables))
def solution(n): """Returns the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(20) 232792560 >>> solution(22) 232792560 >>> solution(3.4) 6 >...
def get_filename_from_url(url): """Get the filename from a URL. Args: url (str): URL Returns: str: Filename of the URL. """ return url[url.rfind('/') + 1:]
def construct_chains_list(num_monos,construction="segregation"): """ Create list of tuples for chains """ if construction == "single": chains_list=[(0,num_monos,0)] print("chain construction is 'single'") elif construction == "ring": chains_list=[(0,num_monos,1)] ...
def parsePoint(storedPt): """ Translates a string of the form "{1, 0}" into a float tuple (1.0, 0.0) """ return tuple(float(c) for c in storedPt.strip("{}").split(","))
def _max_1d(nums): """Find max in 1D array.""" max_col = 0 max_num = nums[0] for i in range(1, len(nums)): if nums[i] > max_num: max_col = i max_num = nums[i] return max_col, max_num
def create1D(length, value=None): """ Create and return a 1D array containing length elements, each initialized to value. """ return [value] * length
def is_even(k): """Solution to exercise R-1.2. Takes an integer value and returns True if k is even, and False otherwise. However, the function cannot use the multiplication, modulo, or division operators. """ k_str = str(k) last_digit = int(k_str[-1]) return last_digit in [0, 2, 4, 6, ...
def normal_shock_stag_pressure_ratio(M, *args): """Gives the normal shock stagnation pressure ratio as a function of upstream Mach number.""" gamma = args[0] a = (0.5*(gamma+1.0)*M)**2.0 b = a/(1.0+0.5*(gamma-1.0)*M**2.0) c = b**(gamma/(gamma-1.0)) d = 2.0/((gamma+1.0)*(gamma*M**2-0.5*(gamma-1....
def format_message_response(params): """ Format automatic response |params| is None if the system can't process the user's message or is not confident enough to give a response. Otherwise, |params| is a triple that consists of the question that the system is trying to answer, the response it...
def average(iterable): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 >>> print average([1, 2, 3]) 2.0 """ return sum(iterable, 0.0) / len(iterable)
def calcMimeType(request): """ This method generate mime-type of response by given <request>. :param dict request: :return str: """ return 'text/javascript' if request['method']=='GET' else 'application/json'
def extract_intervals(request_history): """ Extract the continuous (start, end) intervals during which network IO happend. Summing the duration of those intervals gives the total API call time as perceived by the end-user (taking into account parallel requests using concurrency features). """ i...
def percentiles_from_counts(counts_dt, percentiles_range=None): """Returns [(percentile, value)] with nearest rank percentiles. Percentile 0: <min_value>, 100: <max_value>. counts_dt: { <value>: <count> } percentiles_range: iterable for percentiles to calculate; 0 <= ~ <= 100 Source: https://stackov...
def index(tup, ind): """ Fancy indexing with tuples """ return tuple(tup[i] for i in ind)
def lmap(func, lis): """Python2/3 compatibility: replace map(int, list) with lmap(int, list) that always returns a list instead of an iterator. Otherwise conflicts with np.array in python3. """ return list(map(func, lis))
def source_and_offset(source): """Return a source and offset from a source description. >>> source_and_offset("hello, _|_world") ("hello, world", 7) >>> source_and_offset("_|_hello, world") ("hello, world", 0) >>> source_and_offset("hello, world_|_") ("hello, world", 12) """ offset ...
def is_group(group): """Return ``True`` if passed object is Group and ``False`` otherwise.""" return type(group).__name__ == "Group"
def time_to_human(seconds): """ Convert time in seconds to human readable format. :returns: a string of the form "DD days, HH hours, MM minites and SS seconds". """ assert seconds >= 0 #number of seconds should be nonnegative dd = int(seconds) // 86400 # days hh = (int(seconds) // 3...
def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin """ return round(rankine...
def listify(obj): """ Given an object, return a list. Always returns a list. If obj is None, returns empty list, if obj is list, just returns obj, otherwise returns list with obj as single member. Returns: list: You guessed it. """ if obj is None: return [] else: ...
def _uptime(seconds): """Return uptime string. Args: seconds: Seconds of uptime Returns: result: Uptime string """ # Initialize key variables (minutes, remainder_seconds) = divmod(seconds/100, 60) (hours, remainder_minutes) = divmod(minutes, 60) (days, remainder_hours)...
def units_info(units): """Make the units taken from a file LaTeX math compliant. This function particularly deals with powers: e.g. 10^22 J """ components = units.split() exponent = None pieces = [] for component in components: index = component.find('^') if not ...
def _norm_slice(sl, start, stop): """Return a slice normalized to an farray start index.""" length = stop - start if sl.start is None: normstart = 0 else: if sl.start < 0: if sl.start < -length: normstart = 0 else: normstart = sl.st...
def _instance_key(instance): """ Returns a unique value for each valid instance of this check. The uptime_log_directory must be unique for each instance of the check, so we just use that. """ return instance['uptime_log_directory']
def smoothstep(t: float) -> float: """Smooth curve with a zero derivative at 0 and 1, making it useful for interpolating.""" return t * t * (3. - 2. * t)
def _expand_for_carryover(max_vol, plan, **kwargs): """ Divide volumes larger than maximum volume into separate transfers """ max_vol = float(max_vol) carryover = kwargs.get('carryover', True) if not carryover: return plan new_transfer_plan = [] for p in plan: source = p[...
def first_value(d): """get the first value of a dict""" return list(d.values())[0]
def _get_coord_shift(ndim, nprepad=0): """Compute target coordinate based on a shift. Notes ----- Assumes the following variables have been initialized on the device:: in_coord[ndim]: array containing the source coordinate shift[ndim]: array containing the zoom for each axis compu...
def get_user_id_from_token(jwt_identity): """ Extract the user ID from a JSON web token (after the token has been decrypted) :param jwt_identity: string containing user ID in the form: 'user_id=<user_id>' :return: user ID """ return int(jwt_identity.split('=')[1])
def get_item(dictionary, key): """Return value from dictionary. Args: dictionary (dict): Dictionary to retrieve value from. key (str): Key to perform lookup. Returns: Value of key in dictionary. """ return dictionary.get(key)
def get_tablename(stations): """ Figure out the table that has the data for these stations """ states = [] for sid in stations: if sid[:2] not in states: states.append(sid[:2]) if len(states) == 1: return "alldata_%s" % (states[0],) return "alldata"
def extract_http_tags(event): """ Extracts HTTP facet tags from the triggering event """ http_tags = {} request_context = event.get("requestContext") path = event.get("path") method = event.get("httpMethod") if request_context and request_context.get("stage"): if request_context....
def __is_descriptor__(obj: object) -> bool: """ Function to check if item is a descriptor (has ``__get__``, ``__set__`` or ``__delete__`` methods) :param obj: Object to check :return: Boolean depicting if object is a descriptor or not """ return hasattr(obj, '__get__') or hasattr(obj, '__set__'...
def diff(new_output, stable_output): """Get difference between the two dictionaries' keys. Args: new_output (fixture): A dictionary of the objects and values of the current state of getting_started. The object names are the keys of the dictionary. stable_output (fixture): A dic...