content
stringlengths
42
6.51k
def gcd_by_iterative(x, y): """ >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return x
def music_to_notes(music, *, line_length=1): """Converts music into notes (two tuples of note name and length) This function returns a list of two-tuples of a string/None and a float. The first item is the note name (or a break if it is a None). The second item is its length. Note that there is a ...
def prime_factors(n): """Return tuple of prime factors of n.""" factors = [] i = 2 while n > 1: if n % i == 0: n /= i factors.append(i) else: i += 1 return tuple(factors)
def down_diagonal_contains_only_os(board): """Check whether the going down diagonal contains only os""" for i in range(len(board)): if board[i][i] != "O": return False return True
def replace_null(x, replace = None): """ Replace null values Parameters ---------- x : Expr, Series Column to operate on Examples -------- >>> df = tp.Tibble(x = [0, None], y = [None, None]) >>> df.mutate(x = tp.replace_null(col('x'), 1)) """ if replace == None: ret...
def area_of_polygon(x, y): """Calculates the signed area of an arbitrary polygon given its verticies http://stackoverflow.com/a/4682656/190597 (Joe Kington) http://softsurfer.com/Archive/algorithm_0101/algorithm_0101.htm#2D%20Polygons """ print('x:',x,'\ny:',y) area = 0.0 for i in ran...
def MapLines(f, s): """Apply a function across each line in a flat string. Args: f: A string transform function for a line. s: A string consisting of potentially multiple lines. Returns: A flat string with f applied to each line. """ return '\n'.join(f(line) for line in s.split('\n'))
def bytes2human(n): """Convert bytes to human readable format.""" symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] ...
def _add_service_name_to_service_port(spec, svc_name): """Goes recursively through the ingress manifest and adds the right serviceName next to every servicePort definition. """ if isinstance(spec, dict): dict_keys = list(spec.keys()) for k in dict_keys: spec[k] = _add_service...
def valid_tabulated_shape(width, height, is_rectangle): """Return if the tabulated shape is valid. Validating that the strings `width` and `height` contain positive floats was previously done using a regex. However, experiments showed that trying to split the string and reading in the floats is much fa...
def is_synonym(name: str, synonym_string: str) -> bool: """ Inputs: name: string to check for within synonym_string synonym_string: string with /// between names Returns True if case insensitive match of name to full name in synonym_string """ return name.lower() in [x.lower() for x ...
def _strip_str(value): """Strip whitespace if value is a string.""" if isinstance(value, str): value = value.strip() return value
def fill_list_cols(collection): """ Fill the lists with empty items so pandas can store it """ result = [] max_length = 0 for col in collection: result.append(col) if len(col) > max_length: max_length = len(col) for col in result: addition = max_length - len(col) col += [""] * addition return resul...
def get_unique_values(known_values, new_values): """ Compare two lists, counts and returns unique elements not found in known values """ unique_values = [] # Note: new_list = list[:] signals that we want a copy of the original list, # otherwise using new_list.remove() lower down would alter both l...
def __ensure_suffix(t, suffix): """ Ensure that the target t has the given suffix. """ tpath = str(t) if not tpath.endswith(suffix): return tpath+suffix return t
def is_end_of_sentence(prev_token, current_token): """Determine whether there is an end of the sentence Args: prev_token: hypothetical end of the sentence current_token: hypothetical beginning of the sentence Returns: None """ is_capital = current_token[0].isupper() is_...
def min_max_mormalization_1(x): """[0 1]""" return [(float(i) - min(x)) / float(max(x) - min(x)) for i in x]
def message_filter_function(data): # type: (dict) -> bool """ Message filter :param data: LoggerJSON message body :return: """ try: return data["message"]["host"] != "logger.cvtsp.com" except: return True
def timeout_soft_cmd(cmd, timeout): """Same as timeout_cmd buf using SIGTERM on timeout.""" if not timeout: return cmd return 'timeout %us stdbuf -o0 -e0 %s' % (timeout, cmd)
def get_float_format(number, places=2): """ Return number with specific float formatting """ format_string = '{:.' + str(places) + 'f}' return format_string.format(number) if number % 100 else str(number)
def convert_proxy_to_requests(proxy): """ This function convert a string ip:port to the requests package proxy format """ return {'http': 'http://{}'.format(proxy), 'https': 'http://{}'.format(proxy)}
def from_i3number(s, l, toks): """ Convert an I3 "number" to an int or float for python. :param s: passed in from callback :param l: passed in from callback :param toks: token to be modified :return: numeric type from token """ n = toks[0] try: return int(n) except ValueE...
def replicate(lst, n): """ Replicate each of the elements of lst a given number of times. For example, for lst = [a, b, c] and n = 3, the returned list is [a, a, a, b, b, b, c, c, c]. """ def rep_helper(val, n): i = 0 v = "" while i < n: v = v + val i += 1 ...
def _equal(input, values): """Checks if the given input is equal to the first value in the list :param input: The input to check :type input: int/float :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: bool ...
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for i in range(n - 1): a, b = b, a + b return a
def is_anagram(word1, word2): """Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean """ return sorted(word1) == sorted(word2)
def rgb_to_dec(value): """ Converts rgb to decimal colours (i.e. divides each value by 256) Parameters ---------- value: tuple (length 3) RGB values Returns ------- dec : tuple (length 3) Decimal color values References ---------- https://towardsdatascience...
def check_cloud(path: str): """Naive check to if the path is a cloud path""" if path.startswith("s3:"): return True return False
def harmonize_entities(default_ents, requested_ents): """Harmonizes two dictionaries representing default_ents and requested requested_ents. Given two dictionaries of entity: boolean key: value pairs, returns a dictionary where the values of entities specified in `requested_ents` override those specified ...
def to_norm_coordinates(x, y, total_width, total_height): """Reformat absolute coordinates of image of shape shape to normalized ones. :param int x: x coordinate of pt in px :param int y: y coordinate of pt in px :param int total_width: total width of the image the point shall be normalized in :par...
def calcul_ttl_in_hour(ttl: int): """ Fonction qui prend le temps sous forme de secondes et le retourne sous format heures-minutes-secondes :param ttl: le temps en secondes :return: le temps sous format heures-minutes-secondes """ if ttl < 60: return str(ttl) + " secondes" mn = ...
def explode_entity_name(entity_name: str) -> str: """ replaces _ with space """ return entity_name.replace('_', ' ')
def part1(data): """Finds a chain that uses all adapters to connect the charging outlet to your device's built-in adapter and count the joltage differences between the charging outlet, the adapters, and your device. Returns the number of 1-jolt differences multiplied by the number of 3-jolt differences....
def reverse_str(input_str): """ Reverse a string """ return input_str[::-1]
def escape(st): """ Escape special chars and return the given string *st*. **Examples**: >>> escape('\\t and \\n and \\r and " and \\\\') '\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\' """ st = st.replace('\\', r'\\') st = st.replace('\t', r'\t') st = st.replace('\r', r'\r') ...
def calculate_hamming_distance(first_dna, second_dna): """ Calculates the Hamming distance between first_dna and second_dna. Args: first_dna (str): DNA string. second_dna (str): DNA string. Returns: int: the Humming distance. """ hamming_distance = 0 for index in r...
def erd_decode_string(value: str) -> str: """ Decode an string value sent as a hex encoded string. """ raw_bytes = bytes.fromhex(value) raw_bytes = raw_bytes.rstrip(b'\x00') return raw_bytes.decode('ascii')
def xor_data(binary_data_1, binary_data_2): """Returns the xor of the two binary arrays given.""" return bytes([b1 ^ b2 for b1, b2 in zip(binary_data_1, binary_data_2)])
def capitalize(string): """Capitalize a sentence. Parameters ---------- string : `str` String to capitalize. Returns ------- `str` Capitalized string. Examples -------- >>> capitalize('worD WORD WoRd') 'Word word word' """ if not string: ret...
def tstr_to_float(tstr): """ Convert time from 12-hour string (with AM/PM) to agenda-compatible float. :param tstr: 12-hour time string :returns: Float like: 8.0 for '8:00AM' """ afloat = float(tstr.rstrip("APM").split(":")[0]) if "PM" in tstr and tstr.split(":")[0] != "12": afloat ...
def preproc_star(text): """line preprocessing - removes first asterisk""" return text.replace("*", " |", 1) if text.startswith("*") else text
def is_test_response(res): """ check if the response is test_response or not """ try: res = res.json() return True if '__for_test__' in res else False except Exception as error: return False
def format_information(title, artist, album="", index=0): """ Takes in track information and returns everything as a formatted String. Args: title (str): track title string artist (str): track artist string album (str): optional track album string index (str): optional track...
def dot(A, B): """Calculate dot product of two vectors. Parameters ---------- A, B : list of float Vectors to be multiplied. Returns ------- float Dot product of `A` and `B`. """ return sum(a * b for a, b in zip(A, B))
def compose(s1, s2): """Construct a value of Compose value type. s1, s2 -- serialised form of a property value (This is only needed if the type of the first value permits colons.) """ return s1.replace(b":", b"\\:") + b":" + s2
def gf_eval(f, x, p): """Evaluate f(x) over GF(p) using Horner scheme. """ result = 0 for a in f: result *= x result += a result %= p return result
def cm_from_in(inch): """Convert a length in inches to centimeters. Parameter inch: a length in inches. Return: the length in centimeters. """ cm = inch * 2.54 return cm
def space_separated_arg(string): """ Split a comma separated string """ return string.split(' ')
def parseResponseResult(result, operation=''): """ result: SUCCESS candy_awarded: 1 """ body = {} body['result'] = getattr(result, "result", None) if body['result'] == 'SUCCESS': if operation == 'FREE_POKEMON': body['candy_awarded'] = getattr(result, "candy_awarded", None) ...
def binary_search1(arr, key): """ binary search using recursive method """ if len(arr) > 0: mid = len(arr)//2 if key == arr[mid]: return True else: if arr[mid] > key: return binary_search1(arr[0:mid], key) else: return binary_search1(arr[mid+1:], key) else: return False
def to_none(field): """ Returns the value of None for input empty strings and empty lists. """ if field == '' or field == []: return None else: return field
def factorial(num): """ The factorial of a number. On average barely quicker than product(range(1, num)) """ # Factorial of 0 equals 1 if num == 0 or 1: return 1 else: return num*factorial(num)
def count_iterable(i): """ Returns the number of elements in an iterable. Used to get the number of combinations to test. """ return sum(1 for e in i)
def ggt(a, b): """berechnet den groessten gemeinsamen Teiler zweier Zahlen Quelle: http://www.iti.fh-flensburg.de/lang/krypto/algo/euklid.htm""" while b != 0: a, b = b, a%b return a
def overlap_1d(x1min, x1max, x2min, x2max): """ Return the overlap distance between 2 segments. """ if x1min > x2min: x1min, x2min = x2min, x1min x1max, x2max = x2max, x1max return 0 if x1max < x2min else min(x1max, x2max) - x2min
def cleanNumBeds(x): """ This is a helper function to cleanup the number of physical beds """ #All the valid values appear to be <= 6 if float(x) <= 9: return x #replace those with 1 bed since that is 90% of all properties else: return 1
def transform_lower_chars(text): """Given string, transform into lower characters.""" return str(text).lower()
def string_replace(s,c,ch=''): """Remove any occurrences of characters in c, from string s s - string to be filtered, c - characters to filter""" for a in c: s = s.replace(a,ch) return s
def unwrap_posterior_images_from_list_tuples_function(posteriorListOfTuples): """ This function... :param posteriorListOfTuples: :return: """ ## Dictionary values are now being returned as unicode characters ## so convert back to ascii # print("QQQQQ {0}".format(posteriorListOfTuples)) ...
def distribute(total, nthread): """ Try to distribute jobs into N threads as equal as possible. For example: distributing 10 jobs on 3 threads, we prefer (4, 3, 3) than (4, 4, 2) How to do it? 1. get the ceiling size for each thread, that should be (3, 3, 3), from `divmod(10, 3)[0]` 2. get the modulo by `divmod(1...
def _factor2(n): """Factorise positive integer n as d*2**i, and return (d, i). >>> _factor2(768) (3, 8) >>> _factor2(18432) (9, 11) Private function used internally by the Miller-Rabin primality test. """ assert n > 0 i = 0 d = n while 1: q, r = divmod(d, 2) ...
def Clamp01(num): """ Returns ``num`` clamped between 0 and 1. Parameters ---------- num : float Input number """ if num < 0: return 0 if num > 1: return 1 return num
def check_path(path): """ Check if it is a valid path. :param path: :return: Boolean for existence of path. """ import os return os.path.isfile(path)
def calc_dist(state1, state2): """Calculate the distance between two states""" checked_idx = [] distance = 0 for idx in state1.keys(): if state1[idx] == -1: continue if not state1[idx] == state2[idx]: distance += 1 checked_idx.append(idx) for...
def typeid_to_typedef_name(typeid, replacement='_'): """returns a sanitized typeid """ illegal_chars = ['-', '>', '<', ':', ' ', ',', '+', '.'] for ch in illegal_chars: typeid = typeid.replace(ch, replacement) return typeid
def auth_data_from_url(url): """ >>> auth_data_from_url('http://localhost/bar') ('http://localhost/bar', (None, None)) >>> auth_data_from_url('http://bar@localhost/bar') ('http://localhost/bar', ('bar', None)) >>> auth_data_from_url('http://bar:baz@localhost/bar') ('http://localhost/bar', ('...
def det(A): """Computes the determinant of a square matrix A using co-factor expansion. Assumes A is an nxn but does not assume a specific n. >>> A = [ ... [4, 3, 2, 1], ... [0, 2, 1, 4], ... [0, 0, 4, 3], ... [0, 0, 0, 2]] >>> det(A) 64 """ if not A: return 1 su...
def ordered_if_possible(x, y): """Compute x < y, or false if possible (e.g., when pushing on the heap incomparable values like strings and lists).""" try: return x < y except (TypeError, ValueError): return False
def compareInteractionPrecedence(e1, e2): """ e1/e2 = (interaction, pathdist, lindist, tok2pos) """ if e1[1] > e2[1]: return 1 elif e1[1] < e2[1]: return -1 else: # same dependency distance if e1[2] > e2[2]: return 1 elif e1[2] < e2[2]: ret...
def _is_namedtuple(x): """Duck typing test for namedtuple factory-generated objects.""" return isinstance(x, tuple) and hasattr(x, '_fields')
def split_query_into_keywords(query): """Split the query into keywords, where keywords are double quoted together, use as one keyword.""" keywords = [] # Deal with quoted keywords while '"' in query: first_quote = query.find('"') second_quote = query.find('"', first_quote + 1) ...
def get_polarity(ename, pdata=None): """Get device polarity from *pdata*. """ if pdata is None: return 1 else: return pdata.get(ename, 1)
def validate_channels(unique_channels, channel_orders): """ Checks if list of unique channels lists (or sets) fully covered by provided channel orders. Returns tuple of two lists: list channel orders, which are covering provided channels and list of station channels, which are not covered. Former being ...
def zip_(*arrays): """Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes. Args: arrays (list): Lists to process. Returns: list: Zipped list. Example: >>> zip_([1, 2, 3]...
def JD2epochBessel(JD): #---------------------------------------------------------------------- """ Convert a Julian date to a Besselian epoch. :param JD: Julian date (e.g. 2445700.5) :type JD: Floating point number :Returns: Besselian epoch (e.g. 1983.9) :Reference: Standards Of Fundamental Astron...
def isfunction_signature(signature): """Test if a DRS, or CCG type, is a function. Args: signature: The DRS or CCG signature. Returns: True if the signature is a function. See Also: marbles.ie.ccg.ccgcat.Category """ return len(signature.replace('\\', '/').split('/')) ...
def _get_subplot_dims(n): """[summary] Args: n (int): [description] Returns: tuple of int: [description] """ ncols = 4 if n % ncols: nplots = n + (ncols - n % ncols) else: nplots = n nrows = int(nplots / ncols) return nrows, ncols
def excape_x(byte_str): """ Replace '\\x' with '$' folowed by capital letters. """ if b'\\x' in byte_str: index = byte_str.find(b'\\x') left = byte_str[:index] right = byte_str[index + 4:] digit = byte_str[index + 2: index + 4] return left + b'$00' + digit.upper()...
def appears_dcx(content): """Checks if the magic bytes at the start of content indicate that it is a .dcx file. """ return content[0:4] == b"DCX\x00"
def norm_to_index(z, s): """Compute the index from a normalized and centered coordinate. Parameters ---------- z : float normalized and centered coordinate s : int shape of one axis. Eg x_index = norm_to_index(x, w) Returns ------- float float value of the inde...
def dg ( gxw ): """derivative of the psychometric function""" return gxw*(1-gxw)
def get_android_data_path(language: str, word_type: str): """ Returns the path to the data json of the Android app given a language and word type. Parameters ---------- language : str The language the path should be returned for. word_type : str The type of word...
def remove_none_values(data) -> dict: """Remove any `None`-valued items from input dict and return a clean dict.""" return {key: value for key, value in data.items() if value is not None}
def map_data_to_map(data): """ Function to map kwargs to Object. Uses `self.mapping` to map kwargs to `self.ATTRIBUTE`. Parameters ---------- data : dict Dictionary of keyword arguments. Returns ------- mapped_data : dict Mapped data. """ mapping = { ...
def get_simc_dir(talent, covenant, folder_name): """get proper directory based on talent and covenant options""" if covenant: return "{0}/{1}/{2}/".format(folder_name, talent, covenant) if talent: return "{0}/{1}/".format(folder_name, talent) return "{0}/".format(folder_name)
def appendDtectArgs( cmd, args=None ): """Append OpendTect arguments Parameters: * cmd (list): List to which the returned elements will be added * arg (dict, optional): Dictionary with the members 'dtectdata' and 'survey' as single element lists, and/or 'dtectexec' (see odpy.getODSoftwareDir) ...
def _negative_tuple(x): """ >>> _negative_tuple((1, 1, 1)) (-1, -1, -1) """ return tuple(-m for m in x)
def default_error(exception=None): """Render simple error page. This should be overidden in applications.""" # pylint: disable=unused-argument return "There was an LTI communication error", 500
def insert_sort(unsorted_list): """[Takes in an unsorted list and returns a sorted list] Args: unsorted_list ([list]): [an unsorted list of ints] """ pace = 1 for pace in range(len(unsorted_list)): pace_behind = pace - 1 temp = unsorted_list[pace] while pace_behind >...
def period(age, bv): """ From Angus 2015. This is just a place holder - need to update this model. age in Gyr. Returns period in days. """ a, b, n = .4, .31, .55 return a*(bv - .4)**b * (age*1e3)**n
def less_important_function(num: int) -> str: """ Example which is documented in the module documentation but not highlighted on the main page. :param num: A thing to pass :return: A return value """ return f'{num}'
def insertion_sort_dec(A): """ insertion sort always maintains a sorted sublist it has O(n2) time complexity sorted sublist is in the lower positions of the list """ for i in range(1,len(A)): key = A[i] j = i - 1 while j >= 0 and A[j] < key: A[j+1] = A[j] j -= 1 A[j+1] = key return A
def qi(fm, fmpp): """Calculate qI qI = (fm - fmpp) / fmpp :param fm: Fm :param fmpp: Fm'' :returns: qI (float) """ return (fm - fmpp) / fmpp
def get_epoch(data, i, epoch_len): """ Get the data corresponding to the `i`-th epoch. Parameters ---------- data : array-like, shape=(n_samples, n_features) Data to be epoched. i : int The epoch to collect. epoch_len : int Number of samples in each epoch. Returns ------- data : ndarray, shape=(epo...
def calc_power_capacity(block_count): """ Calculate the power capacity of a contiguous group of power capacitors Given the number of Power Capacitors, this function will return the total power storage they will support. Args: block_count: The number of Power Capacitors (block id 331) Retu...
def intinlist(lst): """test if int in list""" for item in lst: try: item = int(item) return True except ValueError: pass return False
def parse_int(data, *, default=None): """ Parse data into Python integer object :param data: Data to be parsed :param default: If data is blank or invalid :return: """ if data: try: return int(data) except (ValueError, TypeError): return default el...
def decdeg2dms(dd): """ Tansform decimal degrees into degrees minutes seconds Argument: dd (float): decimal angle Returns: degrees, minutes, seconds""" negative = dd < 0 dd = abs(dd) minutes, seconds = divmod(dd * 3600, 60) degrees, minutes = divmod(minute...
def sum_env_dict(envs): """Sums counts from the data structure produced by count_envs.""" return sum([sum(env.values()) for env in envs.values()])
def s(x): """Gets shape of a list/tuple/ndarray """ if type(x) in [list, tuple]: return len(x) return x.shape