content
stringlengths
42
6.51k
def count_digits1(s): """ >>> count_digits1('dghf2dfg12') '212' """ digits = '' for ch in s: if ch in '0123456789': digits = digits + ch return digits
def colour_text(text, fg=None, bg=None): """Given some text and fore/back colours, return a coloured text string.""" if fg is None: return text else: colour = '{0},{1}'.format(fg, bg) if bg is not None else fg return "\x03{0}{1}\x03".format(colour, text)
def check_args(args): """Check arguments validity""" if len(args["src"]) != len(args["dst"]): print("Error: SRC and DEST must have same number of files") return False return True
def convertToLabelFormat(oldLabels): """ Convert the label form with sets to label form with lists. For later functions, the labels are expected to be of the form: { 'label': [nodeIndex] } that is, a dictionary whose keys are the labels and values are the index number of the nodes that have that label. The node index list [nodeIndex] must be ordered. """ newLabels = {} for label in oldLabels: nodes = list(oldLabels[label]) nodes.sort() newLabels[label] = nodes return newLabels
def compare_state(obs1, obs2, margin_noise=0.3, margin_features=0.1): """ Compare 2 user observations based on the configured margins :param obs1: user's state => observation 1 :param obs2: user's state => observation 2 :param margin_noise: acceptable difference between noisy states of obs1 and obs2 :param margin_features: acceptable difference between each features(user interests) of obs1 and obs2 :return: true if obs1 is similar to obs2, false if otherwise """ if abs(obs1[0] - obs2[0]) > margin_noise: print("False") return False for i in range(1, len(obs1)): if abs(obs1[i] - obs2[i]) > margin_features: print("False") return False print("True") return True
def longest(str_1, str_2): """Function which concat, sort and find set difference of two given strings""" return "".join(sorted(set(str_1 + str_2)))
def hw_part_roi(hw_part_price: float, daily_mining_profit: float) -> float: """ Computes how many days have to pass to reach ROI (Return of investment) for single hardware part. Formula: hw_part_price / daily_mining_profit :param hw_part_price: Float. Current hardware part retail price. :param daily_mining_profit: Float. Money you gain after paying the daily mining expense. :return: Float. Days required for single hardware part ROI. """ return round(hw_part_price / daily_mining_profit, 1)
def ValueErrorOnFalse(ok, *output_args): """Raises ValueError if not ok, otherwise returns the output arguments.""" n_outputs = len(output_args) if n_outputs < 2: raise ValueError("Expected 2 or more output_args. Got: %d" % n_outputs) if not ok: error = output_args[-1] raise ValueError(error) if n_outputs == 2: output = output_args[0] else: output = output_args[0:-1] return output
def seq2str(seq,jstr=','): """Join a sequence ``seq`` of string-ifiable elements with a string ``jstr``. Example ------- .. code:: python seq2str(('a','b','c'),' - ') 'a - b - c' seq2str([1,2,3],':') '1:2:3' """ return jstr.join([str(_) for _ in seq])
def compute_padding(M, N, J): """ Precomputes the future padded size. If 2^J=M or 2^J=N, border effects are unavoidable in this case, and it is likely that the input has either a compact support, either is periodic. Parameters ---------- M, N : int input size Returns ------- M, N : int padded size """ M_padded = ((M + 2 ** J) // 2 ** J + 1) * 2 ** J N_padded = ((N + 2 ** J) // 2 ** J + 1) * 2 ** J return M_padded, N_padded
def hamming_distance(m, n): """Hamming Distance between two natural numbers is the number of ones in the binary representation of their xor. """ return sum(map(int, bin(m ^ n)[2:]))
def _to_timm_module_name(module): """ Some modules are called differently in tfimm and timm. This function converts the tfimm name to the timm name. """ if module == "vit": module = "vision_transformer" elif module == "swin": module = "swin_transformer" return module
def percent_to_float(s: str) -> float: """Helper method to replace string pct like "123.56%" to float 1.2356 Parameters ---------- s: string string to replace Returns ------- float """ s = str(float(s.rstrip("%"))) i = s.find(".") if i == -1: return int(s) / 100 if s.startswith("-"): return -percent_to_float(s.lstrip("-")) s = s.replace(".", "") i -= 2 if i < 0: return float("." + "0" * abs(i) + s) return float(s[:i] + "." + s[i:])
def calculate_relative_metric(curr_score, best_score): """ Calculate the difference between the best score and the current score, as a percentage relative to the best score. A negative result indicates that the current score is lower (=better) than the best score Parameters ---------- curr_score : float The current score best_score : float The best score Returns ------- float The relative score in percent """ return (100 / best_score) * (curr_score-best_score)
def transpose_board(board: list) -> list: """ Return transposed board so that each column becomes a row and each row becomes a column. Precondition: a board has at least one row and one column. >>> transpose_board(['1']) ['1'] >>> transpose_board(['12', '34']) ['13', '24'] >>> transpose_board(['123', '456', '789']) ['147', '258', '369'] >>> transpose_board(['22', '43', '10']) ['241', '230'] """ transposed_board = [] for row in range(len(board[0])): transposed_board.append("") for column in board: transposed_board[-1] += column[row] return transposed_board
def is_hex_digit(char): """Checks whether char is hexadecimal digit""" return '0' <= char <= '9' or 'a' <= char <= 'f'
def nCk(n, k): """http://blog.plover.com/math/choose.html""" if k > n: return 0 if k == 0: return 1 r = 1 for d in range(1, k + 1): r *= n r /= d n -= 1 return r
def prime_sieve(n): """ Return a list of prime numbers from 2 to a prime < n. Very fast (n<10,000,000) in 0.4 sec. Example: >>>prime_sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] Algorithm & Python source: Robert William Hanks http://stackoverflow.com/questions/17773352/python-sieve-prime-numbers """ sieve = [True] * (n // 2) for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i // 2]: sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1) return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]
def strip_tag_name(t: str) -> str: """Processes and XML string.""" idx = t.rfind("}") if idx != -1: t = t[idx + 1:] return t
def get_area_heron(thing): """ Use heron's formula to get the area of a triangle with vertices specified in 3D space. The trinagle is given as a list of lists. """ r1, r2, r3 = thing[0], thing[1], thing[2] abs_a = ( (r1[0]-r2[0])**2+ (r1[1]-r2[1])**2 + (r1[2]-r2[2])**2 )**0.5 abs_b = ( (r2[0]-r3[0])**2+ (r2[1]-r3[1])**2 + (r2[2]-r3[2])**2 )**0.5 abs_c = ( (r3[0]-r1[0])**2+ (r3[1]-r1[1])**2 + (r3[2]-r1[2])**2 )**0.5 s = (abs_a+abs_b+abs_c)/2 return ( s*(s-abs_a)*(s-abs_b)*(s-abs_c) )**0.5
def _gen_ssl_lab_urls(domains): """Returns a list of urls. :param list domains: Each domain is a 'str' """ return ["https://www.ssllabs.com/ssltest/analyze.html?d=%s" % dom for dom in domains]
def GetLongestMatchOption(searchstr, options=[], ignore_case=True): """ Get longest matched string from set of options. params: searchstr : string of chars to be matched options : array of strings that are to be matched returns: [] - array of matched options. The order of options is same as the arguments. empty array is returned if searchstr does not match any option. example: subcommand = LongestMatch('Rel', ['decode', 'enable', 'reload'], ignore_case=True) print subcommand # prints ['reload'] """ if ignore_case: searchstr = searchstr.lower() found_options = [] for o in options: so = o if ignore_case: so = o.lower() if so == searchstr: return [o] if so.find(searchstr) >=0 : found_options.append(o) return found_options
def disable_password_caching(on=0): """Desabilitar o Cache de Senhas no Internet Explorer DESCRIPTION Quando voce tenta visualizar um site protegido por senha, normalmente e pedido que se digite o nome de usuario e a senha, com uma opcao "Salvar esta senha na sua lista de senhas". Esta entrada pode ser usada para desabilitar esta habilidade de usuarios salvarem senhas. COMPATIBILITY Windows 2000/XP MODIFIED VALUES DisablePasswordCaching : dword : 00000000 = Padrao; 00000001 = Desabilita a cache de senhas. """ if on: return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\ CurrentVersion\\Internet Settings] "DisablePasswordCaching"=dword:00000001''' else: return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\ CurrentVersion\\Internet Settings] "DisablePasswordCaching"=dword:00000000'''
def sanitize_dict(obj): """Convert all dict values in str. Parameters ---------- obj : dict Returns ------- new_obj : dict with all values as str """ new_obj = dict([(k, str(v)) for k, v in obj.items()]) return new_obj
def tokens_to_surf(it): """ Given an iterator of segments as (type, value) tuples, reconstruct the surface string. """ return "".join(v for (t, v) in it if t == "surf")
def sort_list_using_sorted(lst): """ Sorted() sorts a list and always returns a list with the elements in a sorted manner ,without modifying the original sequence. It takes three parameters from which two are, optional, here we tried to use all of the three. """ return sorted(lst, key=lambda x:x[1])
def keep_spacing(value): """ Replace any two spaces with one &nbsp; and one space so that HTML output doesn't collapse them.""" return value.replace(' ', '&nbsp; ')
def scale(value: int or float, origin_lower: int or float, origin_upper, scale_lower, scale_upper): """ Translate a value from one numerical range to another Args: value(int,float): The current value origin_lower(int,float): The lower boundary of the original domain origin_upper(int,float): The upper boundary of the original domain scale_lower(int,float): The lower boundary of the new domain scale_upper(int,float): The upper boundary of the new domain Returns: int, float """ return scale_lower + (value - origin_lower) * ((scale_upper - scale_lower) / (origin_upper - origin_lower))
def points_with_error(dp): """Pull out all data points. Args: dp: list of dict, each giving information for a row Returns: tuple (list of true values, list of predicted values) """ true = [] pred = [] for p in dp: true += [p['true_activity']] pred += [p['predicted_activity']] return (true, pred)
def lsize( lst ): """ Combined size of all Nodes in a list """ return sum( [ x[1] for x in lst ] )
def _nmeaFloat(degrees, minutes): """ Builds an NMEA float representation for a given angle in degrees and decimal minutes. @param degrees: The integer degrees for this angle. @type degrees: C{int} @param minutes: The decimal minutes value for this angle. @type minutes: C{float} @return: The NMEA float representation for this angle. @rtype: C{str} """ return "%i%0.3f" % (degrees, minutes)
def sbas_nav_decode(dwrds: list) -> dict: """ Helper function to decode RXM-SFRBX dwrds for SBAS navigation data. :param list dwrds: array of navigation data dwrds :return: dict of navdata attributes :rtype: dict """ return {"dwrds": dwrds}
def _add_extra_attributes(attrs, extra_attr_map): """ :param attrs: Current Attribute list :param extraAttrMap: Additional attributes to be added :return: new_attr """ for attr in extra_attr_map: if attr not in attrs: attrs[attr] = extra_attr_map[attr] return attrs
def string_SizeInBytes(size_in_bytes): """Make ``size in bytes`` human readable. Doesn"t support size greater than 1000PB. Usage:: >>> from __future__ import print_function >>> from angora.filesystem.filesystem import string_SizeInBytes >>> print(string_SizeInBytes(100)) 100 B >>> print(string_SizeInBytes(100*1000)) 97.66 KB >>> print(string_SizeInBytes(100*1000**2)) 95.37 MB >>> print(string_SizeInBytes(100*1000**3)) 93.13 GB >>> print(string_SizeInBytes(100*1000**4)) 90.95 TB >>> print(string_SizeInBytes(100*1000**5)) 88.82 PB """ res, by = divmod(size_in_bytes,1024) res, kb = divmod(res,1024) res, mb = divmod(res,1024) res, gb = divmod(res,1024) pb, tb = divmod(res,1024) if pb != 0: human_readable_size = "%.2f PB" % (pb + tb/float(1024) ) elif tb != 0: human_readable_size = "%.2f TB" % (tb + gb/float(1024) ) elif gb != 0: human_readable_size = "%.2f GB" % (gb + mb/float(1024) ) elif mb != 0: human_readable_size = "%.2f MB" % (mb + kb/float(1024) ) elif kb != 0: human_readable_size = "%.2f KB" % (kb + by/float(1024) ) else: human_readable_size = "%s B" % by return human_readable_size
def prepare_pass(data): """Dummy preparation hook Use if no preparation of input data is desired. Args: data: Input data that should be prepared. Returns: (data,), {} """ return (data,), {}
def make_column_names_numbered(base = "base", times = 1): """create an array of numbered instances of a base string""" return ["%s%d" % (base, i) for i in range(times)]
def string_name(value: str, characters: str = ".") -> str: """ Find and replace characters in a string with underscores '_'. :param value: String to be validate :param char: Characters to be replaced :return value: Re-formatted string """ for char in characters: value = value.replace(char, "_") return value
def clean_table_name(table_name): """Remove and replace chars `.` and '-' with '_'""" path_underscore = table_name.translate(table_name.maketrans("-. ", "___")) return "_".join(filter(None, path_underscore.split("_")))
def _render_minimal_setup_py( package_name: str, author: str, email: str, url: str ) -> str: """Render the contents for an arbitraty Python module. :param package_name: The name of the package to be registered. :param author: Name of package author. :param email: E-mail address of package author. :param url: URL for package (website or repo). :return: Module contents as text. """ setup = (f'from setuptools import setup\n' f'setup(name="{package_name}", version="0.0.1", ' f'py_modules=["{package_name}"], ' f'author="{author}", author_email="{email}", ' f'description="This is a placeholder package created by registerit.", ' f'url="{url}")') return setup
def diff(existing, new): """Constructs the diff for Ansible's --diff option. Args: existing (dict): Existing valuemap data. new (dict): New valuemap data. Returns: A dictionary like {'before': existing, 'after': new} with filtered empty values. """ before = {} after = {} for key in new: before[key] = existing[key] if new[key] is None: after[key] = '' else: after[key] = new[key] return {'before': before, 'after': after}
def unescape(str): """Unescape a string in a manner suitable for XML/Pango.""" return str.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
def convert_qe_time_to_sec(timestr): """Given the walltime string of Quantum Espresso, converts it in a number of seconds (float).""" rest = timestr.strip() if 'd' in rest: days, rest = rest.split('d') else: days = '0' if 'h' in rest: hours, rest = rest.split('h') else: hours = '0' if 'm' in rest: minutes, rest = rest.split('m') else: minutes = '0' if 's' in rest: seconds, rest = rest.split('s') else: seconds = '0.' if rest.strip(): raise ValueError(f"Something remained at the end of the string '{timestr}': '{rest}'") num_seconds = (float(seconds) + float(minutes) * 60. + float(hours) * 3600. + float(days) * 86400.) return num_seconds
def get_full_url(link_category: str, city: str = 'msk') -> str: """Get_full_url.""" full_url = f"https://www.okeydostavka.ru/{city}{link_category}" return full_url
def _lagrange_interpolate_noprime(x, x_s, y_s): """ Find the y-value for the given x, given n (x, y) points; k points will define a polynomial of up to kth order. """ k = len(x_s) assert k == len(set(x_s)), "points must be distinct" def PI(vals): # upper-case PI -- product of inputs accum = 1 for v in vals: accum *= v return accum nums = [] # avoid inexact division dens = [] for i in range(k): others = list(x_s) cur = others.pop(i) nums.append(PI(x - o for o in others)) dens.append(PI(cur - o for o in others)) den = PI(dens) # num = sum([_divmod(nums[i] * den * y_s[i] % p, dens[i], p) # for i in range(k)]) # [(nums[i] * den * y_s[i]) / dens[i] for i in range(k)] num = sum([ (nums[i] * den * y_s[i]) / dens[i] for i in range(k)] ) # return (_divmod(num, den, p) + p) % p return num / den
def my_sum(iterable): """Sum implemetnation.""" tot = 0 for i in iterable: tot += i return tot
def general_value(value): """Checks if value is generally valid Returns: 200 if ok, 700 if ',' in value, 701 if '\n' in value""" if ',' in value: return 700 elif '\n' in value: return 701 else: return 200
def makeGridNodes(grid_info): """ Generate a grid node coordinate list where each grid represents a node :param grid_info: Grid Map Information :return: A Grid Coordinate List st. in each position (Grid ID) a (latitude, longitude) pair is stored """ leftLng = grid_info['minLng'] + grid_info['gridLng'] / 2 midLat = grid_info['maxLat'] - grid_info['gridLat'] / 2 grid_nodes = [] for i in range(grid_info['latGridNum']): midLng = leftLng for j in range(grid_info['lngGridNum']): grid_nodes.append((midLat, midLng)) midLng += grid_info['gridLng'] midLat -= grid_info['gridLat'] print('Grid nodes generated.') return grid_nodes
def invert_number(number: int) -> int: """ number: 7 = 0b111 -> 0b000 = 0 number: 111 = 0b1101111 -> 0b0010000 = 16 number: 10000000000 = 0b1001010100000010111110010000000000 -> 0b0110101011111101000001101111111111 = 7179869183 :param number :return: invert number """ return int(''.join('1' if i == '0' else '0' for i in bin(number)[2:]), base=2)
def quote_str(value): """ Returns a string wrapped in quotes or any other value as a string :param value: any value :type value: str | any :return: a string that may be quoted :rtype: str """ if isinstance(value, str): return '"{0}"'.format(value) else: return str(value)
def determine_alignment(pos): """Parse position of the textbox""" tokens = pos.split('-') if len(tokens) > 2: raise RuntimeError("Unknown position: %s" % (pos)) vpos = None hpos = None for token in tokens: if token in [ 'right', 'left' ]: hpos = token elif token in [ 'top', 'bottom' ]: vpos = token else: raise RuntimeError("Unknown position: %s" % (token)) return (vpos, hpos)
def guid_section(sec_type, guid, guid_attrib, inputfile): """ generates the GUID defined section """ cmd = ["tmp.guid", "-s", "EFI_SECTION_GUID_DEFINED", "-g"] cmd += [guid, "-r", guid_attrib, inputfile] return cmd
def convert_str_weight_into_int(weight): """ Converts part of str before the first space into int value """ try: return int(weight.split(" ", 1)[0]) except ValueError as e: print ("Error: {} \nThe default value {} was asigned".format(e, "0")) return 0
def epoch_time(start_time, end_time): """ Computes the time for each epoch in minutes and seconds. :param start_time: start of the epoch :param end_time: end of the epoch :return: time in minutes and seconds """ elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
def sort_results(results): """Sorts file names based on designated part number. File names are expected to be in the form : {task_id}.{part number}.{extension} :param results: a list of file names to be sorted :type results: list of str """ return sorted(results, key=lambda x: x.split('.', maxsplit=2)[1])
def bkp_log_miss(args_array, server): """Function: bkp_log_miss Description: bkp_log_miss function. Arguments: (input) args_array (input) server """ status = True if args_array and server: status = True return status
def _build_response_credential_filter_multiple_credentials(credential_items, status_code): """ Method to build the response if the API user chose to return all the matched credentials """ return { "status": status_code, "data": [{ "id": item["id"], "name": item["name"] } for item in credential_items] }
def sum_of_factorial_pure_recursion(number: int) -> int: """ >>> sum_of_factorial_pure_recursion(0) 0 >>> sum_of_factorial_pure_recursion(1) 1 >>> sum_of_factorial_pure_recursion(2) 3 >>> sum_of_factorial_pure_recursion(5) 153 """ if number == 1 or number == 0: return number # 1! or 0! elif number == 2: return 3 # 1! + 2! else: return ( sum_of_factorial_pure_recursion(number - 1) + ( sum_of_factorial_pure_recursion(number - 1) - sum_of_factorial_pure_recursion(number - 2) ) * number )
def build_years_list(start): """create a list of 10 years counting backward from the start year""" years = [] for i in range(0, 10): years.append(start - i) return years
def gen_from_source(source): """Returns a generator from a source tuple. Source tuples are of the form (callable, args) where callable(\*args) returns either a generator or another source tuple. This allows indefinite regeneration of data sources. """ while isinstance(source, tuple): gen, args = source source = gen(*args) return source
def f2s(f): """ Format a string containing a float """ s = "" if f >= 0.0: s += " " return s + "%1.9E" % f
def dict_get(dict, key, default=None): """ Returns the value of key in the given dict, or the default value if the key is not found. """ if dict is None: return default return dict.get(key, default)
def greedySum(L, s): """ input: s, positive integer, what the sum should add up to L, list of unique positive integers sorted in descending order Use the greedy approach where you find the largest multiplier for the largest value in L then for the second largest, and so on to solve the equation s = L[0]*m_0 + L[1]*m_1 + ... + L[n-1]*m_(n-1) return: the sum of the multipliers or "no solution" if greedy approach does not yield a set of multipliers such that the equation sums to 's' """ n = len(L) m = [0 for i in range(n)] tempSum = s for i in range(n): m[i] = int(tempSum/L[i]) tempSum -= m[i]*L[i] if tempSum == 0: return sum(m) return "no solution"
def int_to_rgb(number): """Given an integer, return the rgb""" number = int(number) r = number % 256 g = (number // 256) % 256 b = (number // (256 * 256)) % 256 return r, g, b
def is_toplevel_in_list(lst): """Check if objects in list are at top level.""" if len(lst) == 0: return True for ob in lst: if ob.Name.startswith("Clone"): continue if ob.Name.startswith("Part__Mirroring"): continue else: return False return True
def range_str(range_str, sort=True): """Generate range of ints from a formatted string, then convert range from int to str Examples -------- >>> range_str('1-4,6,9-11') ['1','2','3','4','6','9','10','11'] Takes a range in form of "a-b" and returns a list of numbers between a and b inclusive. Also accepts comma separated ranges like "a-b,c-d,f" which will return a list with numbers from a to b, c to d, and f. Parameters ---------- range_str : str of form 'a-b,c', where a hyphen indicates a range and a comma separates ranges or single numbers sort : bool If True, sort output before returning. Default is True. Returns ------- list_range : list of integer values converted to single-character strings, produced by parsing range_str """ # adapted from # http://code.activestate.com/recipes/577279-generate-list-of-numbers-from-hyphenated-and-comma/ s = "".join(range_str.split()) # removes white space list_range = [] for substr in range_str.split(","): subrange = substr.split("-") if len(subrange) not in [1, 2]: raise SyntaxError( "unable to parse range {} in labelset {}.".format(subrange, substr) ) list_range.extend([int(subrange[0])]) if len( subrange ) == 1 else list_range.extend(range(int(subrange[0]), int(subrange[1]) + 1)) if sort: list_range.sort() return [str(list_int) for list_int in list_range]
def keyval_to_str(key, val): """string representation of key and value for print or gui show """ return f"{key} = {val}"
def scan_password(name): """ Get password (if any) from the title """ if 'http://' in name or 'https://' in name: return name, None braces = name.find('{{') if braces < 0: braces = len(name) slash = name.find('/') # Look for name/password, but make sure that '/' comes before any {{ if 0 <= slash < braces and 'password=' not in name: # Is it maybe in 'name / password' notation? if slash == name.find(' / ') + 1: # Remove the extra space after name and before password return name[:slash - 1].strip('. '), name[slash + 2:] return name[:slash].strip('. '), name[slash + 1:] # Look for "name password=password" pw = name.find('password=') if pw >= 0: return name[:pw].strip('. '), name[pw + 9:] # Look for name{{password}} if braces < len(name) and name.endswith('}}'): return name[:braces].strip('. '), name[braces + 2:len(name) - 2] # Look again for name/password if slash >= 0: return name[:slash].strip('. '), name[slash + 1:] # No password found return name, None
def checkedstr(checked): """ Takes a list of checked items and a description, and prints them. """ if len(checked) > 0: for item in checked: if item[2]!='OK' : return '|'.join(item[1]) return 'OK'
def str2b(data): """Convert string into byte type.""" try: return data.encode("latin1") except UnicodeDecodeError: return data
def _check_is_int(obj): """Check whether obj is an integer.""" return isinstance(obj, int)
def dict_mean(dicts): """Average a list of dictionary.""" means = {} for key in dicts[0].keys(): means[key] = sum(d[key] for d in dicts) / len(dicts) return means
def _format_task(task): """ Return a dictionary with the task ready for slack fileds :param task: The name of the task :return: A dictionary ready to be inserted in Slack fields array """ return {"value": task, "short": False}
def common_elements(list1, list2): """common elements between two sorted arrays Arguments: list1 sorted array list2 sorted array Returns: array with common elements """ result = [] visited_elements = [] for item in list1: index = len(visited_elements) while index < len(list2): if(item >= list2[index]): visited_elements.append(list2[index]) if(item == list2[index]): result.append(list2[index]) break index += 1 pass pass return result
def normalize_text(text): """Replaces punctuation characters with spaces, then collapses multiple spaces to a single one, then maps to lowercase.""" import string return ' '.join(''.join([ ' ' if c in string.punctuation else c for c in text ]).split()).lower()
def get_minterm(d): """ Sorts the dict's keys, then returns a sorted array of [0's and 1's] corresponding to the value of each key """ keys = sorted(list(d.keys())) return [int(d[k]) for k in keys]
def merge(a, b): """ helper function used by merge_sort combines two sorted lists into one sorted list """ i, j = 0, 0 sorted_list = [] while i < len(a) and j < len(b): if a[i] < b[j]: sorted_list.append(a[i]) i += 1 else: sorted_list.append(b[j]) j += 1 # at this point, we have reached the end of one of the lists, we therefore # append the remaining elements directly to sorted_list sorted_list += a[i:] sorted_list += b[j:] return sorted_list
def title_case(sentence): """ Convert a string ti title case. Title case means that the first character of every ward is capitalize.. Parameters sentence: string string to be converted to tile case Returns ------- ret: string Input string in title case Examples -------- >>>> title_case("ThIs iS a STring to be ConverteD") >>>> This Is A String To Be Converted. """ # Check that input is string if not isinstance(sentence, str): raise TypeError("Invalid input must be type string.") if len(sentence) == 0: raise ValueError("Cannot apply title function to empty string") return sentence.title()
def get_shared_prefix(w1, w2): """Get a string which w1 and w2 both have at the beginning.""" shared = "" for i in range(1, min(len(w1), len(w2))): if w1[:i] != w2[:i]: return shared else: shared = w1[:i] return shared
def tostr(lst): """Makes all values of a list into strings""" return [str(i) for i in list(lst)]
def make_list_from_string(line): """Function for creating info list for daemon_adding.""" result = [] sub_string = "" for index in range(0, len(line)): if line[index] != " ": sub_string += line[index] if index == len(line) - 1: result.append(sub_string) elif sub_string != "": result.append(sub_string) sub_string = "" return result
def max_recur(head, max): """Excercise 1.3.28 Find max in linked list recursively.""" if head is None: return max if head.item > max: max = head.item head = head.next return max_recur(head, max)
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return (None, None) low = ints[0] high = ints[0] for i in ints: if i < low: low = i elif i > high: high = i return (low, high)
def get_polygon_outer_bounding_box(polygon): """Get the outer bounding box of a polygon defined as a sequence of points (2-uples) in the 2D plane. :param polygon: (x1,y1), ... (xn,yn) :return: (x,y,width,height) """ xs = [i[0] for i in polygon] # may be improved if using numpy methods directly ys = [i[1] for i in polygon] mx = min(xs) my = min(ys) return mx, my, max(xs) - mx, max(ys) - my
def rgb2hex(rgb): """ converts a list of rgb values to hex >>> rgb2hex([255, 100, 0]) #FF6400 """ r, g, b = rgb return '#{:02x}{:02x}{:02x}'.format(r, g, b)
def twiddle_bit(bb, bit): """ Flip a bit from on to off and vice-versa """ return bb ^ (1 << bit)
def HSVtoRGB(h, s, v): """ Convert Hue-Saturation-Value into Red-Green-Blue equivalent. Parameters: h - Hue between [0.0, 360.0) degrees. red(0.0) to violet(360.0-). s - Staturation [0.0, 1.0] v - Value [0.0, 1.0] Return Value: (r, g, b) 3-tuple with each color between [0, 255] """ # achromatic (grey) if s == 0.0: r = g = b = int(v * 255) return (r, g, b) # sector 0 to 5 h /= 60.0 i = int(h) # hue whole part f = h - i # hue fraction part of h p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f )) if i == 0: r = int(v * 255.0) g = int(t * 255.0) b = int(p * 255.0) elif i == 1: r = int(q * 255.0) g = int(v * 255.0) b = int(p * 255.0) elif i == 2: r = int(p * 255.0) g = int(v * 255.0) b = int(t * 255.0) elif i == 3: r = int(p * 255.0) g = int(q * 255.0) b = int(v * 255.0) elif i == 4: r = int(t * 255.0) g = int(p * 255.0) b = int(v * 255.0) else: # sector 5 r = int(v * 255.0) g = int(p * 255.0) b = int(q * 255.0) return (r, g, b)
def ordinal(n): """Takes a number (int) and returns both the number and its ordinal suffix""" return str(n) + ("th" if 4 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th"))
def process_key(key): """Ensure key string uses newlines instead of spaces.""" KEY_BEGIN = "-----BEGIN RSA PRIVATE KEY-----" KEY_END = "-----END RSA PRIVATE KEY-----" key_out = KEY_BEGIN + "\n" for item in key.replace(KEY_BEGIN, "").replace(KEY_END, "").split(): key_out += item + "\n" key_out += KEY_END return key_out
def _concat_sampling(sample1, sample2): """ computes an index vector for the sequential sampling with sample1 and sample2 """ sample_out = [[i_samp1 for i_samp1 in sample1 if i_samp1 == i_samp2] for i_samp2 in sample2] return sum(sample_out, [])
def FormatClassToJava(i): """ Transoform a typical xml format class into java format :param i: the input class name :rtype: string """ return "L" + i.replace(".", "/") + ";"
def cross(A, B): """Cross product of elements in A and elements in B """ return [ x +y for x in A for y in B]
def search_wordlist(words: list, html: str): """Return the words in a list that appear in the HTML Args: words (list): A list of words to look for html (str): The string to look for the words in Returns: list: The list of words from the list found in the HTML """ return [word for word in words if word in html]
def day_number(hour_number): """ Returns the day_number given a particular hour_number Parameters ---------- hour_number : float The number of hours since Jan first of a given year Returns ------- day_number : int The hour number """ N = (hour_number / 8760) * 365 return int(N)
def get_enabled_services(environment, roles_data): """Build list of enabled services :param environment: Heat environment for deployment :param roles_data: Roles file data used to filter services :returns: set of resource types representing enabled services """ enabled_services = set() parameter_defaults = environment.get('parameter_defaults', {}) for role in roles_data: count = parameter_defaults.get('%sCount' % role['name'], role.get('CountDefault', 0)) try: count = int(count) except ValueError: raise ValueError('Unable to convert %sCount to an int: %s' % (role['name'], count)) if count > 0: enabled_services.update( parameter_defaults.get('%sServices' % role['name'], role.get('ServicesDefault', []))) return enabled_services
def totalCredits (theDictionary): """Calculates the total credits student is taking this semester. :param dict[str, int] theDictionary: The student's class information with the class as the key and the number or credits as the value :return: The total credits :rtype: int """ total = 0 # = sum (theDictionary.values ()) for i in theDictionary: total += theDictionary[i] return total
def binary_tree(r): """Definition of a binary tree using lists.""" return [r, [], []]
def find_indices(nums, val): """Given a list, find the two indices that sum to a specific value""" for i, outer_num in enumerate(nums): for j, inner_num in enumerate(nums): if outer_num + inner_num == val: return (i, j) return False
def maximum(value1, value2, value3): """Return the maximum of three values.""" max_value = value1 if value2 > max_value: max_value = value2 if value3 > max_value: max_value = value3 return max_value
def build_complement(dna): """ :param dna: str, the base of dna would be 'A', 'T', 'C', 'G': A and T are corresponding base of each. C and G are corresponding base of each. :return: The corresponding base of dna. """ ans = '' for base in dna: if base == 'A': ans += 'T' elif base == 'T': ans += 'A' elif base == 'C': ans += 'G' elif base == 'G': ans += 'C' return ans
def integer_if_integral(x): """Convert a float to int if it can be represented as an int""" return int(x) if x == int(x) else x