content
stringlengths
42
6.51k
def stringify(lst): """ Joins list elements to one string. :param lst: list. List of strings. :return: string. Joined list of strings to one string. """ return ''.join(str(x) for x in lst)
def fix_line_ending(content): """Fix line ending of `content` by changing it to \n. :param bytes content: content of the subtitle. :return: the content with fixed line endings. :rtype: bytes """ return content.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
def _encoded_string(s): """Encode the string-like argument as bytes if suitable""" return s.encode('ascii') if hasattr(s, 'encode') else s
def tupleToList(tupleTo): """ tupleToList(...) method of tupleo.tuple instance T.tupleToList(tupleTo) -> None -- convert tuple to List to Full Depth Level. """ if type(tupleTo)==tuple: tupleTo = list(tupleTo) for i in range(len(tupleTo)): if type(tupleTo[i])==tuple: t...
def parentLevel(parentOp, childOp): """ determines if op1 is a parent of op2 at any depth. Returns None or the depth of parenthood. i.e. op2.parent(returnValue) will yield op1. This method returns None so that op2.parent(returnValue) will error in that case. """ if parentOp == childOp: return 0 parentLev = 1 ...
def coord_list_to_svg_path(coord_list): """ Turn a list of points into an SVG path """ path = '' #'M 0,0 '# % (coord_list[0]['coord'].x, coord_list[0]['coord'].y) last_action_type = '' for action in coord_list: if action['type'] == 'move': if last_action_type != 'M': ...
def fasta_to_sequence(fasta): """ Convert a multiline fasta sequence to one line sequence""" f = fasta.strip().split("\n") if len(f) > 0: return "".join(f[1:]) else: return ""
def pg_info(link): """Populate page test info :param link: url for page being tested as String :return: object containing information for page being tested """ page_info = { 'tag': 'response', 'url': link, 'title': 'Not tested', 'http status': '---', ...
def format_row(row): """ Transforms [1, 2, 3] -> 1 2 3 """ return " ".join(str(i) for i in row)
def centroid(points): """ Compute the centroid (average lat and lon) from a set of points ((lat,lon) pairs). """ lat_avg = sum([p[0] for p in points]) / len(points) lon_avg = sum([p[1] for p in points]) / len(points) return (lat_avg, lon_avg)
def find_non_sep_position(text, norm_position, norm_sep="|", morph_sep="-"): """ Finds the actual position of character n in a string, such that n is the number of characters traversed excluding separator characters :param text: the text to search for a position in :param norm_position: position ignoring separato...
def find_span_linear(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of a single knot over the knot vector using linear search. Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param k...
def CalculateForecastStats(matched, available, possible=None): """Calculate forecast percentage stats. Args: matched: The number of matched impressions. available: The number of available impressions. possible: The optional number of possible impressions. Returns: The percentage of impressions t...
def is_balanced_int(root): """Check if balanced.""" if root is None: return 0 left = is_balanced_int(root.left) right = is_balanced_int(root.right) if left < 0 or right < 0 or abs(left - right) > 1: return -1 return max((left, right)) + 1
def levenshtein(a, b): """Calculates the Levenshtein distance between a and b.""" n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a, b = b, a n, m = m, n current = range(n + 1) for i in range(1, m + 1): previous, current = current, [i] + ...
def piece_not(piece: str) -> str: """ helper function to return the other game piece that is not the current game piece Preconditions: - piece in {'x', 'o'} >>> piece_not('x') 'o' >>> piece_not('o') 'x' """ return 'x' if piece == 'o' else 'o'
def generate_org_data(org_name, first_name, last_name, email, capabilities): """ generate_org_data(org_name, first_name, last_name, email, capabilities) Generates org create data from inputs and returns org data object. """ capability_name_list = [] for capability in capabilities: capabi...
def fib(n): """ Finding the Fibonacci sequence with seeds of 0 and 1 The sequence is 0,1,1,2,3,5,8,13,..., where the recursive relation is fib(n) = fib(n-1) + fib(n-2) :param n: the index, starting from 0 :return: the sequence """ n = n//1 if n>=1 else 0 # ensure n is non-negative integer if n>1: ...
def array_unique(l): """ Removes all duplicates from `l`. """ return list(set(l))
def parse_arb_id(arb_id: int): """Return IDH and IDL.""" return divmod(arb_id, 0x100)
def is_sphinx_markup(docstring): """Returns whether a string contains Sphinx-style ReST markup.""" # this could be made much more clever return ("`" in docstring or "::" in docstring)
def government_furloughing(t, states, param, t_start_compensation, t_end_compensation, b_s): """ A function to simulate reimbursement of a fraction b of the income loss by policymakers (f.i. as social benefits, or "tijdelijke werkloosheid") Parameters ---------- t : pd.timestamp current dat...
def iupac_converter(iupac_code): """ Return a list of all possible bases corresponding to a given iupac nucleotide code. """ iupac_dict = {"A": "A", "C": "C", "G": "G", "T": "T", "R": "AG", "Y": "CT", "S": "GC", "W": "AT", "K": "GT", "M": "AC", "B": "CGT", "D": "A...
def file_sorting_key(filename): """ Extract a key for a filename sort, putting JPEGs before everything else. """ extension = filename.lower()[filename.rfind(".") + 1 :] key = 0 if extension in ("jpg", "jpeg") else 1 return (key, filename)
def _force_float(v): """ Converts given argument to float. On fail logs warning and returns 0.0. Args: v (any): value to convert to float Returns: float: converted v or 0.0 if conversion failed. """ try: return float(v) except Exception as exc: return float('na...
def mean(values): """Compute the mean of a sequence of numbers.""" return sum(values) / len(values)
def lucas(n, elem): """A simple function to print lucas series of n-numbers""" # check if n is correct # we can only allow n >=3 and n as an integer number # since we always expect user to provide two elements # these two elements will be the starting number of the series try: n = int(n...
def get_current_role(line: str, column: int, default: str = "any"): """ Parse current line with cursor position to get current role. Valid roles: - :role:`target` - :role:`Text <target>` - :domain:role:`target` - :domain:one:two:`target` Default role: - `Foo` - `Foo <bar>` ...
def fds_crc(data, checksum=0x8000): """ Do not include any existing checksum, not even the blank checksums 00 00 or FF FF. The formula will automatically count 2 0x00 bytes without the programmer adding them manually. Also, do not include the gap terminator (0x80) in the data. If you wish to do so, ...
def dict_to_arg_flags_str(flags_dict): """ Converts a dictionary to a commandline arguments string in the format '--<key0>=value0 --<key1>=value1 ...' """ return ' '.join( ['--{}={}'.format(k, flags_dict[k]) for k in flags_dict.keys()])
def debian_number(major='0', minor='0', patch='0', build='0'): """Generate a Debian package version number from components.""" return "{}.{}.{}-{}".format(major, minor, patch, build)
def _validate_tag(string): """ Extracts a single tag in key[=value] format """ result = {} if string: comps = string.split('=', 1) result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''} return result
def postorder(root): """Postorder depth-first traverse a binary tree.""" ans = [] node, stack = root, [] prev = None while node or stack: if node: stack.append(node) node = node.left else: node = stack[-1] if node.right and node.ri...
def fix_resource(first_resource, resource): """Use the first resource to fill in other resources. """ for property_ in first_resource.keys(): if not resource.get(property_): resource[property_] = first_resource[property_] return resource
def toggle_modal_tab(n1, n2, is_open): """ :return: Open modal callback if user clicks tab 2 description button on tab 2. """ if n1 or n2: return not is_open return is_open
def atf_fc_uri(article_uri): """URI of feature collection""" return article_uri+"/featurecollection"
def unpickle(factory, args, kwargs): """Unpickle something by calling a factory""" return factory(*args, **kwargs)
def _calc_input_panel_rect(panel_size, input_width): """ Calc rectangle of the panel image for inputting to neural network model. Because panel image isn't square but neural network model postulate square :param panel_size: size of source panel image [width, height] :param input_width: width of inpu...
def get_aton(mmsi: str) -> bool: """ Gets the AIS Aids to Navigation (AtoN) status of a given MMSI. AIS Aids to Navigation (AtoN): AIS used as an aid to navigation uses the format 9192M3I4D5X6X7X8X9 where the digits 3, 4 and 5 represent the MID and X is any figure from 0 to 9. In th...
def int_string(string_list): """ This absolutely assumed everything is int parseable """ return [int(x) for x in string_list]
def get_excluded_classes(std_class_names, config_dict, cazy_dict): """Define the CAZy classes that will not be scraped. This includes classes for which not Families have been specified for scraping. :param std_class_names: list of standardised CAZy class names :param config_dict: configuration dict de...
def raises_keyerr(k, m): """ Determine whether a mapping is missing a particular key. This helper is useful for explicitly routing execution through __getitem__ rather than using the __contains__ implementation. :param object k: the key to check for status as missing :param Mapping m: the key-...
def check_for_null(array): """ check for null string values in array """ while "" in array: array.remove("") if "" in array else array return array
def bytes_to_int(b: bytes) -> int: """ Convert bytes to an int, with hardcoded Endianness. """ return int.from_bytes(b, "little")
def allowed_transitions(states): """ this function takes a set of states and uses it to compute the allowed transitions it assumes the model is acyclic ie. individuals can only transition towards states to the right of it in the list Parameters ---------- states : list a list with t...
def coerce_value(val): """ Coerce config variables to proper types """ def isnumeric(val): try: float(val) return True except ValueError: return False if isnumeric(val): try: return int(val) except ValueError: ...
def strip_data(data): """ retire les blancs et les retour chariot""" b=data.replace('\n',' ').replace('\t',' ').strip().replace(' ',' ') c=b.replace(' ',' ') while (b != c): b=c c=b.replace(' ',' ') pass return b
def recursive_string_interpolation(string, obj, max_depth=5): """Recursively perform string interpolation.""" for iteration in range(max_depth): previous_string = string string = string % obj if string == previous_string: break return string
def _nih_segmented(h, grouping=6): """Segment hex-hash with dashes in nih style RFC6920_ >>> _nih_segmented("0123456789abcdef") "012345-6789ab-cdef" .. _RFC6920: https://www.ietf.org/rfc/rfc6920 """ segmented = [] while h: segmented.append(h[:grouping]) h = h[grouping:] ...
def promotion_from_piecetype(piecetype): """ get piece type char from numeric piecetype """ piecetypes = {1: 'n', 2: 'b', 3: 'r', 4: 'q'} return piecetypes[piecetype]
def chiSquare(observed, expected): """takes in a list of numbers, the observed and expected values and outputs the chi-square value""" total = 0 for i in range(len(observed)): total += (((observed[i] - expected[i])**2)/expected[i]) return total
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) <...
def col_map_from_header(header_str): """ create column map that maps column names to column numbers from a csv string """ col_map = {} header_fields = header_str.rstrip().split(","); for i,field in enumerate(header_fields): col_map[field] = i return col_map
def parse_derivative_info(dstring): """ Input: string: string of the form *,*x,*y,*xx, *xy, *yx, *yy, where * stands for any letter. Output: tuple, encoding derivative information """ # Return tuples if type(dstring) is tuple: ...
def increment_list(a_list, index): """Increment the last integer in a list, then and appends it. Adds index+1 if list list is empty""" if len(a_list) == 0: a_list.append(index + 1) else: last_index = a_list[-1] a_list.append(last_index + 1) return a_list
def get_sma(data, length): """ Returns the simple moving average over a period of LENGTH """ if len(data) < length: return "Not enough Data" subset = data[-length:] return sum(subset) / len(subset)
def same_first_last(L: list) -> bool: """Precondition: len(L) >= 2 Return True if and only if first item of the list is the same as the last. >>> same_first_last([3, 4, 2, 8, 3]) True >>> same_first_last(['apple', 'banana', 'pear']) False >>> same_first_last([4.0, 4.5]) False """...
def twos_comp(val, num_bits): """compute the 2's compliment of int value val""" if( (val&(1<<(num_bits-1))) != 0 ): val = val - (1<<num_bits) return val
def maximize_tbreaks(tbreaks): """Remove tbreaks that are non-maximal. i.e. remove tbreaks that are subsets of other tbreaks.""" subsets = set() for tb1 in tbreaks: for tb2 in tbreaks: if tb1 < tb2: subsets.add(tb1) tb1.discard() break ...
def split_indices(l,lookup): """Return two lists, within and without. within contains the indices of all elements of l that are in lookup, while without contains the remaining elements of l.""" within,without = [],[] for (i,v) in enumerate(l): try: ind = lookup.index(v) ...
def class_ioerror(log): """An error classifier. log the console log text Return None if not recognized, else the error type string. """ if ('ext3_abort called' in log and 'Read-only file system' not in log and 'Remounting filesystem read-only' not in log): retur...
def bracketIP6(ip): """Put brackets around an IPv6 address, just as tor does.""" return "[%s]" % ip
def breaklines(text, char_limit=60): """ Break text into lines so none is loner than char_limit. """ settext = [] for par in text.split("\n"): chunk = [] chunk_len = 0 for word in par.split(" "): if len(word) + chunk_len > char_limit: settext.appen...
def bytesto(bytes, to: str, bsize: int = 1024) -> float: """Takes bytes and returns value convereted to `to`""" a = {"k": 1, "m": 2, "g": 3, "t": 4, "p": 5, "e": 6} r = float(bytes) return bytes / (bsize ** a[to])
def compare_solutions_list(dict_1, dict_2, keys, info={}): """Compare solutions returning a list of dictionaries for each key""" return [{**info, **{'key': k, 'model': dict_1[k], 'actual': float(dict_2[k])}} for k in keys if k in dict_1.keys()]
def convert_to_bytes(mem_str): """Convert a memory specification, potentially with M or G, into bytes. """ if str(mem_str)[-1].upper().endswith("G"): return int(round(float(mem_str[:-1]) * 1024 * 1024)) elif str(mem_str)[-1].upper().endswith("M"): return int(round(float(mem_str[:-1]) * 1...
def build_success_api_response(returnEntity): """Return a formatted API response.""" # type: (dict[str, str], str) -> dict[str, dict[str, str]] return { "apiResponse" : returnEntity }
def leap_year(year): """ Given a year, report if it is a leap year. :param year int - The year to check :return bool - Leap year or not. On every year that is evenly divisible by 4 except every year that is evenly divisible by 100 unless the year is also evenly divisible by 400 For example, 1997 is...
def JavaDataTypeToC(java_type): """Returns a C datatype for the given java type.""" java_pod_type_map = { 'int': 'jint', 'byte': 'jbyte', 'char': 'jchar', 'short': 'jshort', 'boolean': 'jboolean', 'long': 'jlong', 'double': 'jdouble', 'float': 'jfloat', } java_typ...
def closestNode(coord,points): """Return closest point to coord from points""" dists = [(pow(point[0] - coord[0], 2) + pow(point[1] - coord[1], 2), point) for point in points] # list of (dist, point) tuples nearest = min(dists) return nearest[1]
def is_valid_matrix2D(lst): """ Checks if there is at least one positive value in the given 2 dimensional list. :param lst: list of elements :return: True if at least one positive value exist otherwise false. """ sz = len(lst[0]) for i in range(0, sz): for j in range(0, sz): ...
def b_edge_reversed(s, initial, initial_reversed): """ If a b-edge can be validly reversed, return the result of the reversal. Otherwise, return None. """ # precondition for validity: if s.startswith('B') and (s.endswith('B') or s.endswith(initial) or s.endswith(initial_reversed)): s2 = ...
def relativedatapath(datapath): """ relative data path :param datapath: :return: """ return 'data/' + datapath
def average(input): """ Returns a list with a running average of input The running average is a list with the same size as the input. Each element at position n is the average of all of the elements in input[:n+1] Example: average([1, 3, 5, 7]) returns [1.0, 2.0, 3.0, 4.0] Parameter ...
def as_range(positions): """ Given a list of positions, merge them into intervals if possible """ l = list(positions) if len(l) > 1: return '{0}-{1}'.format(l[0], l[-1]) else: return '{0}'.format(l[0])
def fn_k2_TE(h_11,c_11,beta_11): """EM coupling factor k^2 for thickness expander mode, as function of: -- piezoelectric tensor component h_11 -- elastic stiffness tensor component c_11 -- impermittivity tensor component beta_11. """ return h_11**2 / (c_11 * beta_11)
def smartJoin(words): """ Joins list of words with spaces, but is smart about not adding spaces before commas. """ input = " ".join(words) # replace " , " with ", " input = input.replace(" , ", ", ") # replace " ( " with " (" input = input.replace("( ", "(") # replace " ) " w...
def linearized_best_response(y): """A linearization of the best-response of the weights to some hyperparameter at some point. :param y: The hyperparameter to evaluate the linearization at. :return: The linearized best-response. """ return -1.0*y + 0.0
def check_stat_type(stat_list: list) -> bool: """check that all the statistics are numerical""" stat_input_error = False for stat in stat_list: try: # Tries to convert the input into float # (string type input containing numeric character does not cause errors) ...
def get_val(dic, key, default=None): """ Traverse through the levels of a dictionary to obtain the specified key, safely handling any missing levels. For example, if the key is "app.error", it will find the "error" entry in the "app" dictionary; if either the app dictionary or the error entry is mi...
def get_range(value, max_num=None): """ Returns the range over a given value. Usage:: {% load libs_tags %} {% for item in object_list.count|get_range %} {{ item }} // render real items here {% endfor %} {% for item in object_list.count|get_range:5 %} ...
def str_sized(string: str, lenth: int, end: str = ' ') -> str: """Cuts off a long string to conform with `lenth`, replace the end of the string with `end` if provided. Args: string (str): the string to format lenth (int): the max lenth of the string end (str): replace the end of the cut...
def get_shared_content_cache_key_ptr(site_id, slug, language_code): """ Get the rendering cache key for a sharedcontent block. This key is an indirection for the actual cache key, which is based on the object ID and parent ID. """ return "sharedcontent_key.{0}.{1}.{2}".format(site_id, slug, lan...
def strip_byte_order_prefix(string, prefix_chars='<>|='): """ >>> from comma.numpy import strip_byte_order_prefix >>> strip_byte_order_prefix('<f8') 'f8' """ return string[1:] if string.startswith(tuple(prefix_chars)) else string
def regular_polygon_area(perimeter, apothem): """Returns the area of a regular polygon""" perimeter = float(perimeter) apothem = float(apothem) if (perimeter < 0.0 or apothem < 0.0): raise ValueError('Negative numbers are not allowed') return perimeter * apothem / 2
def num_states(spin_str_element): """ This function evaluates de spin number string, formatted as s=a/b and returns the number of states 2*s + 1. In the table we have three type of strings: 1. spin numbers integers formatted with 1 or 2 characters, e.g s=1, and s=10. 2. spin numbers formatted ...
def foo(arg): """The World is Yours""" return arg.format(123)
def html_attrs_tuple_to_string(attrs): """Converts a set of HTML attributes tuple to an HTML string. Converts all HTML attributes returned by :py:meth:`html.parser.HTMLParser.handle_starttag` ``attrs`` value into their original HTML representation. Args: attrs (list): List of attributes, e...
def parsenext(string,delimiter): """ Returns all text from the start of the input string up to the occurence of the delimiter.""" delimlen=len(delimiter) i=0 strlen=len(string) while(i<strlen): if string[i:i+delimlen]==delimiter: break i+=1 return string...
def _pyval_field_major_to_node_major(keys, values, depth): """Regroup each field (k, v) from dict-of-list to list-of-dict. Given a "field-major" encoding of the StructuredTensor (which maps each key to a single nested list containing the values for all structs), return a corresponding "node-major" encoding, co...
def hours_to_minutes( hours: str ) -> int: """Converts hours to minutes.""" return int(hours)*60
def to_list(raw: str) -> list: """If the `raw` string is formatted like a list, it is converted to a list, otherwise returns a list with `raw` as the single item. """ raw = raw.strip() retval = [] if raw[0] == '[' and raw[-1] == ']': for item in raw[1:-1].split(','): retval ...
def getsteps(num_of_steps, limit): """ Helper function for display_percent_done """ steps = [] current = 0.0 for i in range(0, num_of_steps): if i == num_of_steps-1: steps.append(int(round(limit))) else: steps.append(int(round(current))) current +=...
def humanize_megabytes(mb): """ Express a number of megabytes in the most suitable unit (e.g. gigabytes or terabytes). """ if not mb: return '' if mb >= 1048576: return f'{int(mb / 1048576)} TB' if mb >= 1024: return f'{int(mb / 1024)} GB' return f'{mb} MB'
def aoi_from_latlon(ylat, xlong): """ Example: lat = 38.459702 long = -122.438332 aoi = aoi_from_latlon(lat, long) """ # Intent is for an AOI of a single pixel # Approx 12 cm, ie <1m dx = 0.000001 dy = 0.000001 aoi = { "type": "Polygon", "coordin...
def lineTextAnalyzis(line): """ :rtype: object """ values = line.split("\t") if len(values) == 4: vocabulary = values[0] meaning = values[1] types = values[2] tags = values[3] return vocabulary, meaning, types, tags else: return None
def _check_valid_type_dict(payload): """_check_valid_type_dict checks whether a dict is a correct serialization of a type Args: payload(dict) """ if not isinstance(payload, dict) or len(payload) != 1: return False for type_name in payload: if not isinstance(payload[type_name], dict): retu...
def alpha_to_index(char): """Takes a single character and converts it to a number where A=0""" translator = { "A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S...
def git_pattern_handle_blanks(git_pattern: str) -> str: """ Trailing spaces are ignored unless they are quoted with backslash ("\"). in fact all spaces in gitignore CAN be escaped it is not clear if they NEED to be escaped, but it seems like ! see: https://stackoverflow.com/questions/1021365...
def heron(a): """Calculates the square root of a""" eps = 0.0000001 old = 1 new = 1 while True: old,new = new, (new + a/new) / 2.0 print(old, new) if abs(new - old) < eps: break return new