content
stringlengths
42
6.51k
def display_seconds(seconds: int, granularity: int = 1): """Display seconds as a string in hours, minutes and seconds Args: seconds: number of seconds to convert granularity: level of granularity of output Returns: string containing seconds in hours, minutes and seconds """ intervals = { "hours": 3600, "minutes": 60, "seconds": 1, } result = [] for name in intervals: count = intervals[name] value = seconds // count if value: seconds -= value * count if value == 1: name = name[:-1] result.append(f"{value} {name}") return ", ".join(result[:granularity])
def calc_type(a: int, b: int, res: int) -> str: """Find the calculation type by the result. Examples: >>> assert calc_type(10, 2, 5) == 'division' """ return { a - b: 'subtraction', a + b: 'addition', a / b: 'division', a * b: 'multiplication', }[res]
def np_list_remove(cols, colsremove, mode="exact"): """ """ if mode == "exact": for x in colsremove: try: cols.remove(x) except BaseException: pass return cols if mode == "fuzzy": cols3 = [] for t in cols: flag = 0 for x in colsremove: if x in t: flag = 1 break if flag == 0: cols3.append(t) return cols3
def average(values): """calculates average from a list""" try: return float(sum(values) / len(values)) except ZeroDivisionError: return 0
def find_ar_max(_ar, _ib=0, _ie=-1, _min=False): """ Finds array (or list) maximum (or minimum), index and value :param _ar: array (or list) to find max. or min. :param _ib: array index to start search :param _ie: array index to finish search :param _min: switch specifying that minimum (rather than maximum) has to be searched """ strErIncorArray = 'Incorrect input array.' if(_ar is None): raise Exception(strErIncorArray) nTot = len(_ar) if(nTot <= 0): raise Exception(strErIncorArray) iBeg = _ib if(_ib < 0): iBeg = 0 iEnd = _ie if((iEnd == -1) or (_ie >= nTot)): iEnd = nTot - 1 if(iEnd < iBeg): raise Exception('Incorrect definition of start and end indexes.') curExtr = _ar[0] curInd = 0 for i in range(iBeg, iEnd + 1, 1): curVal = _ar[i] if(_min == True): curVal *= -1 if(curExtr < curVal): curExtr = curVal curInd = i return curExtr, curInd
def mutable_two(nums): """ Uses built-in max() method and extra storage. """ if len(nums) < 2: raise ValueError('Must have at least two values') idx = max(range(len(nums)), key=nums.__getitem__) my_max = nums[idx] del nums[idx] second = max(nums) nums.insert(idx, my_max) return (my_max, second)
def indent_lines( text: str ) -> str: """Indent the lines in the specified text.""" lines = text.splitlines() indented_lines = [f' {line}' for line in lines] return '\n'.join(indented_lines)
def divide(n, iterable): """split an iterable into n groups, per https://more- itertools.readthedocs.io/en/latest/api.html#grouping. :param int n: Number of unique groups :param iter iterable: An iterable to split up :return: a list of new iterables derived from the original iterable :rtype: list """ seq = tuple(iterable) q, r = divmod(len(seq), n) ret = [] for i in range(n): start = (i * q) + (i if i < r else r) stop = ((i + 1) * q) + (i + 1 if i + 1 < r else r) ret.append(iter(seq[start:stop])) return ret
def _create_stage_table_command(table_name, target_table, selected_fields="*"): """ Create an redshift create temporary table command. Notes: - CREATE TABLE AS command does not inherits "NOT NULL" - CREATE TABLE LIKE statement also inherits sort key, distribution key. But the main point to to note here that, CREATE TABLE LIKE command additionally inherits "NOT NULL" settings from the source table that CREATE TABLE AS does not seealso: https://docs.aws.amazon.com/pt_br/redshift/latest/dg/r_CREATE_TABLE_AS.html seealso: https://docs.aws.amazon.com/pt_br/redshift/latest/dg/r_CREATE_TABLE_AS.html """ copy_command = ("""CREATE TEMPORARY TABLE {} AS SELECT {} FROM {} WHERE 1 = 0;""").format( table_name, selected_fields, target_table ) return copy_command
def parse_create_table(sql): """ Split output of SHOW CREATE TABLE into {column: column_spec} """ column_types = {} for line in sql.splitlines()[1:]: # first line = CREATE TABLE sline = line.strip() if not sline.startswith("`"): # We've finished parsing the columns break bits = sline.split("`") assert len(bits) == 3 column_name = bits[1] column_spec = bits[2].lstrip().rstrip(",") column_types[column_name] = column_spec return column_types
def in_seconds(days=0, hours=0, minutes=0, seconds=0): """ Tiny helper that is similar to the timedelta API that turns the keyword arguments into seconds. Most useful for calculating the number of seconds relative to an epoch. >>> in_seconds() 0 >>> in_seconds(hours=1.5) 5400 >>> in_seconds(hours=3) 10800 >>> in_seconds(minutes=30) 1800 >>> in_seconds(hours=3, minutes=30, seconds=10) 12610 >>> in_seconds(days=1) 86400 >>> in_seconds(days=3, hours=10) 295200 """ return int((days * 86400) + (hours * 3600) + (minutes * 60) + seconds)
def sextodec(xyz, delimiter=None): """Decimal value from numbers in sexagesimal system. The input value can be either a floating point number or a string such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " " can be specified using the keyword ``delimiter``. """ divisors = [1, 60.0, 3600.0] xyzlist = str(xyz).split(delimiter) sign = 1 if "-" in xyzlist[0]: sign = -1 xyzlist = [abs(float(x)) for x in xyzlist] decimal_value = 0 for i, j in zip(xyzlist, divisors): # if xyzlist has <3 values then # divisors gets clipped. decimal_value += i / j decimal_value = -decimal_value if sign == -1 else decimal_value return decimal_value
def char_preprocess(texto, chars_inserted = []): """ DESCRIPTION: Normalizes some characters and adds . to headings INPUT: texto <string> - Text to be treated chars_inserted <list> - Positions of the chars inserted in the text OUTPUT: Returns the processed text """ #'.' = 46 #'\t' = 9 #'\n' = 10 #'\v' = 11 #'\f' = 12 #'\r' = 13 #' ' = 32 #'\xc2\xa0' = 160 text = list(texto) newline = [10, 11, 13] spaces = [9, 11, 32, 160] last_ch = 0 nl_flag = 0 nl_pos = -1 len_text = len(text) last_ch_pos = 0 for i in range(len(text) - 1): val = ord(text[i]) #print val, chr(val) #if val == 0: #Null character # text[i] = ' ' if val == 160: if i - 1 >= 0 and ord(text[i - 1]) in spaces: text[i - 1] = '.' text[i] = ' ' elif i + 1 <= len_text and ord(text[i + 1]) in spaces: text[i + 1] = ' ' text[i] = '.' else: text[i] = ' ' elif val in newline and last_ch != 46: nl_flag = 1 nl_pos = i elif val <= 32: text[i] = ' ' else: if text[i].isalnum(): if nl_flag == 1 and val >= 41 and val <= 90:#Upper case text[nl_pos] = '.' #text[last_ch_pos + 1] = '.' if ord(text[nl_pos + 1]) not in spaces: text.insert(nl_pos + 1, ' ') chars_inserted.append(nl_pos + 1) nl_flag = 0 else: nl_flag = 0 last_ch = ord(text[i]) last_ch_pos = i return ''.join(text)
def _offset_rounding_error(figure): """ """ fig = [] pre_part = [] for line in figure: if not pre_part == []: fig.append((pre_part[3], line[1], line[2], line[3])) else: fig.append(line) pre_part = line return fig
def lines_to_text(receipt_lines): """ :param receipt_lines: takes a dictionary as input, where the key is a line_id and the value are objects containing the element text and bounding polygon :return: A list of text strings concatenated for each line, instead of google vision objects """ receipt_text = [] for line in receipt_lines: text = "" for item in receipt_lines[line]: # Get descriptions, strip leading hashtags and asterixs text += " " + item.description.strip("#").lstrip("*") receipt_text.append(text.lower().strip()) return receipt_text
def node_dict(nodes): """ :param nodes: :return: dict of frozenset(labels) to list(nodes) """ d = {} for node in nodes: key = frozenset(node.labels) d.setdefault(key, []).append(node) return d
def sizeof_fmt(num, suffix='B'): """ Converts byte size to human readable format """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def compare_users(user1, user2): """Comparison util for ordering user search results.""" # Any verified user is ranked higher if user1["is_verified"] and not user2["is_verified"]: return -1 if user2["is_verified"] and not user1["is_verified"]: return 1 return 0
def is_float(string): """ is the given string a float? """ try: float(string) except ValueError: return False else: return True
def post_process_remote_resources(resources): """ Process resources list from uframe before returning for display (in UI). """ try: if not resources: return resources for resource in resources: if '@class' in resource: del resource['@class'] return resources except Exception as err: message = 'Error post-processing event for display. %s' % str(err) raise Exception(message)
def to_asciihex(b): """ Convert raw binary data to a sequence of ASCII-encoded hex bytes, suitable for import via COPY .. CSV into a PostgreSQL bytea field. """ return '\\x'+''.join('%.2x' % ord(x) for x in b)
def asp_convert(string): """ Convert the given string to be suitable for ASP. Currently this means replacing - with _. It is a bit unsafe in that if name exist that are identical except one has a - and one has a _ in the same place, then this wont catch it, but if you do that stuff you. (str) -> str """ return string.replace("-", "__").lower()
def etag_matches(etag, tags): """Check if the entity tag matches any of the given tags. >>> etag_matches('"xyzzy"', ['"abc"', '"xyzzy"', 'W/"woof"']) True >>> etag_matches('"woof"', ['"abc"', 'W/"woof"']) False >>> etag_matches('"xyzzy"', ['*']) True Note that you pass quoted etags in both arguments! """ for tag in tags: if tag == etag or tag == '*': return True return False
def fpr_score(conf_mtx): """Computes FPR (false positive rate) given confusion matrix""" [tp, fp], [fn, tn] = conf_mtx r = tn + fp return fp / r if r > 0 else 0
def separate_seq_and_el_data(line): """ Takes a string containing a nucleotide sequence and its expression level (el) - tab separated - and returns the sequence as a string and the expression level as a float. Args: ----- line (str) -- the input line containing the sequence and expression level (tab separated) to be separated. Returns: ----- seq (str) -- the nucleotide sequence. exp_level (float) -- the expression level of the sequence. """ # Assertions assert isinstance(line, str), 'Input line must be passed as a string.' # Functionality data = line.rstrip().split('\t') seq = data[0] try: exp_level = float(data[1]) except IndexError: raise IndexError('Input line must have the sequence and expression\ level tab separated.') return seq, exp_level
def mem_format(memory, ratio=1.0): """Convert memory in G to memory requirement. Args: memory: Memory size in G. ratio: The percent that can be used. Returns: Formatted string of memory size if memory is valid, None otherwise. """ try: memory = float(memory) except: return None else: return "%dM" % int(ratio * memory * 1024)
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}): """ task 0.5.9 comprehension whose value is the intersection of setA and setB without using the '&' operator """ return {x for x in (setA | setB) if x in setA and x in setB}
def replace(original, old_word, new_word): """ If new_word is in original, this function will replace old_word with new_word. """ ans = '' for i in range(len(original)): if new_word == original[i]: ans += new_word else: ans += old_word[i] return ans
def extract_file_name(line: str): """ Extract the file name from a line getting by a line of string that contains a directory like `/path/to/file`, where `file` will be extracted. :param line: A line of string :return: The extracted tuple of absolute path and filename """ start_idx = line.rfind('hdfs://') if start_idx == -1: absolute_path = line else: absolute_path = line[start_idx:] idx = absolute_path.rfind('/') filename = absolute_path[idx + 1:] if filename.startswith('.'): return None, None return absolute_path, filename
def IsStringInt(string_to_check): """Checks whether or not the given string can be converted to a integer. Args: string_to_check: Input string to check if it can be converted to an int. Returns: True if the string can be converted to an int. """ try: int(string_to_check) return True except ValueError: return False
def fizz_buzz(int_number): """ Return fizz if number is a multiple of 3 Return buzz if number is a multiple of 5 Return fizzbuzz if number is a multiple of 3 and 5 Else return the number If the number is NOT a number, then raise a ValueError """ # don't work with non-numeric input if not isinstance(int_number, int): raise ValueError("int_number must be an integer") # got a number! if int_number % 3 == 0 and int_number % 5 == 0: return 'fizzbuzz' elif int_number % 3 == 0: return 'fizz' elif int_number % 5 == 0: return 'buzz' else: return int_number
def doc2str(document): """ document: list of list [n_sent, n_word] """ document = [" ".join(d) for d in document] return "\n".join(document)
def capturing(pattern): """ generate a capturing pattern :param pattern: an `re` pattern :type pattern: str :rtype: str """ return r'({:s})'.format(pattern)
def bold_large_p_value(data: float, format_string="%.4f") -> str: """ Makes large p-value in Latex table bold :param data: value :param format_string: :return: bolded values string """ if data > 0.05: return "\\textbf{%s}" % format_string % data return "%s" % format_string % data
def check_clockwise(vertices): """Checks whether a set of vertices wind in clockwise order Adapted from http://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order Args: vertices (list): A list of [x,y] vertices Returns: bool indicating if the points wind in a clockwise order """ tot = 0 nv = len(vertices) i = nv - 1 j = 0 while j < nv: tot += (vertices[j][0] - vertices[i][0]) * (vertices[j][1] + vertices[i][1]) i = j j += 1 return tot > 0
def _add_missing_parameters(flattened_params_dict): """Add the standard etl parameters if they are missing.""" standard_params = ['ferc1_years', 'eia923_years', 'eia860_years', 'epacems_years', 'epacems_states'] for param in standard_params: try: flattened_params_dict[param] except KeyError: flattened_params_dict[param] = [] return flattened_params_dict
def append_update_post_field_to_posts_list(d_included, l_posts, post_key, post_value): """Parse a dict and returns, if present, the desired value. Finally it updates an already existing dict in the list or add a new dict to it :param d_included: a dict, as returned by res.json().get("included", {}) :type d_raw: dict :param l_posts: a list with dicts :type l_posts: list :param post_key: the post field name to extract. Example: 'author_name' :type post_key: str :param post_value: the post value correspoding to post_key :type post_value: str :return: post list :rtype: list """ elements_current_index = len(l_posts) - 1 if elements_current_index == -1: l_posts.append({post_key: post_value}) else: if not post_key in l_posts[elements_current_index]: l_posts[elements_current_index][post_key] = post_value else: l_posts.append({post_key: post_value}) return l_posts
def get_stat_name(stat): """ Returns the stat name from an integer """ if stat == 2: return "attackdamage" elif stat == 10: return "maximumhealth"
def is_callable(value): """Returns whether the value is callable.""" return hasattr(value, '__call__')
def is_receiver(metric): """Is interface ``metric`` a receiver? :param dict metric: The metric. :rtype: :py:class:`bool` """ return metric.get("name", "").endswith("rx")
def acceptable_word(word, stopwords): """Checks conditions for acceptable word: length, stopword.""" accepted = bool(2 <= len(word) <= 40 and word.lower() not in stopwords) return accepted
def sort_by_value(d,reverse=False): """ One of many ways to sort a dictionary by value. """ return [(k,d[k]) for k in sorted(d,key=d.get,reverse=reverse)]
def line_to_type(fobject_or_string, d_type=str, no_split=False): """ Grab a line from a file like object or string and convert it to d_type (default: str). Parameters ---------- fobject_or_string : object A file like object or a string containing something that is to be converted to a specified type dtype : object The dtype one want to convert to. The standard Python dtypes are supported. no_splot : bool If True do not split a string. Useful for comments etc. We still strip. """ if isinstance(fobject_or_string, str): line = fobject_or_string else: line = fobject_or_string.readline() # Previously this was map instead of list comprehension if not no_split: result = [d_type(item) for item in line.split()] else: result = line.strip() if len(result) == 1: return result[0] return result
def comma_separated_list(value): """ Transforms a comma-separated list into a list of strings. """ return value.split(",")
def ishtml(filename): """Is the file an HTMLfile""" return filename.lower()[-5:] == '.html'
def get_md5_bytes(data: bytes) -> str: """Gets the MD5 hash of a bytes object holding data Args: data: Data as a bytes object Returns: str: MD5 hash of data """ import hashlib return hashlib.md5(data).hexdigest()
def same_type(arg1, *args): """Compares the class or type of two or more objects.""" t = getattr(arg1, '__class__', type(arg1)) for arg in args: if getattr(arg, '__class__', type(arg)) is not t: return False return True
def get_time(fld): """input a date field, strip off the date and format :From - 2017-06-17 20:35:58.777353 ... 2017-06-17 :Returns - 20 h 35 m 58.78 s """ if fld is not None: lst = [float(i) for i in (str(fld).split(" ")[1]).split(":")] return "{:02.0f} h {:02.0f} m {: 5.2f} s".format(*lst) else: return None
def fix_conf(jgame): """Fixture for a standard configuration""" # XXX This line exists to fool duplication check return jgame["configuration"]
def is_gr_line(line): """Returns True if line is a GR line""" return line.startswith('#=GR')
def add_inputs(input_1: float, input_2: float, *extra) -> float: """ adds 2 or more numbers together :param input_1: first number :type input_1: float :param input_2: second number :type input_2: float :return: all the inputs added together :rtype: float """ total = input_1 + input_2 for curr_num in extra: total += curr_num return total
def multiply_by_exponent(val, exponent=3, base=10): """ Simple template tag that takes an integer and returns new integer of base ** exponent Return int Params: val: int The integer to be multiplied exponent: int The exponent base: int The base """ if type(val) == int: int_val = int(val) else: int_val = 0 return int_val * (base ** exponent)
def desolve_rk4_determine_bounds(ics,end_points=None): """ Used to determine bounds for numerical integration. - If end_points is None, the interval for integration is from ics[0] to ics[0]+10 - If end_points is a or [a], the interval for integration is from min(ics[0],a) to max(ics[0],a) - If end_points is [a,b], the interval for integration is from min(ics[0],a) to max(ics[0],b) EXAMPLES:: sage: from sage.calculus.desolvers import desolve_rk4_determine_bounds sage: desolve_rk4_determine_bounds([0,2],1) (0, 1) :: sage: desolve_rk4_determine_bounds([0,2]) (0, 10) :: sage: desolve_rk4_determine_bounds([0,2],[-2]) (-2, 0) :: sage: desolve_rk4_determine_bounds([0,2],[-2,4]) (-2, 4) """ if end_points is None: return((ics[0],ics[0]+10)) if not isinstance(end_points,list): end_points=[end_points] if len(end_points)==1: return (min(ics[0],end_points[0]),max(ics[0],end_points[0])) else: return (min(ics[0],end_points[0]),max(ics[0],end_points[1]))
def tolatin1(what): """ convert to latin1. """ return what.encode('latin-1', 'replace')
def extract_thread_list(trace_text): """Removes the thread list from the given trace data. Args: trace_text: The text portion of the trace Returns: a map of thread ids to thread names """ threads = {} # start at line 1 to skip the top of the ps dump: text = trace_text.splitlines() for line in text[1:]: cols = line.split(None, 8) if len(cols) == 9: tid = int(cols[1]) name = cols[8] threads[tid] = name return threads
def compare_fields(field1, field2): """ compare 2 fields if they are same then return true """ if field1 is None and field2 is None: return True if (field1 is None and field2 is not None) or\ (field2 is None and field1 is not None): return False if field1 == field2: return True return False
def list_creator(nbBins): """Create the necessary number of lists to compute colors feature extraction. # Arguments : nbBins: Int. The number of bins wanted for color histogram. # Outputs : lists: A list of 2*3*`nbBins` empty lists. """ nbLists = 2*3*nbBins return [[] for _ in range(nbLists)]
def choose3(n, k): """ (int, int) -> int | c(n-1, k-1) + c(n-1, k), if 0 < k < n c(n,k) = | 1 , if n = k | 1 , if k = 0 Precondition: n > k >>> binomial(9, 2) 36 """ c = [0] * (n + 1) c[0] = 1 for i in range(1, n + 1): c[i] = 1 j = i - 1 while j > 0: c[j] += c[j - 1] j -= 1 return c[k]
def get_itemid(itemlist, itemname, itemtype): """Summary - generic function to get id from name in a list Args: itemlist (TYPE): python list itemname (TYPE): k5 item name to be converted to an id itemtype (TYPE): keyname ...eg. groups/users/roles etc Returns: TYPE: Description """ try: itemid = 'None' for item in itemlist[itemtype]: if (item.get('name') == itemname): itemid = item.get('id') break return itemid except: return 'Failed to get item id'
def hw_uint(value): """return HW of 16-bit unsigned integer in two's complement""" bitcount = bin(value).count("1") return bitcount
def _fix_coords(coords, offset): """Adjust the entity coordinates to the beginning of the sentence.""" if coords is None: return None return tuple([n - offset for n in coords])
def search_opentag(line, pos=0, tag="tu"): """search opening tag""" tag1 = f"<{tag} ".encode() tag2 = f"<{tag}>".encode() try: pos1 = line.index(tag1, pos) except ValueError: pos1 = -1 try: pos2 = line.index(tag2, pos) except ValueError: pos2 = -1 if pos1 > -1 and pos2 > -1: return min(pos1, pos2) return max(pos1, pos2)
def is_capitalized(text: str): """ Given a string (system output etc.) , check whether it is lowercased, or normally capitalized. """ return not text.islower()
def count_bytes(binary_data): """Return the length of a string a string of bytes. Should raise TypeError if binary_data is not a bytes string. """ if not isinstance(binary_data, bytes): raise TypeError("expected bytes, got %s" % type(binary_data)) return len(binary_data)
def distance_score(pos1: list, pos2: list, scene_x_scale: float, scene_y_scale: float): """ Calculate distance score between two points using scene relative scale. :param pos1: First point. :param pos2: Second point. :param scene_x_scale: X scene scale. :param scene_y_scale: Y scene scale. :return: Distance score. """ # Calculate distances dif_x = abs(pos1[0] - pos2[0]) dif_y = abs(pos1[1] - pos2[1]) # Calculate relative distances scale_x = dif_x / scene_x_scale scale_y = dif_y / scene_y_scale return 1 - (0.5 * scale_x + 0.5 * scale_y)
def level_tag(list_tags, level_int ): """ Tags if the are nois or signal """ if len(list_tags)==0: return 'noise' try: return list_tags[level_int] except: return 'noise'
def check_str(names, aliases): """ Check if names match the simbad alias list. Args: names (list of str): object names in data headers aliases (list of str): aliases separated by '|' for each object. """ # Basic string check match = [] for name, alist in zip(names, aliases): # Some corner cases with catalog names if name[:2] == 'GL': name = 'GJ'+name[2:] elif name[:3] == 'BBW': name = 'BRAN'+name[3:] match.append(any(name in a for a in alist)) return match
def _different_phases(row_i, row_j): """Return True if exon start or end phases are different.""" value = (row_i['StartPhase'] != row_j['StartPhase']) or \ (row_i['EndPhase'] != row_j['EndPhase']) return value
def array_merge_recursive(array1, *arrays): """Emulates the array_merge_recursive function.""" for array in arrays: for key, value in array.items(): if key in array1: if isinstance(value, dict): array[key] = array_merge_recursive(array1[key], value) if isinstance(value, (list, tuple)): array[key] += array1[key] array1.update(array) return array1
def bin2int(alist): """ convert a binary string into integer """ answer = 0 temp = alist temp.reverse() for i in range(len(temp)): answer += 2**int(temp[i]) temp.reverse() return answer
def generate_probabilities(alpha, beta, x): """Generate probabilities in one pass for all t in x""" p = [alpha / (alpha + beta)] for t in range(1, x): pt = (beta + t - 1) / (alpha + beta + t) * p[t - 1] p.append(pt) return p
def valuedict(keys, value, default): """ Build value dictionary from a list of keys and a value. Parameters ---------- keys: list The list of keys value: {dict, int, float, str, None} A value or the already formed dictionary default: {int, float, str} A default value to set if no value Returns ------- dict A dictionary Notes ----- This standalone and generic function is only required by plotters. """ if isinstance(value, dict): return {key: value.get(key, default) for key in keys} else: return dict.fromkeys(keys, value or default)
def _newer_than(number: int, unit: str) -> str: """ Returns a query term matching messages newer than a time period. Args: number: The number of units of time of the period. unit: The unit of time: 'day', 'month', or 'year'. Returns: The query string. """ return f'newer_than:{number}{unit[0]}'
def find_max_min(my_list): """ function to get the minimum nd maximum values in a list and return the result in alist """ min_max_result = [] if type(my_list) == list: """ checks if the input is alist in order to perform the intended task use max() and min() methods to find the maximum and minimum values from the list respectively and return the output in a list """ max_value=max(my_list) min_value=min(my_list) if max_value == min_value: """ checks if the maximum and minimum are equal if they are equal if they are not equal it returns a list that contains the minimum and maximum values """ min_max_equals = len(my_list) return min_max_equals else: min_max_result.append(min_value) min_max_result.append(max_value) return min_max_result else: return "invalid input"
def hex_encode_bytes(message): """ Encode the binary message by converting each byte into a two-character hex string. """ out = "" for c in message: out += "%02x" % ord(c) return out
def _process_shape_and_axes(shape, axes): """ :returns: shape, axes, nbatch """ if axes is None: # if invalid, return shape, axes, 1 elif len(axes) > 3: raise ValueError( "FFTs with dimension greater than three are unsupported.") elif 0 in axes: if len(shape) == 4: raise ValueError( "Can't transform along first dimension of 4D arrays.") return shape, axes, 1 else: axes = tuple(ax - 1 for ax in axes) return shape[1:], axes, shape[0]
def _get_groups(verb): """ Return groups """ try: return verb.data.plydata_groups except AttributeError: return []
def get_next_version(current_version) -> str: """ Get the next version that we can use in the requirements file. """ release, major, minor = [int("".join(o for o in i if o.isdigit())) for i in current_version.split(".")] if release == 0: return f"0.{major + 1}.0" return f"{release + 1}.0.0"
def readFileIntoList(fileName): """ Reads a single file into a single list, returns that list, strips newline character """ inFile = open(fileName) items = list() for line in inFile: items.append(line.rstrip('\n')) inFile.close() return items
def transpose_results(result): """Given a query result (list of strings, each string represents a row), return a list of columns, where each column is a list of strings.""" split_result = [row.split('\t') for row in result] return [list(l) for l in zip(*split_result)]
def hello(friend_name): """Say hello to the world :param friend_name: String :rtype: String """ return f"Hello, {friend_name}!"
def flatten_list(l): """Flatten a 2D sequence `l` to a 1D list that is returned""" return sum(l, [])
def slash_join(a, b): """ Join a and b with a single slash, regardless of whether they already contain a trailing/leading slash or neither. """ if not b: # "" or None, don't append a slash return a if a.endswith("/"): if b.startswith("/"): return a[:-1] + b return a + b if b.startswith("/"): return a + b return a + "/" + b
def datatype_percent(times, series): """ returns series converted to datatype percent ever value is calculated as percentage of max value in series parameters: series <tuple> of <float> returns: <tuple> of <float> percent between 0.0 and 1.0 """ max_value = max(series) try: new_series = tuple((value/max_value for value in series)) return new_series except ZeroDivisionError: return (0.0,) * len(series)
def indent_block(text, indention=' '): """ This function indents a text block with a default of four spaces """ temp = '' while text and text[-1] == '\n': temp += text[-1] text = text[:-1] lines = text.split('\n') return '\n'.join(map(lambda s: indention + s, lines)) + temp
def elmult(v1, v2): """ Multiply two vectors with the same dimension element-wise. """ assert len(v1) == len(v2) return [v1[i] * v2[i] for i in range(len(v1))]
def normal_from_lineseg(seg): """ Returns a normal vector with respect to the given line segment. """ start, end = seg x1, y1 = start x2, y2 = end dx = x2 - x1 dy = y2 - y1 return (dy, -dx)
def Pluralize(num, word, plural=None): """Pluralize word based on num. Args: num: int, the number of objects to count. word: str, the word to pluralize. plural: str, the plural form of word if not "add s" Returns: str: the plural or singular form of word in accord with num. """ if num == 1: return word return plural or word + 's'
def compute_metric_deltas(m2, m1, metric_names): """Returns a dictionary of the differences of metrics in m2 and m1 (m2 - m1)""" return dict((n, m2.get(n, 0) - m1.get(n, 0)) for n in metric_names)
def RPL_LUSERUNKNOWN(sender, receipient, message): """ Reply Code 253 """ return "<" + sender + ">: " + message
def _public_coverage_ht_path(data_type: str, version: str) -> str: """ Get public coverage hail table. :param data_type: One of "exomes" or "genomes" :param version: One of the release versions of gnomAD on GRCh37 :return: path to coverage Table """ return f"gs://gnomad-public-requester-pays/release/{version}/coverage/{data_type}/gnomad.{data_type}.r{version}.coverage.ht"
def lg_to_gpa(letter_grade): """Convert letter grade to GPA score Example: B+ => 3.3""" return {'A': '4.0','A-': '3.7','B+': '3.3', 'B': '3.0', 'B-': '2.7', 'C+': '2.3', 'C': '2.0','D': '1.0','F': '0'}[letter_grade]
def bitshift_left(case, caselen): """Shift bit by bit to left, adding zeroes from the right""" bitshifts = [] for bit in range(1, caselen + 1): shift = case[bit:] + "0" * bit bitshifts.append(shift) return bitshifts
def fibo(n): """Calculate Fibonacchi numbers :param int n: Which position in the series to return the number for :returns: The Nth number in the Fibonacchi series """ if n == 1: return 1 elif n == 2: return 1 elif n > 2: return fibo(n - 1) + fibo(n - 2)
def is_slice_index(index): """see if index is a slice index or has slice in it""" if isinstance(index, slice): return True if isinstance(index, tuple): for i in index: if isinstance(i, slice): return True return False
def inputs(form_args): """ Creates list of input elements """ element = [] html_field = '<input type="hidden" name="{}" value="{}"/>' for name, value in form_args.items(): if name == "scope" and isinstance(value, list): value = " ".join(value) element.append(html_field.format(name, value)) return "\n".join(element)
def _google_spreadsheet_url(key): """ Returns full editing URL for a Google Spreadsheet given its key """ return "https://docs.google.com/spreadsheets/d/{key}/edit".format(key=key)
def alphabet_position(text): """ In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. "a" = 1, "b" = 2, etc. :param text: a string value. :return: the index of each character in the input sting as a string. """ return " ".join([str(list("abcdefghijklmnopqrstuvwxyz").index(x) + 1) for x in text.lower() if x.isalpha()])
def _compute_nfp_uniform(l, u, cum_counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bound on set sizes. cum_counts: the complete cummulative distribution of set sizes. sizes: the complete domain of set sizes. Return (float): the expected number of false positives. """ if l > u: raise ValueError("l must be less or equal to u") if l == 0: n = cum_counts[u] else: n = cum_counts[u]-cum_counts[l-1] return n * float(sizes[u] - sizes[l]) / float(2*sizes[u])
def to_hex(cmd): """Return the hexadecimal version of a serial command. Keyword arguments: cmd -- the serial command """ return ' '.join([hex(ord(c))[2:].zfill(2) for c in cmd])