content
stringlengths
42
6.51k
def row_sum_odd_numbers(n): """ Given the triangle of consecutive odd numbers """ result = 0 start = (n * n)-(n - 1) end = start+n * 2 for i in range(start, end, 2): result += i return result
def to_char(keyval_or_char): """Convert a event keyval or character to a character""" if isinstance(keyval_or_char, str): return keyval_or_char return chr(keyval_or_char) if 0 < keyval_or_char < 128 else None
def title_case(sentence, str): """ Convert a string to title case. Parameters ---------- sentence : string String to be converted to title case Returns -------- str : string String converted to title case Example -------- >>> title_case('ThIS IS a StrinG to...
def overlap(s1, s2): """Two strings: s1, s2. Reutnrs x,y,z such as: s1 = xy s2 = yz """ if len(s2) == 0: return s1, (), s2 i1, i2 = 0, 0 #i1, i2: indices in s1, s2 s2_0 = s2[0] istart = max( 0, len(s1) - len(s2) ) for i in range(istart, len(s1)): s1_i = ...
def broken_fit(p,xax): """Evaluate the broken power law fit with the parameters chosen Parameters: p[0] - breakpoint p[1] - scale p[2] - lower slope (xax < breakpoint) p[3] - higher slope (xax >= breakpoint) """ xdiff=xax-p[0] lfit=(p[2]*xdiff+p[1])*(xdiff < 0) ...
def angle(d, m, s): """Return an angle data structure from d degrees, m arcminutes and s arcseconds. This assumes that negative angles specifies negative d, m and s.""" return d + ((m + (s / 60)) / 60)
def choose_small_vocabulary(index, concepts): """ Choose the vocabulary of the small frame, by eliminating the terms which: - contain more than one word - are not in ConceptNet """ vocab = [term for term in index if '_' not in term and term in concepts] return vocab
def catch(func, handle=lambda e: e, *args, **kwargs): """Helper function to enable the list comprehension in xmltolist. Whenenver a data field doesn't have an entry, put an empty string. cf. http://stackoverflow.com/a/8915613 """ try: return func(*args, **kwargs) except KeyError: ...
def elias_encode(a): """ Elias gamma encode the integer a. """ e = '' n = 0 while a != 0: e = str(a&1) + e a >>= 1 n += 1 return '0'*(n-1) + e
def get_doi_url(doi): """ Given a DOI, get the URL for the DOI """ return "https://doi.org/%s" % doi
def argmin(seq, fn): """Return an element with lowest fn(seq[i]) score; tie goes to first one. >>> argmin(['one', 'to', 'three'], len) 'to' """ best = seq[0]; best_score = fn(best) for x in seq: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score ...
def layout_end(layout): """Find the ending token for the layout.""" tok = layout[0] if tok == '{': end = '}' elif tok == '[': end = ']' else: return -1 skip = -1 for i, c in enumerate(layout): if c == end and skip == 0: return i elif c == ...
def create_pipeline_message_text(channel, pipeline): """ Creates a dict that will be sent to send_message for pipeline success or failures """ emote = ":red_circle:" if pipeline.get("state") == "FAILED" else ":white_check_mark:" return { "channel": channel, "text": ( f"{e...
def check_duration_index(cross): """Verify the duration location""" assert len(cross) > 0, \ '(ValueError) Coda fit line does not cross noise threshold' return None
def seq_into_tuple(sequence): """ Extract all repeating motifs. :param sequence: str - motif sequence in ACATCAG,3-TGT,CATCGACT format :return: list(tuple) - motif sequence in list((seq, rep)) format """ modules = sequence.split(',') return [(m.split('-')[-1], 1 if len(m.split('-')) == 1 els...
def patch_metadata(metadata: dict, patch: dict) -> dict: """Replace the fields mentioned in the patch, while leaving others as is. The first argument's content will be changed during the process. """ for key in patch.keys(): val = patch[key] if isinstance(val, dict): patch_m...
def primary_secondary(url): """ return just the secondary.primary domain part, as a single string """ if len(url) >= 2: url_split = url.split('.') url_join = '.'.join(url_split[-2:]) return url_join # To consider: Would a single-length case ever happen? else: return url
def bbcode_content(value): """ Ref. http://code.djangoproject.com/wiki/CookBookTemplateFilterBBCode """ import re pat = re.compile(r'<([^>]*?)>', re.DOTALL | re.M) value = re.sub(pat, '&lt;\\1&gt;', value) bbdata = [ (r'\[url\](.+?)\[/url\]', r'<a href="\1">\1</a>'), ...
def closest_perfect_kth_root(x, k): # x is the number of interest, k is the power """ naive method by KJL """ y = 2 while y <= x: y = y**k if y > x: return y**(1/k) - 1 if y == x: y**(1/k) y = y**(1/k) y += 1
def sum_using_formula(arr, n): """ It works only if array is sequential""" return n * (n + 1) / 2
def setlsb(component, bit): """ Set Least Significant Bit of a colour component. """ return component & ~1 | int(bit)
def append_byte(bytes_array, bytes_add): """Append bytes to a byte array. Parameters: bytes_array (bytes): Byte array bytes_add (bytes): Bytes to be added Returns: bytes: Resulting byte array """ bytes_array += bytes_add return bytes_array
def kind(n, ranks): """Return the card for which there is n-of-a-kind, else return None""" for card in ranks: if ranks.count(card) == n: return card return None
def fib(n): """Returns the nth Fibonacci number. >>> fib(0) 0 >>> fib(1) 1 >>> fib(2) 1 >>> fib(3) 2 >>> fib(4) 3 >>> fib(5) 5 >>> fib(6) 8 >>> fib(100) 354224848179261915075 """ "*** YOUR CODE HERE ***" a = 0 b = 1 # a, b = 0, 1 ...
def round_masses(mass): """ Round all the masses for the output to 8 digits after comma """ if mass == '-': return '-' else: return round(mass, 8)
def _border_trim_slice(n, ps, pstr): """ Helper function for remove_borders. Produce slices to trim t_n pixels along an axis, t_n//2 at the beginning and t_n//2 + t_n%2 at the end. """ t_n = (n - ps) % pstr t_start, t_end = t_n // 2, t_n // 2 + t_n % 2 assert t_start < n - t_end ...
def mapParts(lib, libid): """ Assign a unique index to each part """ cmap = {} for i in range(0, len(lib)): construct = lib[i] try: constructid = libid[i] except: constructid = lib[i] for p in constructid: if p not in cmap: ...
def calculate_job_percentage(total_files, files_finished): """ Do some maths to calculate the job percentage :) Parameters ---------- total_files: int Total number of files for a job files_finished: int Files finished for a job Returns ------- An int representation ...
def reorder(index_list, list_to_reorder): """Curried function to reorder a list according to input indices. Parameters ---------- index_list : list of int The list of indices indicating where to put each element in the input list. list_to_reorder : list The list being reorde...
def escape(orig): """Because Lua hates unescaped backslashes.""" return '"{}"'.format(orig.replace('\\', '\\\\').replace('"', '\\"'))
def check_bucket_valid(bucket): """ Check bucket name whether is legal. :type bucket: string :param bucket: None ======================= :return: **Boolean** """ alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-" if len(bucket) < 3 or len(bucket) > 63: return False ...
def _nollToZernInd(j): """ Authors: Tim van Werkhoven, Jason Saredy See: https://github.com/tvwerkhoven/libtim-py/blob/master/libtim/zern.py """ if (j == 0): raise ValueError("Noll indices start at 1, 0 is invalid.") n = 0 j1 = j-1 while (j1 > n): n += 1 j1 -= n ...
def rchop(s, sub): """Chop ``sub`` off the end of ``s`` if present. >>> rchop("##This is a comment.##", "##") '##This is a comment.' The difference between ``rchop`` and ``s.rstrip`` is that ``rchop`` strips only the exact suffix, while ``s.rstrip`` treats the argument as a set of trailing...
def highlight_text(snippets, article): """Add HTML higlighting around each snippet found in the article.""" for snippet in snippets: try: idx = article.index(snippet) except ValueError: pass else: new_article = ( article[:idx] ...
def _routes_to_set(route_list): """Convert routes to a set that can be diffed. Convert the in-API/in-template routes format to another data type that has the same information content but that is hashable, so we can put routes in a set and perform set operations on them. """ return set(frozenset...
def not_x_or_y(x_or_y, K_sets, on_keys=None): """not tags-any=x_or_y""" s_xy = set(x_or_y) xy_s = [k for k, S in K_sets.items() if (on_keys is None or k in on_keys) and len(S & s_xy) == 0] return xy_s
def is_outlook_msg(content): """ Checks if the given content is a Outlook msg OLE file Args: content: Content to check Returns: bool: A flag the indicates if a file is a Outlook MSG file """ return type(content) == bytes and content.startswith( b"\xD0\xCF\x11\xE0\xA1\xB...
def partition_range(max_range): """partition for milla website in lengths of 3 or 4 >>> partition_range(3) [[0], [1], [2]] >>> partition_range(5) [[0], [1], [2], [3, 4]] >>> partition_range(8) [[0, 1], [2, 3], [4, 5], [6, 7]] >>> partition_range(12) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]] """...
def flattenjson(obj, delim="__"): """ Flattens a JSON object Arguments: obj -- dict or list, the object to be flattened delim -- string, delimiter for sub-fields Returns: The flattened JSON object """ val = {} for i in obj: if isinstance(obj[i], dict): ret =...
def forward_integrate(init: float, delta: float, sampling_time: float) -> float: """ Performs a simple euler integration :param init: initial state :param delta: the rate of chance of the state :return: The result of integration """ return init + delta * sampling_time
def normalize(dict): """ Normalized given dictionary value to [0,1] and sum(dict.values()) = 1 """ total = sum([v for v in dict.values()]) for i, v in dict.items(): dict[i] = v/total return dict
def decode(string): """Decodes a String""" dec_string = string \ .replace('&amp;', '&') \ .replace('&lt;', '<') \ .replace('&gt;', '>') return dec_string
def iseventtask(task): """ Return True if `task` is considered an event task, meaning one that acts on `tkinter` events. Return False otherwise. """ return getattr(task, "next_event", -1) >= 0
def human_to_bytes(size): """ Given a human-readable byte string (e.g. 2G, 30M), return the number of bytes. Will return 0 if the argument has unexpected form. .. versionadded:: 2018.3.0 """ sbytes = size[:-1] unit = size[-1] if sbytes.isdigit(): sbytes = int(sbytes) ...
def is_image_file(filename): """ determines whether the arguments is an image file @param filename: string of the files path @return: a boolean indicating whether the file is an image file """ return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"])
def to_list(data_in): """Convert the data into a list. Does not pack lists into a new one. If your input is, for example, a string or a list of strings, or a tuple filled with strings, you have, in general, a problem: - just iterate through the object will fail because it iterates through the ch...
def extent(shape, offset): """ Compute shifted array extent Parameters ---------- shape : array_like Array shape offset : array_like Array offset Returns ------- rmin, rmax, cmin, cmax : int Indices that define the span of the shifted array. Notes -...
def str_decode(text, coding=None): """Decode bytes to string.""" if isinstance(text, str): return text elif isinstance(text, bytes): if coding: return text.decode(coding) else: return text.decode() else: raise Exception('String decoding error:%s' %...
def do_indent(s, width=4, indentfirst=False): """ {{ s|indent[ width[ indentfirst[ usetab]]] }} Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional par...
def encode_to_bytes(string, encoding="ascii"): """Helper function to encode a string as a bytestring""" if not isinstance(string, bytes): string = string.encode(encoding) return string
def spline_grid_from_range(spline_size, spline_range, round_to=1e-6): """ Compute spline grid spacing from desired one-sided range and the number of activation coefficients. Args: spline_size (odd int): number of spline coefficients spline_range (float): one-side...
def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2...
def green_bold(payload): """ Format payload as green. """ return '\x1b[32;1m{0}\x1b[39;22m'.format(payload)
def to_lists(*args): """Convert to lists of the same length.""" # tuple to array args = list(args) # entries to arrays for ix, arg in enumerate(args): if not isinstance(arg, list): args[ix] = [arg] # get length length = max(len(arg) for arg in args) # broadcast sin...
def format_text_to_float(text): """Returns text after removing and adding characters in order to be casted to a float number. Parameters ---------- text : str the text to be formatted. Returns ------- str a string formatted to be casted to float. """ return text.rep...
def f_x(x, threshold, reld) : """ Function in range 0 to 1, to set soil water and groundwater flow to 0 below a user-specified threshold x: float threshold: f(x) is 0 below this threshold reld: relative "activation distance", the distance from the threshold (as a propor...
def timezones(zone): """This function is used to handle situations of Daylight Saving Time that the standard library can't recognize.""" zones = { "PDT": "PST8PDT", "MDT": "MST7MDT", "EDT": "EST5EDT", "CDT": "CST6CDT", "WAT": "Etc/GMT+1", "ACT": "Australia/ACT", ...
def _get_ws_location(water_surface_elev, zmax, zmin): """ Return one of three values depending on the location of the water surface relative to the elevations of the discretized cross-section points. Vectorized below. Returns: (str) one of the following: 'below' if above zmax (and automatic...
def get_chrom_start_end_from_string(s): """Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}' ...doctest: >>> get_chrom_start_end_from_string('chr01__substr__11838_13838') ('chr01', 11838, 13838) """ try: chrom, s_e = s.split('__substr__') start, ...
def rocks(n): """ >>> rocks(13) 17 >>> rocks(36123011) 277872985 The trick here is to compute correctly the number of the digits from given n E.g, 13 --> there're (13-9)*2 + 9 = 17 digits 100 --> there're (100-99)*3 + (99-9)*2 + 9 So you know the rule """ s = 0 l = len(str(n)) while l > 1: # the trick...
def ke(item): """ Used for sorting names of files. """ if item[0].isdigit(): return int(item.partition(' ')[0]) else: return float('inf')
def initial_state(): """ Set the factory settings for the application. The settings are stored in a dictionary. Returns: An empty dict() """ defstate = dict() return defstate
def solve(input): """find the sum of all digits that match the next digit in the list""" input = [int(c) for c in input] result = 0 previous = input[0] for c in input[1:]: if c == previous: result += c previous = c if previous == input[0]: result += previous # print 'result=' + str(result) return resul...
def verify_new_attending(in_dict): """ This function verifies the input information for post_new_attending() This function receives the dictionary containing the input from the function post_new_attending(). The function uses a for loop to check if the key strings are the same as the expected k...
def strBool(bool_str): """ Take the string "true" or "false" of any case and return a boolean object. """ if bool_str.lower() == "true": return True elif bool_str.lower() == "false": return False else: raise Exception( "argument for strBool must be s...
def pascalcase(var): # SomeVariable """ Pascal case convention. Include an uppercase at every first element. :param var: Variable to transform :type var: :py:class:`list` :returns: **transformed**: (:py:class:`str`) - Transformed input in ``PascalCase`` convention. """ result = ""...
def get_sign(x): """ Returns the sign of x. :param x: A scalar x. :return: The sign of x. """ if x > 0: return +1 elif x < 0: return -1 elif x == 0: return 0
def binary(n): """Returns n in binary form. First while loop finds the largest '1' bit, and the second while loop incrementally fills the lower value bits. """ if n == 0: return 0 ans = '1' a = 0 while n - (2 ** a) >= 0: a += 1 a -= 2 n -= (2 ** (a+1)) while a ...
def gf_sub_const(f, a, p): """Returns f - a where f in GF(p)[x] and a in GF(p). """ if not f: a = -a % p else: a = (f[-1] - a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a]
def generate_numbers(limit): """ @param: limit - length of the sequence of natural numbers to be generated @return: list_of_numbers - list of the generated sequence """ if limit <= 0: raise ValueError('Invalid limit specified') list_of_numbers = list() for...
def remove_brackets(list1): """Remove brackets from text""" return str(list1).replace('[','').replace(']','')
def format_seconds(seconds): """Convert seconds to a formatted string Convert seconds: 3661 To formatted: " 1:01:01" """ hours = seconds // 3600 minutes = seconds % 3600 // 60 seconds = seconds % 60 return "{:4d}:{:02d}:{:02d}".format(hours, minutes, seconds)
def get_amazon_link(product_id: str, page: int) -> str: """ Generates an amazon review link for the following parameters :param product_id: unique id of the product :param page: review page number :return: amazon review page without any filter """ result = ( "https://www.amazon.com/-...
def summy(string_of_ints): """This function takes a string of numbers with spaces and returns the sum of the numbers.""" numbers = string_of_ints.split() answer = 0 for i in numbers: answer = answer + int(i) return answer
def prim_value(row): """Extract primary key value from DAS record""" prim_key = row['das']['primary_key'] key, att = prim_key.split('.') if isinstance(row[key], list): for item in row[key]: if item.has_key(att): return item[att] else: return row[key][att...
def lineIntersectLine(x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float): """Checks if line from `x1, y1` to `x2, y2` intersects line from `x3, y3` to `x4, y4`""" divisorA = ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)) divisorB = ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)) if divisor...
def createLemexes(key_list): """ :return str: in the format of {x, y, z} from input of key_list """ return '{' + ', '.join(key_list) + '}'
def convert_humidity(h): """Eliminate % from text so you can cast as int""" return h.replace('%', '')
def frequency_map(text, k): """[computes the frequency map of a given string text and integer k, returns a dictionary of each supplied k-mer value] Args: text ([string]): [input string] k ([int]): [determine length of kmer] Returns: [dict]: [for every length of kmer specifi...
def constrained_path(path): """Remove all '..' occurrences from specified path. It is used to ensure all artifact paths are constrained to remain under temporary artifact directory.""" return path.replace('..', '')
def properties_predicted(body): """ Callback function which work when properties prediction success :param body: MassTransit message """ global CLASSIC_CLASSIFICATION_PREDICTED_FLAG CLASSIC_CLASSIFICATION_PREDICTED_FLAG = True return None
def clip(val): """Standard clamping of a value into a fixed range (in this case -4.0 to 4.0) Parameters ---------- val: float The value to be clamped. Returns ------- The clamped value, now fixed to be in the range -4.0 to 4.0. """ if val > 4.0: return 4.0 e...
def _create_axis(axis_type, variation="Linear", title=None): """ Creates a 2d or 3d axis. :params axis_type: 2d or 3d axis :params variation: axis type (log, line, linear, etc) :parmas title: axis title :returns: plotly axis dictionnary """ if axis_type not in ["3d", "2d"]: ret...
def is_rgb_color(v): """Checks, if the passed value is an item that could be converted to a RGB color. """ try: if hasattr(v, "r") and hasattr(v, "g") and hasattr(v, "b"): if 0 <= int(v.r) <= 255 and 0 <= int(v.g) <= 255 and \ 0 <= v.b <= 255: retu...
def replace_name_with_derivedColumnNames(original_name, derived_col_names): """ It replace the default names with the names of the attributes. Parameters ---------- original_name : List The name of the node retrieve from model derived_col_names : List The name of the derived attribu...
def app_path(value): """ Return the app path (remove path) :param value: :return: """ splitted = value.split('/') return '/'.join(splitted[3:])
def equal(fst, snd) -> bool: """Returns if files are equal by calculating their hash""" return hash(fst) == hash(snd)
def k2s(**kwargs) -> str: """Maps multiple arguments to a string. Needed since gui labels need to be strings. """ return ", ".join([f"{key}={value}" for key, value in kwargs.items()])
def is_int(val): """ Determines whether the specified string represents an integer. Returns True if it can be represented as an integer, or False otherwise. """ try: int(val) return True except ValueError: return False
def get_digit_prefix(characters): """ Get the digit prefix from a given list of characters. :param characters: A list of characters. :returns: An integer number (defaults to zero). Used by :func:`compare_strings()` as part of the implementation of :func:`~deb_pkg_tools.version.compare_versions...
def blockify(text, blocklen): """Splits data as a list of `blocklen`-long values""" return [text[i:i + blocklen] for i in range(0, len(text), blocklen)]
def get_enzyme_reactions(eid, db): """ For a given ec number return associated reaction ids :param eid: enzyme id format "EC-x.x.x.x" :param db: database dict :return: """ erids = [] if eid[:3] != "EC-": eid = "EC-{}".format(eid) for rid, react in db['reactions'].items(): ...
def get_value_from_dict_safe(d, key, default=None): """ get the value from dict args: d: {dict} key: {a hashable key, or a list of hashable key} if key is a list, then it can be assumed the d is a nested dict default: return value if the key is not reachable, default is N...
def fuzzy_string_find(string, pattern, pattern_divisor=10, min_portion=2): """ Finds the pattern in string by only looking at the first and last portions of pattern """ pattern_length = len(pattern.split()) portion = max(pattern_length//pattern_divisor, min_portion) first_portion = pattern.sp...
def FormatTag(key, value): """Format an individual tag for use with the --tags param of Azure CLI.""" return '{0}={1}'.format(key, value)
def _convert_dict_to_list(d): """This is to convert a Python dictionary to a list, where each list item is a dict with `name` and `value` keys. """ if not isinstance(d, dict): raise TypeError("The input parameter `d` is not a dict.") env_list = [] for k, v in d.items(): env_list...
def number_similarity(num1,num2): """ :param num1: :param num2: :return: """ count = 0 for x, y in zip(str(num1), str(num2)): if x == y: count = count + 1 total = max(len(str(num1)), len(str(num1))) return count/float(total)
def get_chunk_type(tok): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ tok_split = tok.split("-") return tok_split[0], tok_split[-1]
def _isEmpty(number): """ Simple private method to check if a variable (list) is empty. It returns a boolean evaluation. """ return (number == [] or number == '')
def _to_json_dict_with_strings(dictionary): """ Convert dict to dict with leafs only being strings. So it recursively makes keys to strings if they are not dictionaries. Use case: - saving dictionary of tensors (convert the tensors to strins!) - saving arguments from script (e.g. argpar...